Archives for : php

PHP Files

PHP File handling

PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files thru the use of these functions. Note that before you start working with files, you have to make sure that you have the right permissions that will allow you to manipulate them. So while you’re trying to figure out why you can’t delete a file, it may be because the server doesn’t allow you to do that.

The creation and removal of files are completed with two functions: “touch()” and “unlink()”. “touch()” searches if a file exists, and if it doesn’t, it creates one, according to the specified filename; “unlink()” is used to remove the file passed on as an argument:

touch(“newinfo.txt”); //create a new file, if it doesn’t already exist
unlink(“oldinfo.txt”); //delete a file

Now that you know how to create a file, you should learn how to access it. This is done using the “fopen()” function, with requires a string containing the file path and a string containing the mode in which the file is about to be opened, which tells “fopen()” to open a file for reading, writing, or both. The complete list of the available modes can be found in the PHP documentation. “fopen()” return an integer, also known as a file pointer, which should be assigned to a variable. This will be used later on to work with the opened file. If a file cannot be open for whatever reason, “fopen()” returns FALSE. After you’re done with the file, you should remember to close it with “fclose()”, passing as an argument the file pointer.

$oldfp = fopen(“oldinfo.txt”, “r”); //opens a file for reading
if(!$fp = fopen(“newinfo.txt”, “w”)) //tries to open a file for writing
die(“Error opening file!”); //terminates execution if it cannot open the file
fclose($oldfp);

Reading from files is done with “fgets()”, which reads data from a file until it reaches a new line “n”, an EOF (end-of-file), or a specified length, in this order. So if you specify 4096 bytes but “fgets()” first reaches a new line, it stops further reading. You should know that after each reading or writing to a file, PHP automatically increments an index which holds the current position in the file. So if you have just opened a file, and then read 100 bytes, the next time you will want to read something else using the same file pointer, PHP will continue from where the 101st byte. The “fgetc()” is similar to “fgets()”, except that it returns only a single character from a file every time it is called. Because a character is always 1 byte in size, “fgetc()” doesn’t require a length argument.

$text = fgets($fp, 2000); //reads 2000 bytes at most
$chr = fgetc($fp); //reads 1 byte only

While you can read lines using “fgets()”, you need a way of telling when you have reached the end-of-file, so you won’t continue reading without any results. This is accomplished with the “feof()” functions, which returns “TRUE” or “FALSE”, weather the position of a file pointer is at the end of it. You now have enough information to read a file line by line:

