STRING-FUNCTIONS

PHP String Functions :

Get The Length of a String:

The PHP strlen() function returns the length of a string (number of characters).

The example below returns the length of the string “Hello world!”:

<?php
echo strlen(“Hello world!”); // outputs 12
?>

Output:

12

Count The Number of Words in a String

The PHP str_word_count() function counts the number of words in a string:

<?php
echo str_word_count(“Hello world!”); // outputs 2
?>

Output :

2

Reverse a String

The PHP strrev() function reverses a string:

<?php
echo strrev(“Hello world!”); // outputs !dlrow olleH
?>

Output:

!dlrow olleH

Search For a Specific Text Within a String

The PHP strpos() function searches for a specific text within a string.

If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

The example below searches for the text “world” in the string “Hello world!”:

<?php
echo strpos(“Hello world!”, “world”); // outputs 6
?>

Output:

6

Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters in a string.

The example below replaces the text “world” with “Dolly”:

<?php
echo str_replace(“world”, “Dolly”, “Hello world!”); // outputs Hello Dolly!
?>

Hello Dolly!

========

use PHP stristr function to match the beginning of a string:

============

<?php
$pageURL = $_SERVER[‘REQUEST_URI’];
$myurl = ‘om.php’;

if (stristr($pageURL, $myurl) !== FALSE) {
echo ‘ alert(“it is popup”) ‘;
} else {
echo “wrong”;
}

?>
note : when you will run above it will alert you with popup window ..

The substr() function returns a part of a string.

Note: If the start parameter is a negative number and length is less than or equal to start, length becomes 0.

Syntax:

Substr(String,Start,Length)

Example:

(1)write code for substr.html(enter digit “123” ) :

<form action=substr.php method=post>

enter your 3 digit number<input type=text name=number>

<input type=submit name=submit value=submit>

</form>

(2)write code for substr.php :

<?php

$a=$_POST[‘number’];

$b=substr($a,0,1);

$c=substr($a,1,1);

$d=substr($a,2,1);

echo “value of b=”.$b.'<Br>’;

echo “value of c=”.$c.'<br>’;

echo “value of d=”.$d.'<br>’;

echo $b+$d;

?>

output:

1

2

3

4

=========

Simple PHP Application to save website content from a website to a file then make search to that file:

Step 1: store website content to a file code given below :

<?php

$curl_handle=curl_init();

 

curl_setopt($curl_handle,CURLOPT_URL,’http://www.vissicomp.com&#8217;);

 

curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);

 

curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);

 

$buffer = curl_exec($curl_handle);

 

$fhandle=fopen(“example.txt”,”a”);

fwrite($fhandle,$buffer);

 

curl_close($curl_handle);

 

if (empty($buffer))

{

print “Nothing returned from url.<p>”;

}

 

else

{

print $buffer;

}

?>

Step 2 make Search in that file for particular word:

(a)write code for search.html:

<form action=searchst.php method=post>

<input type=text name=search>

<input type=submit name=submit value=submit>

</form>

(b)write code for searchst.php file:

<?php

$search = $_POST[‘search’];

// Read from file

$lines = file(‘example.txt’);

foreach($lines as $line)

{

// Check if the line contains the string we’re looking for, and print if it does

if(strpos($line, $search) !== false)

echo”<html><title>SEARCH RESULTS FOR: $search</title><font face=’Arial’> $line <hr>”;

}

?>

========

PHP FORM HANDLING :

The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP – A Simple HTML Form

The example below displays a simple HTML form with two input fields and a submit button:

Example

<html>

<body>

<form action=”welcome.php” method=”post”>

Name: <input type=”text” name=”name”><br>

E-mail: <input type=”text” name=”email”><br>

<input type=”submit”>

</form>

</body>

</html>

When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named “welcome.php”. The form data is sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The “welcome.php” looks like this:

<html>

<body>

Welcome <?php echo $_POST[“name”]; ?><br>

Your email address is: <?php echo $_POST[“email”]; ?>

</body>

</html>

The output could be something like this:

Welcome John

Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:

Example

<html>

<body>

<form action=”welcome_get.php” method=”get”>

Name: <input type=”text” name=”name”><br>

E-mail: <input type=”text” name=”email”><br>

<input type=”submit”>

</form>

</body>

</html>

and “welcome_get.php” looks like this:

<html>

<body>

Welcome <?php echo $_GET[“name”]; ?><br>

