<?php phpinfo(); ?>
<?php ... php code (each statement ends with a semicolon) ... ?>When the container engine receives input from the web server, it reads the input from top to bottom (so-called "parsing"). During the parsing process, the PHP engine looks for the opening and closing (<?php .... ?>) tags and understands that the content between these tags is script code that it must interpreted. The engine ignores everything outside the <?php .... ?> and thus allowing (i) PHP files to have mixed content and (ii) PHP code to be embedded within HTML code.
sample.php
)<?php ... php code ... ?>
<?php include('sample.php') ?>
.
<body> ... </body>
of html code
<body> ... <?php ... php code ... ?> ... </body>
// this is a comment # this is a comment /* this is for multiple lines of comments */
$variable_name = value;
$color = "blue"; echo "My favorite color is $color";The above PHP code is equivalent to
$color = "blue"; echo "My favorite color is " . $color; // string concatenation with a dot (.)Note: The double quotes ensure that PHP will evaluate the entire string and substitute named variables with their values. This feature does not work if the string is enclosed in single quotes.
Type | Description | Type checking |
string | Series of characters | is_string(param) |
int | Non-decimal number | is_int(param) |
float | Floating-point decimal number | is_float(param) |
bool | Expression of a Boolean truth value | is_bool(param) |
array | Ordered map of multiple data values that associates keys to values (keys may be indexed number by default or may be explicitly specified labels) | is_array(param) |
object | Class containing strored ata properties and providing methods to process data | is_object(param) |
NULL | Variable with no value | is_null(param) |
$days[] = 'Monday'; $days[] = 'Tuesday'; $days[] = 'Wednesday'; // or $days = array('Monday', 'Tuesday', 'Wednesday'); // both create an array where the value stored in each element // can be referenced using its index number echo $days[1]; // Tuesday var_dump($days); // array(3) { [0]=> string(6) "Monday" [1]=> string(7) "Tuesday" [2]=> string(9) "Wednesday" } // or $days = array('Monday', 'Tuesday', 'Wednesday', 5 => 'Friday', '6' => 'Saturday', 7 => 'Sunday'); var_dump($days); // array(6) { [0]=> string(6) "Monday" [1]=> string(7) "Tuesday" [2]=> string(9) "Wednesday" // [5]=> string(6) "Friday" [6]=> string(8) "Saturday" [7]=> string(6) "Sunday" }
$months['jan'] = 'January'; $months['feb'] = 'February'; $months['mar'] = 'March'; // or $months = array('jan' => 'January', 'feb' => 'February', 'mar' => 'March'); // both create an array where the value stored in each element // can be referenced using its key name echo $months['jan']; // January // Another example $mixedTypeArray['jan'] = 'January'; $mixedTypeArray['2'] = 'February'; $mixedTypeArray[3] = 'March'; $mixedTypeArray[true] = 'April'; echo $mixedTypeArray['2'] . "<br/>"; // February $mixedTypeArray[2] = 'another entry of February'; echo $mixedTypeArray[2] . "<br/>"; // 'another entry of February'; echo $mixedTypeArray['2'] . "<br/>"; // 'another entry of February'; $mixedTypeArray[2.8] = '2.8 will round down to 2'; // this assignment will replace the value of key=2 of the array echo $mixedTypeArray[2] . "<br/>"; // 2.8 will round down to 2 $mixedTypeArray['2.8'] = 'Huh??'; echo $mixedTypeArray['2.8'] . "<br/>"; // Huh?? echo $mixedTypeArray[1] . " : " . $mixedTypeArray[true] . " <br/>"; // April : April $mixedTypeArray[1] = 'true equals to 1 in PHP'; echo "$mixedTypeArray[1] <br/>"; // true equals to 1 in PHP $mixedTypeArray[4] = 'another entry of February'; var_dump($mixedTypeArray); // array(6) { ["jan"]=> string(7) "January" [2]=> string(24) "2.8 will round down to 2" [3]=> string(5) "March" [1]=> string(23) "true equals to 1 in PHP" ["2.8"]=> string(5) "Huh??" [4]=> string(25) "another entry of February" }
$states[0] = "Virginia"; $states[] = "Georgia"; // implicit key = the array's current key + 1 $capitals['VA'] = "Richmond"; $matrix[7][11] = 2.718;
Array
construct // specify values without keys // PHP interpreter will furnish the numeric keys 0, 1, 2 $list = Array(17, 24, 30); // specify values with keys $agelist = Array("Joe" => 17, "Mary" => 24, "Ann" => 30);
$list[2] = 34; $agelist['Mary'] = 44;
for ($i=0; $i<count($months); $i++) { // use the current $i on each iteration, $months[$i] to access an element in the array } for ($i=0; $i<sizeof($months); $i++) { // use the current $i on each iteration, $months[$i] to access an element in the array } foreach ($months as $value) { // use the current $value on each iteration } foreach ($months as $key => $value) { // use the current $key and $value on each iteration }
$arr = Array ("A", "E", "I", "O", "U"); $str = implode("-", $arr); // join array elements with "-" // the resulting string $str will be "A-E-I-O-U")
$str = "A E I O U"; $arr = explode(" ", $str); // split a given string based on a " " separator // and put the pieces in array // this results in // Array([0]=>"A", [1]=>"E", [2]=>"I", [3]=>"O", [4]=>"U")
$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); $workdays = array_slice($days, 1, 5); // array_slice(array_to_slice, start_index, length)
$letters = array('A', 'B', 'C'); $numbers = array(1, 2, 3); $matrix = array('Letter' => $letters, 'Number' => $numbers); // access individual item echo $matrix['Letter'][0]; // To use an array variable as part of a mixed string, // if an array variable uses quoted keys, // the array variable must be enclosed within curly braces echo "(mix with string) Element value is {$matrix['Letter'][0]}"; // To traverse foreach ($matrix as $matrix_key => $matrix_value) { foreach ($matrix_value as $key => $value) echo $matrix_key .'[' . $key .'] = '. $matrix_value[$key] .'<br />'; }
$user = array( 'info' => array ('name' => 'Duh', 'age' => 32, 'location' => 'USA', ... ) 'education_level' => ... ); echo "I live in $user['info']['location'] <br/>"; echo "My latest education level is $user['info']['education_level'] <br/>";
Operator | Compative test |
== | Equality (compare values) |
!= | Inequality |
=== | Identity (compare values and types) |
!== | Non-identically |
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
<=> | Spaceship (compare values)
|
$parity = ( $number % 2 == 0 ) ? "Even" : "Odd" ; echo "$number is $parity";To check if a variable is NULL, a null coalescing operator (??) can be used to traverse a number of opearands, from left to right, and return the value of the first operand that is not NULL. If none of the operands have a value (i.e., they are not NULL), the ?? operator will itself return a NULL result.
$a = NULL; $b = "xyz"; $c = 123; $result = $a ?? $b ?? $c; echo "abc : $result";Example: conditions.php (text version)
if ($num > 0) $pos_count++; elseif ($num < 0) $neg_count++; else { $zero_count++; }
$loop = 5; while (--$loop) { switch ($loop % 2) { case 0: echo "Even<br />\n"; break; case 1; echo "Odd<br />\n"; break; } }
$fact = 1; $count = 1; while ($count < $n) { $count++; $fact *= $count; }
$count = 1; $sum = 0; do { $sum += $count++; $count++; } while ($count <= 100);
for ($count = 1, $fact = 1; $count < $n; $count++) { $fact *= $count; }
$students = array("Jack", "Jill", John", "Jane"); foreach ($students as $student) { echo $student . "<br/>"; }
$students = array("Jack" => array("age" => 20, "favorite_color" => "blue"), "Jill" => array("age" => 20, "favorite_color" => "green"), ... ); foreach ($students as $name => $info) { echo $name . "'s " . $info['age'] . "years old <br/>"; }
$letter = 'B'; switch ($letter) { case 'A': echo 'Letter is A'; break; case 'B': echo 'Letter is B'; break; case 'C': echo 'Letter is C'; break; case 'D': echo 'Letter is D'; break; default: echo 'Default letter'; break; }
echo $myVar;
print "Hello World!";
printf("Your total bill is %5.2f", $price);
%10s
— a character string field of 10 characters %6d
— an integer field of six digits %5.2f
— a float or double field of five spaces,
with two digits to the right of the decimal point, the decimal point,
and two digits to the left
print "Hello, ".$_POST['name'];
floor(0.60);
// returns 0ceil(0.60);
// returns 1round(0.60);
// returns 1rand();
// returns random number rand(10, 100);
// returns random number between 10 and 100abs(-6.7);
// returns 6.7min(2,8,6,4,10);
// returns 2 min(Array(2,8,6,4,10));
// returns 2max(2,8,6,4,10);
// returns 10 max(Array(2,8,6,4,10));
// returns 10strlen("Hello");
// returns 5strcmp("Hello world!","Hello world!");
// returns 0 (two strings are equal)strpos("Hello world!", "world");
// returns 6substr("Hello world!", 6, 1);
// returns wchop("Hello world!","world!");
// returns Hellotrim(" Hello world! ");
// returns Hello world!function name([parameters]) { ... }
function modify($val, &$ref) { ... // $val is passed by value, $ref is passed by reference // The ampersand in the parameter declaration indicates // that the parameter will be passed by reference. }
function ([parameters]) { ... }Two ways to call an anonymous function:
// (assume we want to display the return value of the function) echo (function ([parameters]) { ... })([value_of_parameters]);
// (assume we want to display the return value of the function) $myVar = function ([parameters]) { ... }; echo $myVal([value_of_parameters]);
function drink($tmp='hot', $flavor='tea') { ... } // Call the function without passing parameters drink(); // Call the function with some parameter passing (ordering) drink('iced'); // Call the function with parameter passing (ordering) drink('cold', 'lemonade');
// A function that accepts multiple integer arguments // and display their total value function add(...$numbers) { $total = 0; foreach ($numbers as $num) { $total += $num; echo "<hr />Total: $total"; } } // Call the function and pass three values add(1, 2, 3);
global
keyword (i.e., refer to a global variable defined outside).
Note: Be careful when using global variables.
static
keyword when defining a variable.
Category | Status |
Successful 2xx | 200 OK |
Redirection 3xx | 301 Moved Permanently |
302 Found | |
Client Error 4xx | 400 Bad Request |
401 Unauthorized | |
403 Forbidden | |
404 Not Found | |
Server Error 5xx | 500 Internal Server Error |
503 Service Unavailable | |
504 Gateway Timeout |
$_GET['form_input_name']
$_POST['form_input_name']
$_SERVER['PHP_SELF'];
<?php // isSet() return true if $_POST['submit'] is not NULL or empty, // otherwise return false if (isSet($_POST['submit'])) { print "Hello, ".$_POST['name']; } else { ?> <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>" > Your name: <input type="text" name="name"> <br /> <input type="submit" name="submit"> </form> <?php } ?>
// check if the form is submitted with a POST method if ($_SERVER['REQUEST_METHOD'] == 'POST') { // check if a specified parameter is empty if (empty($_POST['name'])) // do something ... } ... }Examples: Form handling examples
is_file($path)
:
returns true if $path
exists and is a fileis_dir($path)
:
returns true if $path
exists and is a directoryfile_exists($path)
:
returns true if $path
exists and is either file or a directorygetcwd()
:
returns a string that specifies the current working directoryDIRECTORY_SEPARATOR
:
a backslash on Windows or a forward slash on Mac and Linuxscandir($path)
:
returns an array containing a list of the files and directories in $path
if $path is a valid directory name;
returns false otherwise// Display a directory listing $path = getcwd(); $items = scandir($path); echo "Contents of $path <br/>"; echo "<ul>"; foreach ($items as $item) { echo "<li>$item</li>"; } echo "</ul>";
// Display the files from a directory listing $path = getcwd(); $items = scandir($path); $files = array(); foreach ($items as $item) { $item_path = $path . DIRECTORY_SEPARATOR . $item; if (is_file($item_path)) { $files[] = $item; } } echo "Files in $path <br/>"; echo "<ul>"; foreach ($files as $file) { echo "<li>" . $file . "</li>"; } echo "</ul>";
file($filename)
:
returns an array with each element containing one line from the filefile_get_contents($filename)
:
returns the contents of the file as a stringreadfile($filename)
:
reads a file and echoes it to the screen $content = file_get_contents('sample-data.txt'); // htmlspecialchars converts special characters to HTML entities $content = htmlspecialchars($content); echo "<p>$content</p>";
file_put_contents($filename, $data)
:
writes the specified data string to the specified filename$sometext = "This is line 1.\nThis is line 2.\n"; // Replace the file content with value of $sometext // (this is similiar to open a file with a "write" mode) file_put_contents('sample-data2.txt', $sometext); // If the file does not exist, create one, then write the content. // If file_put_contents results in permission denied, // check the directory permission. // Run chmod to set a "write" permission
$list_of_content = file('sample-data.txt'); foreach ($list_of_content as $content) { echo $content . "<br/>"; }
$friends = array("Duh", "Huh", "Wacky"); $content = implode("\n", $friends); // join elements of an array with a \n file_put_contents("sample-data3.txt", $content);
fopen()
function
Mode | Description |
rb or r |
Opens the file for reading.
If the file does not exist,
fopen() returns FALSE.
|
wb or w |
Opens the file for writing. If the file exists, the existing data is deleted. If the file does not exist, create one. |
ab or a |
Opens the file for writing. If the file exists, the new data is appended. If the file does not exist, create one. |
xb or x |
Create a new file for writing.
If the file exists, fopen() returns FALSE.
|
fopen($file, $mode)
:
opens the specified file (in the specified location, i.e., path)
with the specified opening mode and returns a file handle
feof($file)
:
returns TRUE when the end of thespecified file is reached
fclose($file)
:
closes the specified file
fread($file, $length)
:
returns data from the specified file at the specified length
fgets($file)
:
returns a line from the specified file
fputs($file, $string)
:
writes the contents of string to a filefwrite($file, $string)
:
writes the contents of string to a file<?php $file = fopen("infilename.txt", "r"); // r: read only while ( !feof($file) ) { echo fgets($file), "<br />"; } fclose($file); ?>
<?php $file = fopen("outfilename.txt", "a"); // a: write only, append fputs($file, "Hello world"."\n"); fclose($file); ?>
<?php $file = fopen("outfilename.txt","w"); // w: write only fputs($file, "Hello world"."\n"); fclose($file); ?>
fgetcsv($file)
:
reads in a line of comma-separated values and
returns them in an array
$file = fopen('sample-data.csv', 'rb'); $scores = array(); while (!feof($file)) { $score = fgetcsv($file); if ($score !== false) { $scores[] = $score; echo "<div>$score[0] | $score[1] | $score[2] | $score[3] | $score[4] | $score[5] </div>"; } }To write tabular data to a CSV file
fputcsv($file, $array)
:
writes the specified array to the specified file as a line of comma-separated values
$scores = array(array(90, 100, 100, 100, 95, 95), array(100, 100, 97, 100, 95, 100)); $file = fopen('sample-data1.csv', 'wb'); foreach ($scores as $score) { fputcsv($file, $score); } fclose($file);
copy($old_filename, $new_filename)
:
copies the file with the old filename to file with the new filename.
If successful, returns TRUE$fname1 = "datafile1.txt"; $fname2 = "datafile2.txt"; if (file_exists($fname1)) { $copy_success = copy($fname1, $fname2); if ($copy_success) echo "<div>File was copied</div>"; }
rename($old_filename, $new_filename)
:
renames the file with the old filename to the new filename.
If successful, returns TRUE$fname2 = "datafile2.txt"; $fname_newname = "datafile_newname.txt"; if (file_exists($fname2)) { $rename_success = rename($fname2, $fname_newname); if ($rename_success) echo "<div>File was renamed</div>"; }
unlink($fname)
:
deletes the specified file.
If successful, returns TRUE
$fname3 = "datafile3.txt"; if (file_exists($fname3)) { $delete_success = unlink($fname3); if ($delete_success) echo "<div>File was deleted</div>"; }Examples: File examples
$_SESSION
global array variable
after a call is made to the session_start()
function.
$_SESSION
global array variable stores session data (names/values)
in an associative array of keys and values.
session_start()
function must be explicitly called
to initialize the session.
session_start()
is called,
the session ID stored in the PHPSESSID
variable
(default name) will be loaded from the cookie request header.
If the PHPSESSID
does not exist, a fresh session will be started
and the session ID will be sent back to the client with
the current response in the header.
session_id()
function.
$_POST
(or $_GET
) global array variable.
PHP script can check for the presence of individual submission fields using
a built-in isset()
function to seek an element of
a specified HTML field name.
When this confirms the field is present, its name and value can usually be
stored in a session object.
This might be used to stored username and password details
to be used across a web application (or website).
session_start()
at the beginning of the PHP file
session_start();
isset()
function to seek an element of a specified HTML field name.
if (isset($_POST['user'])) { // do something }
$_SESSION
object for later used.
$_SESSION['user'] = $user; // assign value of $user to a $_SESSION object // (associative array) key = 'user', value = $user
$_SESSION
object,
if (isset($_SESSION['user'])) // checks for the presence of individual field
{
$myuser = $_SESSION['user']; // access the $_SESSION
array with a specified key
...
}
$_SESSION
,
specify its name to the unset()
function.
unset($_SESSION['user']);
session_destroy()
function
session_destroy();
$_COOKIE
global array variable
$_COOKIE
contains all the cookie data stored in the browser,
The cookie data are stored by the same host, through the response headers or
JavaScript.
$_POST
(or $_GET
) global array variable.
PHP script can check for the presence of individual submission fields using
a built-in isset()
function to seek an element of
a specified HTML field name.
When this confirms the field is present, its name and value can usually be
stored in a cookie.
This might be used to stored username and password details
to be used across a web application (or website).
$_COOKIE
object, use a setcookie()
function.
setcookie(name, value, expiration-time) // Example setcookie('user', $user, time()+3600); // 1 hour = 60minutes * 60seconds setcookie('pwd', password_hash($pwd, PASSWORD_DEFAULT), time()+3600); // Create a hash conversion of password values using password_hash() function // with the default hash algorithm (the default algorithm may change over time) // setcookie('pwd', password_hash($pwd, PASSWORD_BCRYPT), time()+3600); // Create a hash conversion of password values using password_hash() function // with the bcrypt hash algorithm // setcookie('pwd', md5($pwd), time()+3600); // Create a hash conversion of password values using md5() function. // Using md5 is not recommended due to the weakness of the algorithm.
$_COOKIE
object,
if (isset($_COOKIE['user'])) // checks for the presence of individual field
{
$myuser = $_COOKIE['user']; // access the $_COOKIE
array with a specified key
...
}
$_COOKIE
object,
set the expiration-time
in the setcookie()
to be in the past
setcookie('user', 'value-does-not-matter', time()-3600); // expired 1 hour ago