$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn’t open $filename");
while(!feof($fp))
{
  $line = fgets($fp);
  print "$line
"; } fclose($fp);

While “fgets()” works well around text files, you may sometimes want more functionality for your script. The “fread()” functions returns the specified amount of data from a file, and doesn’t take into consideration the end-of-line “n”, like “fgets()”. “fread()” also starts from the current file position, but if you’re not happy with it, you can always change it using the “fseek()” function.

fseek($fp, 100); //moves the file pointer to the 100th byte
print(fread($fp, 15)); //outputs 15 bytes

Any writing to a file is done with the use of “fwrite()” or “fputs()” functions, which both use a file pointer and a string to perform the writing:

fwrite($fp, “Hello from PHP!”);

fputs($fp, “Hello again from PHP!”);

So far, these functions were great with a single user. However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the “flock()” function, which will lock a file and won’t allow other processes to write or read the file while the current process is running. “flock()” requires a file pointer and an integer to do this:

flock($fp1, 1); //shared lock – allows read, doesn’t allow write

flock($fp2, 2); //exclusive lock – doesn’t allow neither read, nor write

flock($fp3, 3); //release lock – releases a shared or exclusive lock

There are a lot of other functions that you can use with files like: testing functions – “file_exists()”, “is_file()”, “is_dir()”, “is_readable()”, “is_writeable()”, “is_executable()”; functions that return information on files: “filesize()”, “fileatime()”, “filemtime()”, “filectime()”. You can figure out what the function does by just reading its name; more information about them can be found in the PHP documentation.

PHP Functions

PHP Functions

A function is a block of code to perform a specific task. This block of code can be executed anywhere in the program by calling it’s name. A simple syntax of PHP function is:

//define a function
function f_name()
{    block of code to perform a task;
}
//call a function
f_name();

Let’s make a simple code to make our first PHP function.

<html>
<body>
<?php
function first_func()
{   echo "This is my first PHP function.";
}
first_func();
?>
</body>
</html>

We have made a function named, first_func. First, a function is created by using the keyword, “function” which is followed by the function name. The function name should be self explanatory so that it is easy to use in the program. A function name should start with an alphabet or an underscore and should not contain special characters except underscore. All the code of the function should be within a pair of curly braces. The function once created can be used anywhere in the program by just mentioning the name of the function. In the above example, we have called the function, “first_func” in the program after creating it. Let’s see the output:

This is my first PHP function.

When a function is created, the code within it is not executed. The function is merely created. The code within the function will be executed only when it is called.


Adding parameters in PHP function

In the example above, there are empty brackets after the name of the function. These brackets are empty because we have not used any parameters in it. Parameters can be used along with a function when a variable has different values in the program. Let’s see with the help of an example how parameters are used in a PHP function.

<?php
function add($x,$y)
{    $sum=$x+$y;
     echo "The addition of $x and $y is $sum.";
}
echo "The addition of 4 and 2 using add function:<br/>";
add(4,2);
echo "<br/>The addition of 8 and 5 using add function:<br/>";
add(8,5);
?>

In the above example, we have called the function, “add” twice. The result will be:

The addition of 4 and 2 using add function:
The addition of 4 and 2 is 6.
The addition of 8 and 5 using add function:
The addition of 8 and 5 is 13.

Return values in a PHP function

Till now we have seen that we call a function and it executes the code within it. But suppose that the output of the function has to be used outside the function. In this case, the function returns a value. Let’s see this with an example.

<?php
function add($x,$y)
{    $sum=$x+$y;
     return $sum;
}
echo "The addition of 4 and 2 using add function:<br/>";
add(4,2);
echo "<br/>The addition of 8 and 5 using add function:<br/>";
add(8,5);
?>

The output will be:

The addition of 4 and 2 using add function:
6
The addition of 8 and 5 using add function:
13

PHP Loop

PHP Loop

PHP loops are used to execute some code again and again for some definite number of times. There are many types of looping statements in PHP. They are:

  • while loop
  • do…while loop
  • for loop
  • foreach loop

Let’s discuss each of these loops.


While loop

The while loop is used to execute the specified code as long as the condition is true. The syntax of the while loop is given below:

while (condition)
code to be executed;

Let’s see a simple code to display numbers 1-10 by using while loop.

<?php
$i=1;
while (i<=10)
{     echo $i."<br/>";
      $i++;
}
?>

This simple code displays the numbers 1-10 in separate lines.

1
2
3
4
5
6
7
8
9
10

Let’s see how the above code is executed.
First the value of “i” is initialised to 1. Then the condition is checked and since “i” is less than 10, the code within the while loop is executed and 1 will be displayed. Then the value of “i” will be incremented. and the condition will be again checked and the new value of “i”, i.e. 2 will be displayed. This will continue till the condition is true. Notice, we increment the value of “i” in the loop. You should have a statement in your while loop which will eventually cause the condition to be false. If you don’t do this, the loop will never stop and your program will appear “frozen”.


Do…while loop

A do…while statement is a modified version of while loop. The main difference between both these loops is that the while loop checks the condition before executing the code within it while do while loop executes the code once and then checks the condition. Do while loop is used when the code withing the loop has to be executed at least once irrespective of the condition. The syntax of do while loop is:

do
{    code to be executed;
}
while (condition);

The following example will illustrate this:

<?php
$i=1;
do
{     echo $i."<br/>";
      $i++;
}
while ($i<=10);
?>

The output will be:

1
2
3
4
5
6
7
8
9
10

In the example above, the parser will initialize the value of “i” to 1 and then it will execute the code within the do while loop and then it will check the condition. So even if the condition is false, the code within the loop will be executed at least once.


For loop

The for loop is one of the most used loops because it is very logical and easy to use. The syntax of the for loop is:

for (initial; condition; increm)
{      code to be executed;
}

The syntax of for loop has three parts:

  • initial:Initialize the counter.
  • condition:The condition to be checked at the beginning of each loop. If the condition is true the code within the loop will be executed and if it is false, it will not be executed.
  • increm:Increment or decrement the counter.

Note that each part of the for loop is separated by semicolon. Below is a simple example:

<?php
for ($i=1; $i<=10; $i++)
echo $i."<br/>";
?>

and the output will be:

1
2
3
4
5
6
7
8
9
10

Foreach loop

The foreach statement is used to loop through arrays. For the current value of the array, the code within the loop is executed. The syntax of the foreach loop is:

foreach (arrayname as value)
{      code to be executed;
}

Let’s see a simple example:

<?php
$arr=array(1,2,3,4,5,6,7,8,9,10);
foreach ($arr as $v)
echo $v."<br/>";
?>

The output will be:

1
2
3
4
5
6
7
8
9
10

PHP Arrays

PHP Arrays

An array is a data structure that stores one or more values in a single variable. Each element in the array has its own id. There are 3 types of arrays in PHP namely,:

  • Numeric Array: An array with a numeric ID key.
  • Associative Array: An array where each ID key is associated with a value.
  • Multidimensional Array: An array containing one or more arrays.

Let’s see each of these arrays.


Numeric array

Whenever some data is stored in an array, some ID is assigned to each value. In numeric array, the ID assigned to each value is numeric. Numeric arrays can be created in many ways. Let’s see those ways.

//  Method I
  $name = array('Value1','Value2','Value3' );
//  Method II
  $name[] = 'Value1';
  $name[] = 'Value2';
  $name[] = 'Value3';
//  Method III
  $name[0] = 'Value1';
  $name[1] = 'Value2';
  $name[2] = 'Value3';

Let’s see each of these ways.

&lt;?php
//  Method I
  $name = array( 'Mike','Scott','Peter' );
  echo $name[0].", ".$name[1].", ".$name[2];
?&gt;

In the first method, the keys are assigned automatically but remember that the keys start from 0 and not from 1.

<?php
//  Method II
  $name[] = 'Mike';
  $name[] = 'Scott';
  $name[] = 'Peter';
  echo $name[0].", ".$name[1].", ".$name[2];
?>

In the second method too, the keys are assigned automatically and the keys start from 0.

<?php
//  Method III
  $name[0] = 'Mike';
  $name[1] = 'Scott';
  $name[2] = 'Peter';
  echo $name[0].", ".$name[1].", ".$name[2];
?>

In the last and the third method, we have assigned the keys ourselves. The output of all the three methods will be the same as given below:

Mike, Scott, Peter

Below is an example to make arrays more clear:

<?php
	echo "looping through array";
	$x = array(0,1,4,9,16,25,36,49,64,81);
	for($j = 0;$j<10; $j++)
	{
	    echo " $j  : $x[$j]";
	}
?>

and the output will be:

looping through array
0
1
4
9
16
25
36
49
64
81

Associative Array

In associative array, the ID key is associated with a value. There are two ways of creating an associative array.

//  Method I
  $name = array("key1"=>Value1, "key2"=>Value2, "key3"=>Value3);
//  Method II
  $name['key1'] = "Value1";
  $name['key2'] = "Value2";
  $name['key3'] = "Value3";

Let’s see both these methods.

<?php
     $mdays = array("January" => 31,
		    "February" => 28,
		    "March" => 31,
		    "April" => 30,
		    "May" => 31,
		    "June" => 30,
		    "July" => 31,
		    "August" => 31,
		    "September" => 30,
		    "October" => 31,
		    "November" => 30,
		    "December" => 31
		   );
     echo "February has ".$mdays['February']." days.";
?>

Now let’s see the second method.

<?php
       $mdays['January'] = "31";
       $mdays['February'] = "28";
       $mdays['March'] = "31";
       $mdays['April'] = "30";
       $mdays['May'] = "31";
       $mdays['June'] = "30";
       $mdays['July'] = "31";
       $mdays['August'] = "31";
       $mdays['September'] = "30";
       $mdays['October'] = "31";
       $mdays['November'] = "30";
       $mdays['December'] = "31";
    echo "February has ".$mdays['February']." days.";
?>

The output of both the methods will be:

February has 28 days.

Multidimensional Array

In a multidimensional array each element in the main array can also be an array. A simple multidimensional array is normally visualised as a matrix. Let’s see the syntax to create a simple multidimensional array.

$name = array
(
    "array1" => array
    (
        "value1",
        "value2",
        "valuen"
    ),
    "array2" => array
    (
        "value1",
        "valuem
    ),
    "arrayz" => array
    (
        "value1",
        "valuey"
    )
);

Below is an example to make multidimensional arrays more clear:

<?php
$cds = array
(     "Christina Aguilera" => array
      (
           "Impossible",
           "Beautiful",
           "Dirrty"
      ),
      "Kelly Rowland" => array
      (
           "Stole",
           "Obsession"
      )
);
?>

To access the first cd of “Christina Aguilera”, the PHP script will be:

<?php
echo "First cd of Christina Aguilera is ".$cds['Christina Aguilera'][0];
?>

and the output will be:

First cd of Christina Aguilera is Impossible

PHP Switch

Switch statement

The “switch” statement is similar to a series of “If…else” statements. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. The syntax of the “switch” statement will be:

<?php
switch (expression)
{
case value1:
{ code executed if the expression has value1;
break; }
case value2:
{ code executed if the expression has value2;
break; }
default:
code executed if none of the value is true;
}
?>

Let’s discuss the above syntax step by step. Let’s consider the simple script given below using the if, elseif, else statements.

<?php
if ($i == 0)
echo "i equals 0";
elseif ($i == 1)
echo "i equals 1";
elseif ($i == 2)
echo "i equals 2";
?>

Now we will use the switch statement for the above task. First we will use only the “switch” statement and see what happens.

<?php
switch ($i) {
case 0:
   echo "i equals 0";
case 1:
   echo "i equals 1";
case 2:
   echo "i equals 2"; }
?>

Now, let’s see what the output will be. Suppose, the value of “i” is 1. The output will be:

i equals 1
i equals 2

which is certainly not the desired one. The switch statement is always used along with break. When the expression value matches any case value, it performs the code associated with it and when it encounters break statement, it comes out of the switch loop. If the break statement is missing, the pointer will perform all the statements subsequent to the matching case statement. In our example above, the value of “i” was 1. So the code underneath it was performed but since it did not encounter any break statement, the code beneath the subsequent case statement was also performed. So the correct script will be:

<?php
switch($i) {
case 0:
   { echo "i equals 0";
   break; }
case 1:
   { echo "i equals 1";
   break; }
case 2:
   { echo "i equals 2";
   break; }
}
?>

The output of the above code will be what we desired, i.e.

i equals 1

If you look at the logic of the above program, there is no need to use break in the last case because the pointer will come out of the loop anyways. So, you can avoid using break statement in your last case. But if you have any confusion then use break in every case.

Now there’s only one thing remaining to be understood in the above syntax — “default”. The default case is similar to the else statement. The code in the default case is executed when the expression does not match any of the case values. The following example will make this clear.

<?php
switch($i) {
case 0:
   { echo "i equals 0";
   break; }
case 1:
   { echo "i equals 1";
   break; }
case 2:
   { echo "i equals 2";
   break; }
default:
   { echo "i does not equal any value";
   break; }
}
?>

If the value of i is 5, the output will be:

i does not equal any value

A point to remember:The default case should always appear as the last case in the switch statement.

PHP if else

If, If…else, elseif

Sometimes we want different actions to be performed for different actions. If, If…Else, and Elseif statements can be used for this purpose. Let’s have a look at each of these statements.


If statement

The most important is the “if” statement. It performs some actions if the specified condition is true. If the condition is not true, then the action will be ignored. The syntax of this statement is as follows:

if (condition)
code to be executed if the condition is true;

Let’s see an example.

<html>
<body>
<?php
$str="PHP";
if ($str=="PHP")
echo "Condition is true.";
?>
</body>
</html>

Let’s see what the output of the above script will be.

Condition is true.

The value of str is “PHP”. Hence, we get the above output because the condition is true. If the condition had been false, there would have been no output. Consider the script given below:

<html>
<body>
<?php
$str="Learn PHP";
if ($str=="PHP")
echo "Condition is true.";
?>
</body>
</html>

We will not get any output here because our condition is false. If the action to be performed has more than one statement, all the statements should be enclosed within a pair of curly brackets. Look at the code given below:

<?php
$str="PHP";
if ($str=="PHP")
{ echo "Condition is true.";
echo "This will help to understand PHP better.";
}
?>

The output will be:

Condition is true.This will help to understand PHP better.

If…else

The “if…else” statement provides an additional advantage. If provides the actions to be performed when the condition is true and when it is false. Let’s look at the syntax:

if (condition)
code to be executed if the condition is true;
else
code to be executed if the condition is false;

Have a look at the following example:

<?php
$city = "NJC";
if ($city == "NYC")
{
echo "Condition is true.";
echo "I love NYC!";
}
else
{
echo "Condition is false.";
echo "I don't belong to NYC!";
}
?>

Since our condition is false, both the statements after else will be executed. Hence, the output will be:

Condition is false.I don't belong to NYC!

Elseif

The “elseif” statement helps us to check more than one conditions. First look at the syntax and then we will see how it works.

if (condition1)
{
code executed if condition1 is true;
}
elseif (condition2)
{
code executed if condition2 is true;
}
else
{
code executed if none of the conditions is true;
}

Following example will make it more clear.

<html>
<body>
<?php
$city = "LA";
if ($city == "NYC")
{
echo "I love NYC!";
}
elseif ($city == "LA")
{
echo "I love LA!";
}
else
{
echo "My city is not there!";
}
?>
</body>
</html>

The value of city is “LA”, hence, the output will be:

I love LA!

The “elseif” statement allows us to check multiple conditions. There can be multiple elseif statements.

PHP String Capitalization

String Capitalization

String capitalization is used to change the case of a string. There are three functions for this purpose namely, strtoupper, strtolower and ucwords. Let’s have a look at each of these examples separately.


strtoupper()

This function converts the entire specified string to upper case. Let’s see this with an example:

<?php
$str="We capitalize this string!";
$str_upper=strtoupper($str);
echo $str_upper;
?>

The output of the above PHP code will be:

WE CAPITALIZE THIS STRING!

By using this function, all the alphabets will be capitalized and the numbers and special characters will remain as they are.


strtolower()

This function converts the entire specified string to lower case. It’s functioning is similar to that of “strtoupper()” function.

Let’s see this example:

<?php
$str="PHP is a good language!";
$str_lower=strtolower($str);
echo $str_lower;
?>

The output of the above PHP script will be:

php is a good language!

ucwords()

This function capitalizes starting letter of each word in the string specified. This function comes in handy when writing a title or a heading. Let’s see this example that will demonstrate the function, ucwords():

<?php
$str="This title will look good!";
$str_uc=ucwords($str);
echo $str_uc;
?>

The output will be:

This Title Will Look Good!

This function ensures that the starting letters of each word in the string are capitalized. The rest of the string remains as it is. If there is a letter in upper case in the middle of the word, it will remain in upper case.

PHP substr_replace

substr_replace()-Replace a part of string

The substr_replace() function is complementary to the function that we discussed earlier – “str_replace()”. While in “str_replace()”, we specified the value that had to replaced, in “substr_replace()”, we specify the starting and the end points of the value to be replaced. It is a more mathematical function. “substr_replace” has four parameters. The syntax is as follows:

substr_replace(original, replace, start, length);

Let’s have a look at the above syntax:

  • original : The string in which replacement function has to be performed.
  • replace : The value with which the value has to be replaced.
  • start : The starting point from where the replacement has to start. It has to be a number. In case there is a negative number, it means number of characters from the end of the string.
  • length : It is an optional parameter. This value tells how many characters beginning from the “start” value have to be replaced. In case the value is negative, it means number of characters from the end of the string.

Now let’s see this with an example.

<?php
$str="I am a sex!";
$str_girl=substr_replace($str, "girl", 7,3);
$str_boy=substr_replace($str, "boy", -3, 2);
echo "Girl:".$str_girl."<br/>;
echo "Boy:".$str_boy;
?>

The output of the above code will be:

Girl:I am a girl!
Boy:I am a boy!

The fourth parameter, length is optional. What will happen if we dont use this parameter? Let’s see.

<?php
$str="I am a sex!";
$str_girl=substr_replace($str, "girl", 7);
$str_boy=substr_replace($str, "boy", -3);
echo "Girl:".$str_girl."<br/>;
echo "Boy:".$str_boy;
?>

The output of the above script will be:

Girl:I am a girl
Boy:I am a boy

This is the desired output. But do you see any difference in this output and the output above. The exclamation mark at the end of the statement is missing. The reason is that when you do not specify the length parameter, it replaces all the characters from the starting point to the end of the string, with the replace string.


Perform INSERT

The substr_replace function can also be used to insert a value in a string without replacing anything, simply by putting the parameter, length to 0. Let’s add something in our string above.

<?php
$str="I am a sex!";
$str_girl=substr_replace($str, "girl", 7, 3);
$str_boy=substr_replace($str, "boy", -3, 2);
echo "Girl:".substr_replace($str_girl, "good ", 7, 0)."<br/>;
echo "Boy:".substr_replace($str_boy, "good " , -3, 0);
?>

The output will be:

Girl:I am a good girl!
Boy:I am a good boy!

This has performed our insert function.

PHP str_replace

str_replace()-Replace a string

The “str_replace()” function is used to replace some occurence in a string. It is very much similar to the “replace all” function in a word processor. It let’s us specify a word and what to replace it with, then replaces every occurrence of that word in the document. The syntax of the “str_replace()” function is:

str_replace(search, replace, string);

Let’s have a look at the above syntax. We will discuss each argument now.

  • search:This is the string that has to be replaced.
  • replace:This is the value with which the “search” string has to be replaced.
  • string:This is the string within which the whole replacement procedure has to be done.

We will see a simple example here in which we customise a string depending on whether a person is an adult or a child.

<?php
$str="I am rep.";
$str_ad=str_replace("rep", "adult", $str);
$str_ch=str_replace("rep", "not an adult", $str);
echo "adult:".$str_ad."<br/>;
echo "not adult:".$str_ch;
?>

The output will be:

adult:I am adult.
not adult:I am not adult.

In the above example, we had to replace a single value in the string. Suppose we want to replace multiple values in a single string. For this we will use arrays. We need two arrays for this purpose-one will store the “search” values and the other will store the “replace” values. Let’s see this with an example.

<?php
$str="Welcome Birmingham parent!
Your offspring is a pleasure to have!
We believe pronoun is learning a lot.
The faculty simple adores pronoun2 and you can often hear them say 
"Attah sex!"";
$search=array('offspring', 'pronoun', 'pronoun2', 'sex');
$malerep=array('son', 'he', 'him', 'boy');
$femalerep=array('daughter', 'she', 'her', 'girl');
$malestr=str_replace($search, $malerep, $str);
$femalestr=str_replace($search, $femalerep, $str);
echo "Son: ".$malestr."<br/>";
echo "Daughter: ".$femalestr;
?>

The output of the above script will be:

Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores he2 and you can often hear them say "Attah boy!"

Daughter: Welcome Birmingham parent!
Your daughter is a pleasure to have! We believe she is learning a lot.
The faculty simple adores she2 and you can often hear them say "Attah girl!

The above output is inconsistent with what we wanted. The “pronoun2” does not reflect the result that we wanted. Can you guess the reason?
The reason is very simple. The “str_replace” works step by step. First it will replace all the “offspring” value in the string, then it will replace all the “pronoun” values in the string and then it will proceed to “pronoun2” and then in the end to “sex” value. So when the function is replacing the “pronoun” value, it encounters “pronoun2” in the string and replaces it. Hence, the “pronoun” in “pronoun2” was replaced with “he” or “she”. So when the “str_replace” function started searching for “pronoun2”, it did not find any match in the string. Hence, the error.
A simple solution to this problem can be to place “pronoun2” before “pronoun” in the “search” array. So, the above code can be written correctly as:

<?php
$str="Welcome Birmingham parent!<br/>
Your offspring is a pleasure to have!
We believe pronoun is learning a lot.<br/>
The faculty simple adores pronoun2 and you can often hear them say 
"Attah sex!"";
$search=array('offspring', 'pronoun2', 'pronoun', 'sex');
$malerep=array('son', 'him', 'he', 'boy');
$femalerep=array('daughter', 'her', 'she', 'girl');
$malestr=str_replace($search, $malerep, $str);
$femalestr=str_replace($search, $femalerep, $str);
echo "Son: ".$malestr."<br/>";
echo "Daughter: ".$femalestr;
?>

And the output will be:

Son: Welcome Birmingham parent!
Your son is a pleasure to have! We believe he is learning a lot.
The faculty simple adores him and you can often hear them say "Attah boy!"

Daughter: Welcome Birmingham parent!
Your daughter is a pleasure to have! We believe she is learning a lot.
The faculty simple adores her and you can often hear them say "Attah girl!"

which is the result that we desired.

PHP strpos

strpos()-To find the position of a string or character within a string

The function, strpos() finds the position of a string within a string. It needs two arguments. First argument is the string in which you want to search and the second argument is the string that you want to search. When the function finds the string then it will return the position of the first match. In case it does not find a match, it will return false.

Let’s understand this with a simple example.

<?php
echo strpos("Learn PHP", "PHP");
?>

The result of the above script will be:

6

The strpos() function can also be used in the following manner:

<?php
$str="Learn PHP";
echo strpos($str, "PHP");
?>

The answer will be the same. Now, let’s see why the result was 6 and not 7. Remeber that the strpos() function always returns a value that is (position – 1). The reason is that the counter starts with 0 and not from 1. When you search for a string, then the position of the first character will be returned.


Finding position of a string using offset

The strpos() function has a third optional argument also. But what is the purpose? When we searched a string using strpos(), it returned the value of the first occurence of the string. But there can be more than one occurence of the string as well and we might be interested in it. For this, we can use the third optional argument in the strpos() function. Let’s see how.

<?php
$str="Learn PHP. Master PHP.";
$pos1=strpos($str, "PHP");
echo "The first occurence of PHP in the string is $pos1.";
$pos2=strpos($str, "PHP", $pos1+1);
echo "<br/>The second occurence of PHP in the string is $pos2.";
?>

The output of this script will be as follows:

The first occurence of PHP in the string is 6.
The second occurence of PHP in the string is 18.

PHP strlen

strlen()-To find the length of a string

To find the length of a string, we use a function strlen(). Let’s use this function to find the length of a string.

<?php

echo strlen("Learn PHP");

?>

The output of the above code will be:

9

Alternatively, we can write the PHP script like the way below. The output will be the same as above.

<?php

$str="Learn PHP";

$length=strlen($str);

echo $length;

?>

PHP Concat Strings

Concat Strings

Two strings can be concatenated by using the operator dot (.). Let’s see this with an example:

<?php
$str1="Learn";
$str2="PHP";
echo $str1.$str2;
?>

The result for the above echo statement will be:

LearnPHP

Now look at the script given below:

<?php
$str1="Learn";
$str2="PHP";
echo $str1." ".$str2;
?>

The result of this script will be:

Learn PHP

Here, we used the concatenation operator twice to include another string i.e. a blank.

PHP Strings

PHP String

A string is a text that might contain characters, numbers or any special character. First of all, we will create a string. Either a string can be stored in a string variable or it can be directly output to a browser without using any variable. Consider the php example:

<html>
<body><?php
$str="String variable is being used";
echo $str;
echo "Direct output";
?></body>
</html>

In the above example, we have used a string variable named, “str” that contains the string, “String variable is being used”. The first echo statement will display the string, “String variable is being used” and the second echo statement will display the string, “Direct output”.

The string is enclosed in double quotes. You can also use single quotes. Suppose you want to display an apostrophe in a string. Let’s see how you will do this.

<?php
echo ‘It’s a very good site to learn PHP!’;
echo ‘It won’t let you down!’;
?>

Here we have used backslash() to escape the apostrophe. The output of the above PHP script in a web page will be:

It's a very good site to learn PHP! It won't let you down!

The output will appear in a single line because there was no <br> tag present. Let’s have a look at a few more escape sequences:

Character Description
n Will add a new line
t Will add a tab
r Carriage return
$ A dollar sign will be displayed
Double quotes are displayed

PHP String “heredoc”

Apart from the two ways to create a string that we discussed earlier, there is one more way to create a string-“heredoc”. It is used to create a multi-line string without the use of quotes. Have a look at the code given below:

<html>
<body><?php
$str=<<<TRY
This is an example to demonstrate heredoc!
TRY;
echo $str;
?></body>
</html>

Let’s have a look at this code. “str” is a string variable which stores multi-line string. It starts with <<< and an identifier. Here, we have used “TRY”. The “heredoc” ends with the identifier in the end followed by a semicolon. Remember that the closing sequence “TRY;” must be on a separate line that must not be indented. The output of the above script on a web page will again be in a single line due to the absence of <br> tag as shown below:

This is an example to demonstrate heredoc!

PHP Comments

PHP comments

Comment is that part of the code that is not parsed by the parser. The main objective of the comment is to provide necessary notes to the programmer. It helps in understanding the code better. Every language has a different way of storing a comment. In PHP, the comments are stored in a manner similar to that of C++. Let’s see a single line comment in a PHP script.

<?php //echo “We are checking a comment.”; echo “We are checking a comment.”; ?>

The output will be:

We are checking a comment.

Why is there only a single line in the output when we have given the echo command twice. The reason is that the first statement is a comment. Any statement written after double slash (//) will not be parsed by the parser and hence, you can put absolutely any notes there for your convenience. But now suppose, we want to add multiple lines of comment instead of a single line comment. It would be very tedious to put “//” at the beginning of each line. This problem has been simplified. Multiple line comments are handled in the following manner:

<?php /*This is a multiple line comment. You can as many lines as you want here. They will not affect the PHP script.*/ echo “We just learnt multiline comment.”; ?>

In the above code, we have used “/*” to mark the beginning of the comment and “*/” to mark the end of the comment. And here’s the output to the above script:

We just learnt multiline comment.

PHP Operators

PHP Operators

The PHP operators can be divided broadly into 5 categories namely,

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators

Arithmetic Operators

Operator Description
+ Addition
Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
Decrement

Let’s see a few examples.

$a = 4;
$b = 2;
$Add= $a + $b;
$Sub= $a - $b;
$Multip= $a * $b;
$Div= $a / $b;
$Mod= $a % $b;
$Increm= $a++;
$Decrem= $b--;

The reult of the above will be:

Add=6
Sub=2
Multip=8
Div=2
Mod=0
Increm=5
Decrem=1

Assignment Operators

Operator Description
= $a = $b; assigns a the value of b (Equal)
+= $a+=$b; means $a = $a+$b; (Addition)
-= $a-=$b; means $a = $a-$b; (Subtraction)
*= $a*=$b; means $a = $a*$b; (Multiplication)
/= $a/=$b; means $a = $a/$b; (Division)
.= $a.=$b; means $a = $a.$b; (Concatenation)
%= $a%=$b; means $a = $a%$b; (Modulus)

Let’s take a look at a few examples:

$a = 4;
$b = 2;
1) $a = $b; (assigns a the value 4)
2) $a+=$b; (a will have the value 6)
3) $a-=$b; (a will have the value 2)
4) $a*=$b; (a will have the value 8)
5) $a/=$b; (a will have the value 2)
6) $a%=$b; (a will have the value 0)