Your email address is: <?php echo $_GET[“email”]; ?>

</body>

</html>

The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.

Think SECURITY when processing PHP forms!

This page does not contain any form validation, it just shows how you can send and retrieve form data.

However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to protect your form from hackers and spammers!

GET vs. POST

Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, …)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.

Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

PHP FORM VALIDATION USING JAVASCRIPT :


<html>
<head>
<title>
Simple Client Side Validation
</title>

function valid()
{

if(myform.name.value==””)
{

alert(“enter your name”);

return false;

document.myform.name.focus();
}

if(myform.contact.value==””)
{
alert(“enter your contact”);
return false;
document.myform.contact.focus();
}
if(isNaN(myform.contact.value))
{

alert(“enter numeric value in contact”);
return false;
document.myform.contact.focus();
}

if(myform.city.value==””)
{

alert(“enter your city”);

return false;

document.myform.city.focus();

}

if(myform.email.value==””)
{

alert(“enter your email”);

document.myform.email.focus();

return false;

}

if(myform.address.value==””)
{

alert(“enter your address”);

document.myform.address.focus();

return false;

}

var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(!myform.email.value.match(mailformat))

{
alert(“You have entered an invalid email address!”);
document.myform.email.focus();
return false;
}

return true;
}

</head>
<body>
<form name=”myform” action=”submit.php” method=”post” onsubmit=”return(valid());” >
Name <input type=”text” name=”name” >
contact<input type=”text” name=”contact”>
city<input type=text name=”city”>
email<input type=text name=”email”>
address<input type=text name=”address””>
<input type=submit name=submit>
</form>
</body>
</html>

FORM VALIDATION USING PHP :

(1)first write code for “form.html” file.

<form action=”validation.php” method=”post”>

Name <input type=”text” name=”name”>

Contact <input type=”text” name=”contact”>

Email <input type=”text” name=”email”>

<input type=”submit” name=”submit” value=”submit” >

</form>

(2)WRITE CODE FOR “validation.php” file:

<?php

$msg=array();

if(empty($_POST[’email’]))

{

$msg=”enter your email”;

}

$regex = “^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$^”;

if(!preg_match( $regex, $_POST[’email’] ))

{

$msg=”enter your valid email”;

}

if(empty($_POST[‘contact’]))

{

$msg=”enter your contact”;

}

if(strlen($_POST[‘contact’])>10)

{

$msg=”accept only 10 digit”;

}

if(!is_numeric($_POST[‘contact’]))

{

$msg=”accept only numbers only”;

}

if(empty($_POST[‘name’]))

{

$msg=”enter your name”;

}

if(empty($msg))

{

echo “successful”;

}

else

{

echo $msg;

}

?>

From Validation to Prevent SQL Injection Attack :

<html>

<head>

<style>

.error {color: #FF0000;}

</style>

</head>

<body>

<?php

// define variables and set to empty values

$nameErr = $emailErr = $genderErr = $websiteErr = “”;

$name = $email = $gender = $class = $course = $subject = “”;

if ($_SERVER[“REQUEST_METHOD”] == “POST”) {

if (empty($_POST[“name”])) {

$nameErr = “Name is required”;

}

else

{

$name = test_input($_POST[“name”]);

}

if (empty($_POST[“email”])) {

$emailErr = “Email is required”;

}

else

{

$email = test_input($_POST[“email”]);

// check if e-mail address is well-formed

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$emailErr = “Invalid email format”;

}

}

if (empty($_POST[“course”])) {

$course = “”;

}

else

{

$course = test_input($_POST[“course”]);

}

if (empty($_POST[“class”])) {

$class = “”;

}

else

{

$class = test_input($_POST[“class”]);

}

if (empty($_POST[“gender”])) {

$genderErr = “Gender is required”;

}

else

{

$gender = test_input($_POST[“gender”]);

}

if (empty($_POST[“subject”])) {

$subjectErr = “You must select 1 or more”;

}

else

{

$subject = $_POST[“subject”];

}

}

function test_input($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

}

?>

<h2>Absolute classes registration</h2>

<p><span class=”error”>* required field.</span></p>

<form method=”POST” action=”<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”>

<table>

<tr>

<td>Name:</td>

<td><input type=”text” name=”name”>

<span class=”error”>* <?php echo $nameErr;?></span>

</td>

</tr>

<tr>

<td>E-mail: </td>

