Learning PHP

Here are some more friendly PHP tutorials.

What is PHP

PHP is a C like language. PHP is called a server side language, because it is executed by a server, never by a browser. The output of the PHP code is sent, as html code, from the server to the browser.

Why use PHP?

  1. A server side language, such as PHP, is essential to deal with input from forms. Forms can greatly increase the interactivity of your site.
  2. PHP lets you communicate with databases on your web server.
  3. PHP can help you avoid writing repetitious html code:

What do you need to use PHP?

Since PHP is executed by a server, you must have access to a server. Access can be gained in two ways.
  1. You can install a server, and PHP on your computer. This is a good option, if you can do it, because it allows you to error check your files, and run them without the bother of uploading them to a web site.
  2. You can use your web hosting server. Whether this is a good option depends on your web hosting server.
    1. You need a server that outputs PHP parsing errors. Otherwise you will see nothing but a blank page whenever you make a PHP syntax error.
    2. It is a great convenience if you choose a server that provides you with cPanel. cPanel allows you to modify your files while they are uploaded. It is available at low cost from some web hosting services.

What is a PHP file?

PHP code can be inserted into any html file. It then becomes a PHP file, and must be given the extension ".php". The ".php" extension tells the server to examine the file for PHP code, and to evaluate it, before sending it to the browser.

How do you execute a PHP file?

You can call a PHP file in two ways:
  1. With an anchor tag. You can call a PHP file with an anchor tag, just as you can call an html file.
        <a href="test.php">Click here. </a>
  2. With a form. You can set your PHP file as the action attribute of a form. When the form is submitted, the PHP file will be executed.
        <form method="POST" action="test.php">
        <input type="submit">
        </form>

Information about your PHP Build

One of the first programs you should run is the following:

<?php 
 phpinfo(); 
?>
The function phpinfo() tells you which version of PHP you are running, and what it is capable of. The following link gives this information for the PHP build I am currently using.

php_info

PHP Syntax

PHP code can be included anywhere within the html code by placing it inside brackets like these:

<?php          ?> 

Semicolons MUST go at the end of EACH statement. There is one exception worth noting.

  1. Within the parentheses of a for loop -- a semicolon Must NOT be used after the last statement.

PHP distinguishes between single and double quotes. Material between single quotes is treated literally. If you include variables, you get variable names out. When double quotes are used, variables are evaluated.

PHP Comments

Single line comments are made with the //, while multiline comments are enclosed between /* and */.
<?php
// This is a comment.
but this is not.

/* This is 
   a 
   comment, too.  */
?>

PHP Variables

Variable Names:

Variables are created by assigning values to them. The type is determined from the variable assigned. Thus the type of a variable can change in mid program.

Variables can be boolean, integer, float, string, array, or object.

The type of a variable can be determined with the gettype() function.

PHP Constants

Constants are declared as follows: define('X', 0);

Constant names are case sensitive. (By convention, they are written in uppercase.) Constant names do not contain a $.

Constants can be boolean, integer, float, or string.

NULL, Empty, Set and Unset Variables

When you need to determine whether a variable has been given a value -- for instance, in checking form input -- the best thing to do is to see php.net's type comparison tables.

gettype()

Arithmetic Operators

Arithmetic Operators are the same in PHP as in JavaScript.
+
-
*
/
%
++ increments by 1
-- decrements by 1

Arithmetic Assignment Operators

= is replaced by
+= is increased by
-= is decreased by
*= is multiplied by
/= is divided by
x%=y x is replaced by x%y

String Operators

The . operator concatenates two strings.

String Assignment Operators

The .= operator works analogously to the += operator.

Comparison Operators

== is equal to
=== is equal to and has the same type
!= is not equal
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to

If ... else Statements

if (  ){    }
else{  };

When using if statements, the comparison must be in parentheses. If one statement is used with no curly braces, it must have a semicolon, even if followed by an else. (This differs from most languages.) Curly braces are needed if there is more than one statement. These are not followed by semicolons, when followed by an else.

The key words and and or may be used in PHP. You'll need extra parentheses.

Be sure to use double equals in if statements.

If you use array variables, such as $_POST[v], in if statements, surround them with curly braces to avoid ambiguity.

For Loops

For loops are just like JavaScript's.