Comparison Operators

Operator Description
== $a==$b; will return true if value of a is equal to value of b
!= $a!=$b; will return true if value of a is not equal to value of b
> $a>$b; will return true if value of a is greater than value of b
< $a<$b; will return true if value of a is less than value of b
>= $a>=$b; will return true if value of a is greater than or equal to value of b
<= $a<=$b; will return true if value of a is less than or equal to value of b

Below are a few examples:

$a == $b;// test if two values are equal
$a != $b;// test if two values are not equal
$a &lt; $b;// test if the first value is less than the second
$a &gt; $b;// test if the first value is greater than the second
$a &lt;= $b;// test if the first value is less than or equal to the second
$a &gt;= $b;// test if the first value is greater than or equal to the second

Logical Operators

Operator Description
&& and; returns true when two or more conditions are be true
|| or; returns true when either of the two conditions is true
! not; negates a given condition

PHP Variables

PHP Variables
What are variables?
Variables are names that store values like strings or numbers. Their values can change at any point in the whole program. Since the value is variable, they are known as variables.

Declaring Variables
Most programming languages require variables to be declared. This is done to ensure what data type it is and hence, what type of data it can store. Each programming language has its own set of data types. In case of PHP, the variables do not have to be declared. PHP automatically converts the variable to the correct data type, depending on how they are set. Hence, PHP is known as a loosely typed language. A strongly typed language requires you to declare the variables in the beginning of the program. Assigning values to variables in PHP
Variable names begin with a dollar sign ($). Lets have a look at the following statements:

$worda = “gnulamp”;
$wordb = “php tutorial”;
$website_url = “http://www.gnulamp.com”;
$word=”$worda $wordb”;
$num1 = 10;
$num2 = 20;
$sum = $number1 + $number2;

Some rules to remember

* A variable name must start with a letter or an underscore (_).
* A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ).
* A variable name should not contain spaces. If needed, underscores should be used.
* Variabe names are case sensitive.
* String constants are enclosed in quotes (“).
* Numeric values are assigned as it is.

PHP Output

PHP Output

To display the result of a PHP script, there are two basic commands. They are echo and print. Both these commands are used in PHP to display any text. The only difference between these two commands is that print() function is slower than echo() function. Hence, echo has an upper hand and is used more. Let’s understand both these functions with the help of examples.
echo function
Let’s see an example below to display the text, “My first PHP program!”.

<html>
<body>
<?php
echo “My first PHP program!”;
?>
</body>
</html>

The output will be:

My first PHP program!

print function
The print function is used in a manner similar to echo statement.

<html>
<body>
<?php
print (My first PHP program!);
print “My first PHP program!”;
?>
</body>
</html>

The output will be:

My first PHP program!
My first PHP program!

PHP Basics continued

PHP Basics

  • PHP runs on different platforms.
  • PHP is compatible with almost all servers used today.
  • PHP is FREE to download from the official PHP resource.