<td><input type=”text” name=”email”>

<span class=”error”>* <?php echo $emailErr;?></span>

</td>

</tr>

<tr>

<td>Time:</td>

<td> <input type=”text” name=”course”>

<span class=”error”><?php echo $websiteErr;?></span>

</td>

</tr>

<tr>

<td>Classes:</td>

<td> <textarea name=”class” rows=”5″ cols=”40″></textarea></td>

</tr>

<tr>

<td>Gender:</td>

<td>

<input type=”radio” name=”gender” value=”female”>Female

<input type=”radio” name=”gender” value=”male”>Male

<span class=”error”>* <?php echo $genderErr;?></span>

</td>

</tr>

<tr>

<td>Select:</td>

<td>

<select name=”subject[]” size=”4″ multiple>

<option value=”Android”>Android</option>

<option value=”Java”>Java</option>

<option value=”C#”>C#</option>

<option value=”Data Base”>Data Base</option>

<option value=”Hadoop”>Hadoop</option>

<option value=”VB script”>VB script</option>

</select>

</td>

</tr>

<tr>

<td>Agree</td>

<td><input type=”checkbox” name=”checked” value=”1″></td>

<?php if(!isset($_POST[‘checked’])){ ?>

<span class=”error”>* <?php echo “You must agree to terms”;?></span>

<?php } ?>

</tr>

<tr>

<td>

<input type=”submit” name=”submit” value=”Submit”>

</td>

</tr>

</table>

</form>

<?php

echo “<h2>Your given values are as :</h2>”;

echo (“<p>Your name is $name</p>”);

echo (“<p> your email address is $email</p>”);

echo (“<p>Your class time at $course</p>”);

echo (“<p>your class info $class </p>”);

echo (“<p>your gender is $gender</p>”);

for($i=0; $i < count($subject); $i++)

{

echo($subject[$i] . ” “);

}

?>

</body>

</html>

=====

Explode () Function :

The explode function is used to “Split a string by a specified string into pieces i.e. it breaks a string into an array”.

The explode function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

For example you have a string

$str=”A E I O U”;

now you want to make each name as an element of an array and access it individually so what you do:

$arr = explode(“,”, $str);

means : we have made pieces of string $text based on separator ‘,’
and put the resulting array in variable $arr

So I used print_r ($arr); and the results are the following:

Array(
[0] => A
[1] => E
[2] => I
[3] => O
[4] => U
)

which is equal to:

$arr = Array (“A”,”E”,”I”,”O”,”U”);

Syntax:

explode (separator,string,limit)

Example1:

<html>
<body bgcolor=”pink”>
<h3>Explode Function</h3>
<?php
$str=”I am simple boy!”;
print_r(explode(” “,$str));
?>
</body>
</html>

Output:

Array ( [0] => I [1] => am [2] => simple [3] => boy! )

Simple example for multiple selection using dropdown with implode function :

(1)first write code for select.html file:

<form action=select.php method=post>

<select name=city[] multiple=”multiple”>

<option value=mumbai>mumbai</option>

<option value=delhi>delhi</option>

<option value=goa>goa</option>

</select>

<input type=submit name=submit>

</form>

output:dropdown

(2)now write code for select.php file:

<?php

$data=implode(‘,’,$_POST[‘city’]);

$con=mysql_connect(‘localhost’,’root’,”);

mysql_select_db(“batch”,$con);

$sql=”insert into test(city)values(‘$data’)”;

mysql_query($sql) or die(mysql_error());

?>

Simple example for multiple selection using Checkboxes with implode function :

(1)first write code for checkbox.html file:

<form action=checkbox.php method=post>

mumbai<input type=checkbox name=city[] value=mumbai>

Delhi<input type=checkbox name=city[] value=delhi>

city<input type=checkbox name=city[] value=city>

<input type=submit name=submit value=submit>

</form>

output :

2

(2) write code for checkbox.php file :

<?php

$data=implode(‘,’,$_POST[‘city’]);

$con=mysql_connect(‘localhost’,’root’,”);

mysql_select_db(“batch”,$con);

$sql=”insert into test(city)values(‘$data’)”;

mysql_query($sql) or die(mysql_error());

?>

 

==========

Create A PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

The example below creates a constant with a case-sensitive name:

<?php
define(“GREETING”, “Welcome to vissicomp.com!”);
echo GREETING;
?>

Output:

Welcome to vissicomp.com!