for ($i=0;$i<5;$i++){
  statements;
};

You can step through arrays using foreach.

foreach($array as $var){ 
  echo($var);
}
foreach ($array as $key => $value){
echo"$key  $value ";
}

While Loops

while ( ){ 

 };
A statement that evaluates to true or false is placed within the parentheses.
Code to be evaluated within the curly braces.

The do-while loop is similar:

do {  } while ( );

Arrays

Arrays are created in PHP by an amazingly transparent statement:
<?php
$a=array(key1=>value1,key2=>value2); 
?>
If the key is omitted, it is by default, 0, 1, 2 etc.

Watch what print_r does with an array.

<?php
 $a=array('a'=>'apple', 'b' => 'banana', 'c' => array ('x', 'y', z'));
 print_r ($a);
?>
The above example will output:
Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) 

To find the number of items in an array, you can use the sizeof function; sizeof() is an alias for count(). You can't use sizeof() on a string. It will return 1.

<?php
 $a=array('a'=>'apple', 'b' => 'banana', 'c' => array ('x', 'y', z'));
 $l=sizeof($a)
 echo"$l";
?>

Multidimensional Arrays

Evidently multidimensional arrays are arrays of arrays.

Array elements can be referred to as:

$x[$i][$j]

However, references to multidimensional arrays can be ambiguous. Thus the code:

echo"$x[$i][$j]";

will only yield something such as:

Array[0]

The request was interpreted as a request to echo $x[$i] which is an array, followed by [$j].

To refer to an element of a multidimensional array unambiguously, you can enclose it in curly braces.

echo {$x[$i][$j]};

Strings in PHP

To concatenate strings use the dot operator:
'string1'.'string2'

When strings are placed within double quotes, variables within the string are evaluated.

However, when a string is placed within single quotes, the string is taken literally. Variable names rather than variables are printed out.

String Functions

chr(byte)Returns the ASCII character of a byte
ord(char)Returns the ordinal value of a character
strlen(string)Returns length of a string
trim(string)removes whitespace from beginning and end of string. Whitespace includes spaces, NULL, tab, new line, vertical tab, and carriage return.
ltrim(string) Removes whitespace from beginning of string.
rtrim(string) Removes whitespace from end of string.
substr(string,i,l)Returns a substring beginning with the ith character. Set i=0 to start at the beginning of the string.
The substring will be l characters long.
Omit l to continue to the end of the string.
str_replace(search,replace,subject)Replace all instances of "search" with "replace" within the string "subject."
strpos(string,substring)Examines string for substring. Returns position or false.
explode('c', string)Splits a string into an array. If 'c' is ' ', it will split a sentence into an array of words.
str_split(string[,n])Splits a string into an array of chunks, n characters long. If n is omitted, the string is split into characters.
number_format(float,n])Converts a float to a string with n decimal places.

Using PHP Functions

Using PHP to add Text to Files

The require() function causes the contents of a file to be inserted as that point. The inserted file can be either a PHP file or an html file.

<?php 
 require("test.php"); 
?>
<?php 
 require("foot.htm"); 
?>

Defining PHP Functions

Example:

<?php 
function state($x){
 if ($x=='S') return 'Solid';
 else if($x=='L') return 'Liquid';
 else if ($x=='G') return 'Gas';
}
?>

Functions can return an array output. The array is declared and filled within the function, and the array variable is returned.

<?php 
function Colors($h){
$dml=array(3,'dark','medium','light');
return $dml;
}
?>

Math Constants and Functions

These constants and functions have been available since PHP v 4.

Constants
M_E M_PI
M_EULER M_SQRTPI
M_LNPI M_SQRT2
M_LN2 M_SQRT3
M_LN10

Arithmetic Functions
abs(x)
max(a,b)
min(a,b)
round(x) round to nearest integer
ceil(x) round up
floor(x) round down
fmod(a,b) remainder of the division

Geometric Functions
sqrt(x) square root of x
pow(x,y) x to the y
exp(x) e to the x
log(x) natural log of x
log10(x)

Transcendental Functions
sin(x)asin(x) sinh() asinh()
cos(x) acos(x) cosh() acosh()
tan(x) atan(x) tanh() atanh()

Trig Related Functions
deg2rad() degrees to radians
rad2deg() radians to degrees
hypot(a,b) hypotenuse of right triangle of sides a,b

Integer Conversions
decbin() decimal to binary
dechex() decimal to hexadecimal
decoct() decimal to octal
hexdec() hexadecimal to decimal
octdec() octal to decimal
base_convert()

Random Numbers
rand(min,max) Returns a random integer between min and max
srand() Seeds the random number generator
getrandmax() Returns the maximum random number that can be returned by a call to the rand() function
lcg_value() Returns a pseudo random number in the range of (0,1)

is_finite(x) true if x is finite
is_infinite(x) true if x is infinite
is_nan(x) true if x is not a number

Accessing Files and Directories on the Server

The function scandir('directoryName') returns an array, each term of which consists of one file in the directory.

<?php 
$directory="/usr/local/";
echo "Contents of Directory $directory<br>";
$folder=scandir($directory); 
 foreach($folder as $var){ 
  echo($var);
  echo'<br>';
}
?>

Files may be opened and read with the file('filename') function. The result is an array, each item of which corresponds to one line of the file.

<?php 
echo"Contents of file freetype-config using file() function<br>";
$content=file("/usr/bin/freetype-config");
 foreach($content as $var){ 
  echo($var);
  echo'<br>';
}
?>

Output

The echo statement sends text and html tags to the browser. Echo is not a function. These echo statements are correct:

<?php
echo "<h5>One enchanted evening</h5>"; 
echo $x;
echo($x);        //When () used, only one variable is accepted.
echo $x, $y, $z; //Variables must be sep'd by commas
echo $row[0]."  ".$row[1]."  ".$row[2 ]."<br>";
?>

If you want to send a quotation mark to the browser, you must send it as \"

The print() function accepts only one argument, and returns true or false.

The print_r() function accepts strings, integers, floats, arrays. If given an array, the keys and values of the array will be printed. One caveat: print_r() will move the array pointer to the end of the array. You can use reset() to bring it back to beginning.

Note: In versions of PHP before 4.0.4, print_r() would continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS).

Formatted Output using the printf() and sprintf() functions

The functions, printf() and sprintf(), are identical except for one point. The printf() function writes the code to the document, while sprintf() writes it to a string variable.

The first argument of printf() is a string which directs formatting. The succeeding arguments are data to be printed within the string.

The data can be integers, floating point numbers, strings, or boolean variables.

The format string can contain any sort of explanatory text, but the feature which directs formatting is a set of "conversion specifications". We'll call these "specs" for short. There should be one "spec" for each datum.

Each "spec" has two functions:

Each "spec" must have at least two characters: it begins with a % sign and ends with a type specifier. In between may be more characters which further direct the formatting. First let's look at type specifiers, since they are essential.

Type Specifier Data TypeHow Displayed
sstring
d integeras a decimal integer
bintegeras a binary integer
Ointegeras an octal integer
xintegeras a hexadecimal integer
Xintegeras a hexadecimal integer
uinteger unsigned integer
ffloating pointstandard decimal notation
E or efloating pointscientific notation
cbyteASCII representation

Need some examples here

try monkeys octal binary, hex scientific, decimal

Next let's look at format modifiers, which go between the % and the type specifier. If they are used they must be in the order shown in the table below.

Possible ValuesPurposeRemarks
sign +Makes a positive number carry a + sign. Negative numbers carry a sign by default.
padding 0, ,'* specifies the character used for padding, if padding is neededused only if length specified; default is space
alignment-left justifiesdefault is right justified
length 1,2,3,4,5,6,etc.minimum number of characters to output
precision .n n=0,1,2,3,etc.Number of characters after decimal point?? number of decimal digits??applies only to floating points

Example with leading zeros

How to include a % in the format string.

Here output was rounded to 1 decimal point:

$out_bmi=sprintf('%0.1f', $_bmi);

Peter Kantor describes and compares the different PHP output commands in PHP Client Side.

Documentation on sprintf() can be found at php.net

Using PHP to Generate non Html Files

The type of file that PHP sends to the browser is, by default, html. However files of other mime types can be sent. This is accomplished by using the header function to designate the mime type.

Images and image files can be generated with php. This is explained in the section on PHP Image Functions