How to save PHP files?

PHP files have the extention .php. PHP files are not different from HTML files. It is basically a simple HTML or any other SGML file having some php script in between. No matter where it is placed, PHP code is executed before any of the HTML code. The only difference is that the file must have the extention .php, else the parser will not parse it.

PHP syntax

A PHP block can occur anywhere in any SGML file. The syntax for the same is given below:

<?php
PHP script here
?>

Some servers have shorthand support and the syntax for PHP in such cases is:

<?
PHP script here
?>

But it’s always recommended to avoid the shorthand way and use the former way.
Have a look at a simple PHP script given below:

<html>
<body><?php
echo "My first PHP program";
?></body>
</html>

The above example will send the text “My first PHP program” to the browser. One thing to note is that every statement in the PHP code must have a semi-colon in the end. “echo” is a statement that outputs the text to the browser.

PHP Tutorial Basics

PHP is a recursive acronym for “PHP: Hypertext Preprocessor”.

  1. It is an open source.
  2. It is a server-side scripting language, i.e. the PHP script gets executed on the server.
  3. It is widely used in web development.
  4. It can be easily embedded into HTML.
  5. PHP is very much similar in syntax to C or Perl.
  6. How and where PHP is used
  7. Server-side scripting:PHP is mainly used to make web pages which are dynamic and interactive. There are three things needed for this purpose namely, web server, web browser and PHP parser.
  8. Command line scripting:This is used when you don’t want to use browser or server. Only PHP parser is needed. The script can be executed using cron on Linux or Task Scheduler on Windows.
  9. Desktop applications:Though not recommended, PHP can be used to write desktop applications using PHP-GTK. This is used specially in writing cross-platform applications.
  10. Some advantages of PHP
  11. PHP can be used on all major operating systems, including Linux, Unix.
  12. Most of the web servers can be used including Apache, Microsoft Internet Information Server.
  13. PHP can be used to create dynamic and interactive web pages.
  14. PHP code can be easily embedded into HTML code.
  15. PHP is free.
  16. Databases Supported by PHP
  17. Some databases that are supported by PHP are Adabas D, InterBase, PostgreSQL, dBase, FrontBase, SQLite, Empress, mSQL Solid, FilePro (read-only), Direct MS-SQL, Sybase, Hyperwave, MySQL, Velocis, IBM DB2, ODBC, Unix dbm, Informix, Oracle (OCI7 and OCI8), Ingres and Ovrimos.

phpdoc-msg

These pages have been retired, check out php docs

Ping host measured in microseconds

Problem

You want to ping a host on a given port and record time taken in microseconds.

The following solution uses PHP socket libraries to open a connection, to the given host and port – then just close it again. By obtaining the microseconds before and after, it is able to deduce time taken in microseconds.

Additionally I’ve added functionality to print the epoch, so the timestamp can be obtained.



Solution

pingStat.php


<?php
list($usec, $sec)=explode(" ",microtime());
$thisDate=sprintf("%f", ($usec+$sec));
$host="$argv[1]";
$port="$argv[2]";

if(!$host) {
die("Usage: $0 host port [ dtg ]n");
}

$fp = fsockopen("$host", $port, $errno, $errstr, 30);
if (!$fp) {

print("ping failed to host: $host:$port -
$errstr ($errno)n");

} else {

list($usec, $sec)=explode(" ",microtime());
$nextDate=sprintf("%f", ($usec+$sec));

if($argv[3]) {
printf("%d:%0.4fn",time(),$nextDate-$thisDate);
} else {
printf("%0.4fn",$nextDate-$thisDate);
}

fclose($fp);

}

?>



Example


First example pings a host on port 80 and prints the current epoch.


$ php -q ./pingStat.php apachehost 80 y
1183524570:0.0824

Second example pings it again on port 443 and this time does not print epoch.


$ php -q ./pingStat.php apachehost 443
0.0775



Reference

[tags]Ping host measured in microseconds, PHP Coding School[/tags]



pinging host measured in micro seconds

Problem

You have a requirement to capture network speed, in microseconds.

The required speed was less than 0.25 of a second (or quarter of second).



Solution

We use PHP to capture the current time in microseconds. Run a system ping command. Capture the new time and minus one from the other.



Example


Here's the PHP code, using the microtime function and a simple ping.

<?php

list($usec, $sec)=
explode(" ",microtime());

$thisDate=sprintf("%f", ($usec+$sec));

$host="$argv[1]";

system("ping -c1 $host > /dev/null 2>&1",$response);

if($response==0) {

list($usec, $sec)=explode(" ",microtime());

$nextDate=sprintf("%f", ($usec+$sec));

printf("%0.4fn",$nextDate-$thisDate);

} else {

print("ping failed to host: $hostn");

}

?>

Here is a run through:

$ php -q pingHost.php bagend
0.0098
$ php -q pingHost.php bagend
0.0066
$ php -q pingHost.php bagend
0.0065
$ php -q pingHost.php bagend
0.0066





Useful PHP script – running queries against sybase database

Problem

you want to run queries against a Sybase Database, using the PHP API.



Solution

A PHP script using sybase API for PHP, connect as given user, with your password on specific host.



Example


Useful for monitoring sybase dbs, although in this instance it does not actually hit any database tables.

<?php

$user = "your_user";
$passwd = "password";
$host = "your_host";
$sql="select getdate(), @@version ";
$conn=sybase_connect($host,$user,$pass); // connect to db
print("running query host: $hostnuser: $usern");
$result = sybase_query ( $sql ); // Run query and store in array
$i = 0;
while($row = sybase_fetch_array($result)) {
// Loop around the array and print field or column 1 and 2
$i++;
$item1 = $row[0];
$item2 = $row[1];
echo "$i $item1 $item2";
}
sybase_close();
?>



Reference

[tags]Sybase PHP example, PHP Coding School[/tags]



display an image with a label superimposed

Problem

You want to generate an image, with text over the top.



Solution

Why of course we use PHP extensive image library routines! 🙂



Example


<?php

header(“Content-type: image/png”);
$string = $_GET[‘label’];

if(isset($_GET[‘font’])) { $font = $_GET[‘font’]; } else { $font=“2″; }
$len=strlen($string);
$text_width = imagefontwidth($font);
$text_height = imagefontwidth($font);
/* Create a blank image */
$im = imagecreate (($len*$text_width)+10, $text_height+10);
$bgc = imagecolorallocate ($im, 0, 0, 0);
$tc = imagecolorallocate ($im, 255, 255, 255);
imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
imagestring ($im, $font, 5, 0, “$string”, $tc);
imagepng($im);
imagedestroy($im);

?>



Reference

I’ve now created an online tool, using this code Label Your Images

[tags]Image Creation, Label Image, PHP Coding School[/tags]



PHP and AJAX tool to transform text

Problem

You want to transform text form ascii to base64, urlencode it, digest it, etc.

Or you want to decode these formats.



Solution

Just wrote this tool, to allow instant transformation of data into following formats:

base64 encode decode, urlencode decode, md5 and sha1 hashing, addslashes and htmlentities

click here to access the transform tool
Pretty cool to see ‘all’ too – check it out.



Example


Here is the code:


<?php

if(isset($_GET['mode'])) {

$mode=urlencode($_GET['mode']);

$val=$_GET['val'];

switch($mode) {

case "base64_encode": echo base64_encode($val); break;
case "base64_decode": echo base64_decode($val); break;
case "urldecode": echo urldecode($val); break;
case "urlencode": echo urlencode($val); break;
case "htmlentities": echo htmlentities($val); break;
case "rot13": echo str_rot13($val);break;
case "md5": echo md5($val);break;
case "sha1": echo sha1($val);break;
case "all":

echo "base64_encode: ".base64_encode($val);
echo "base64_decode: ".base64_decode($val);
echo "urldecode: ".urldecode($val);
echo "urlencode: ".urlencode($val);
echo "htmlentities: ".htmlentities($val);
echo "addslashes: ".addslashes($val);
echo "rot13: ".str_rot13($val);
echo "md5: ".md5($val);
echo "sha1: ".sha1($val);
break;

}

exit(0);

}

?>





making a thumbnail image on the fly

Problem

You need to make a thumbnail of an image, on the fly.



Solution

Here is a short PHP script to make a thumbnail out of the image.

It takes two arguments, one for the image’s file name and one for the compression rate.



Example


displayThumb.php
<?php

$filename = $_GET['filename'];
$compression = $_GET['compression'];

Header("Content-type: image/png");

$im = imagecreatefrompng("$filename");

$currWidth=ImageSX($im);
$currHeight=ImageSY($im);

$newWidth=$currWidth * ($compression / 100);
$newHeight=$currHeight * ($compression / 100);

$im1 = imagecreatetruecolor($newWidth,$newHeight);
$bgc = imagecolorallocate ($im1,255,255,255);
imagefilledrectangle ($im1, 0, 0, $newWidth, $newHeight, $bgc);
imagecopyresampled ($im1, $im, 0, 0, 0, 0,
$newWidth, $newHeight, $currWidth, $currHeight);
imagepng($im1);
imagedestroy($im1);

?>



Reference

[tags]Image manipulation, thumbnail creation on the fly, PHP Coding School[/tags]



converting a GIF to a PNG with PHP

Problem

You need to convert a GIF into a PNG.



Solution

Another short bit of PHP, which takes a GIF filename as a parameter and a compression tag,
so you can convert to PNG and change size too.

If you don’t want to compress the image, just use a value of 100.



Example


convertGifPng.php

<?php

$filename = $argv[1];
$compression = $argv[2];

Header("Content-type: image/png");

$im = imagecreatefromgif("$filename");

$currWidth=ImageSX($im);
$currHeight=ImageSY($im);

$newWidth=$currWidth * ($compression / 100);
$newHeight=$currHeight * ($compression / 100);

$im1 = imagecreatetruecolor($newWidth,$newHeight);
$bgc = imagecolorallocate ($im1,255,255,255);
imagefilledrectangle ($im1, 0, 0, $newWidth, $newHeight, $bgc);
imagecopyresampled ($im1, $im, 0, 0, 0, 0,
$newWidth, $newHeight, $currWidth, $currHeight);
imagepng($im1);
imagedestroy($im1);

?>



Reference

[tags]Convert Images GIF PNG, PHP Coding School[/tags]



PHP MySQL Web Interface

Problem

Having written a ga-zillian scripts, to query dbs, decided it would be much simpler to call just one function multiple times, duh! 🙂

Then fulfilling business request after request – with many short php web pages calling the function. Decided to progressing this further – by removing the web page altogether (hitting the function via a wrapper). Let it handle the query, via variable parameters passed in on the HTTP GET.

This posed a bit of problem, pushing complexity on the enquirer. So then decided to write a web (interface) form to drive the function (wrapper) – which subsequently made the query. 🙂

All will become clear shortly! 🙂



Solution



Example


Following this link will help a bit, I hope! 🙂 mysql demo

This web interface prepares the fields, which are subsequently submitted to the function for you.

You may notice that run_q is a PHP script, this is so you can either e-mail links directly to the function (genericQuery.php) or to this interface (run_q.php).

For example:

This query selects all fields and rows with a limit of 2 rows, to be returned – directly submitted to the function.

Function:
MySQL Demo Query

The next example drives the interface, which can then be submitted to the function. Notice it pre-selects mysql as the db (this is just for demo purposes, the table does not exit and mysql db is not accessible as this user).

Interface:

MYSQL Web Interface

After the interface submits, the subsequent query to the function can be cut and paste from the browser address bar.

Also this interface shows all the possible functions, where you can get quite creative in your query – try it out.



Reference

[tags]PHP MySQL Web Interface, PHP Coding School[/tags]



Writing a wordpress plugin – 3 easy steps

Problem

You want to create a wordpress plugin, which substitutes your tags for HTML.



Solution

This was a million times easier than I thought it was going to be. 🙂

step 1: mkdir wordpress/wp-content/plugins/YourPluginName

step 2: vi wordpress/wp-content/plugins/YourPluginName/Your Plugin Name.php

step 3: activate your plugin



Example


Here I want to substitute the following tags, with content wrapping.

[problem] … [/problem]

Put simply 😉


/*

Plugin Name: php-coding-school
Plugin URI: http://php.coding-school.com/php-coding.school.php
Description: wraps content, etc
Version: 1.0
Author: marcus
Author URI: http://php.coding-school.com

*/

add_filter('the_content', 'mp_wrap_content');

function mp_wrap_content($content) {

$search_strings='Your pattern to replace';

$end_strings='Your replacement';

$content = str_replace($search_strings,$end_strings, $content);
...
return $content;

}
?>



Reference

Used everywhere on this site, including this post itself. 🙂

[tags]Wordpress Plugin Tutorial, PHP Coding School[/tags]



showing syntax highlighted source

Problem

Want to display PHP code with syntax highlighting (colors). This helps with debugging, etc.



Solution

Within PHP you can nicely display colorful text, which can be very useful for debugging or just to showcase your code.

We simply use the highlight_file function within PHP, like this below.



Example


<?php highlight_file("transform.php"); ?>

For a real-life demo, take a look here:



Reference

[tags]PHP Syntax Highlighting, PHP Coding School[/tags]