PHP logo

PHP notes

These notes are only intended to summarise differences between PHP and other C based languages.

Enclosing PHP

<?php
PHP code goes here
?>
    

Outputting HTML

<?php
echo 'some HTML';
echo "some HTML with $var1";
print 'some HTML';
print "some HTML with $var1";
?>
    

Variables in double quotes are replaced with their values. Variables are not replaced if in single quotes. "echo" is slightly faster and is generally preffered, but can't be used in an expression because it is not a function like "print".

Outputting multiple lines

<?php
echo <<<_END
This a headline

This is a line
This is another line
_END;
?>
    

Concatenating strings

<?php
echo $var1.$var2;
?>
    

Logical OR and logical AND

PHP supports the C "||" and "&&" logical operators and the "or" and "and" logical operators, but the "or" and "and" operators have lower precedence and are best avoided. an exception is:

<?php
mysql_select_db($database) or die("Unable to select database");
?>
    

Constants

<?php
define("ROOT_LOCATION", "/usr/local/www/");
?>
    

Magical constants

__LINE__ current line in file
__FILE__ full path and filename
__DIR__ directory of the file
__FUNCTION__ function name
__CLASS__ class name
__METHOD__ class method name
__NAMESPACE__ the current namespace

Global variables

Any variables declared outside of a function or method are global and may optionally be preceeded by the "global" keyword.

Superglobal variables

$GLOBALS All variables that are currently defined in the global scope of the script. The variable names are the keys of the array
$_SERVER Information such as headers, paths, and script locations. The entries in this array are created by the web server and there is no garuantee that every web server will provide any or all of thsee
$_GET Variables passed to the current script via the HTTP GET method
$_POST Variables passed to the current script via the HTTP POST method
$_FILES Items uploaded to the current script via the HTTP POST method
$_COOKIE Variables passed to the current script via HTTP cookies
$_SESSION Session variables available to the current script
$_REQUEST Contents of information passed from the browser; by default, $_GET, $_POST and $_COOKIE
$_ENV Variables passed to the current script via the environment method

Note: it is safer to access superglobals using the htmlentities function which sanitises the content by converting charatcter like "<" to <

<?php
$came_from = htmlentities($_SERVER['HTTP_REFERER']);
?>
    

Comparisons and type conversions

PHP applies automatic type consversions when making comparisons. The "==" comparison uses automatic type consversion if required. The "===" comparison does not use type conversions i.e. type and value must match.

Return values

Functions and methods can return a value but their declarations do not allow you to specify a return type

<?php
function function_name([paremeter, [, ...]])
{
    // statements
    return 1;
}
?>
    

Passing by reference

To pass values to a function or method by reference only the prototype declaration needs show this. The call to the process or method looks the same whether passing by value of by reference.

<?php
function func1(&$parm1)
{
    $parm1 = 7;
}

$var1 = 1;
func1($var1);
?>
    

Including and requiring files

Other PHP files can be included using any of these:

<?php
include "library.php";
include_once "library.php";
require "library.php";
require_once "library.php";
?>
    

The "require_once" is the peferred version because the script will fail at this point if the file can't be found and will not create an error if the file is included twice.

Checking function existence

You can check for the existance of a predefined or user-created function before calling it.

<?php
if (function_exists("array_combine"))
{
    // statements
}
?>
    

Using class properties and methods

<?php
class Customer
{
    public $Forename;
    public $Surname;
    
    function fullname()
    {
        return $this->Forename.' '.$this->Surname;
    }
}

$objCustomer = new Customer;
$objCustomer->Forename = 'Fred';
$objCustomer->Surname = 'Bloggs';
$FullName = objCustomer->fullname();
?>
    

Inspecting objects with print_r

The contents of an object can be output to the webpage using print_r(). This is more readable if you "view source" in the web browser.

<?php
print_r($objCutomer);    
?>
    

Cloning objects

You can create a copy of an object including the values of it properties. Unlike copy an object reference, changing the properties of the clone makes no change to the original object.

<?php
$object2 = clone $object1;
?>
    

Constructors and destructors

<?php
class Customer
{
    function __construct($param1, $param2)
    {
        // statements
    }
    
    function __destruct()
    {
        // statements
    }
}
?>
    

Calling static methods

<?php
class Widget
{
    static function func1()
    {
        // statements
    }
}

Widget::func1();
?>
    

Dynamically adding properties to an object

It is possible to add properties to an object that are not in the class from which it was created. This should be avoided.

<?php
class Widget
{
}

$objWidget = new Widget;
$objWidget->Name = 'Fred';
?>
    

Class constants

<?php
class Widget
{
    const ENGLISH = 0;
    const SPANISH = 1;
    
    static function func1()
    {
        echo self::SPANISH;
    }
}
?>
    

Property scope

<?php
class Example
{
    var $property1; // (deprecated) visible outside of class and to subclasses
    public $property2; // visible outside of class and to subclasses
    protected property3; // visible to subclasses
    private property4; // not visible outsid of the class
}
?>

Static properties and methods

Static properties can't be accessed within an instance of a class but a static method can.
<?php
$temp = new Test();
echo "Test A: ".Test::$static_property.
; echo "Test B: ".$temp->get_sp().
; class Test { static $static_property = "I'm static"; function get_sp() { return self::$static_property; } } ?>

Inheritance

<?php
class base
{
    // properties and methods
    function functionX()
    {
        // statements
    }
}

class subclass extends base
{
    // more properties and methods
    function functionX()
    {
        // statements
    }
    
    function functionY()
    {
        parent::functionX(); // calls function in base class with same name
        self::functionX(); // calls function in current class
    }
}
?>

Subclass constructors

Most object orientated languages will call constructor of base classes start with the class at the base of the heirrachy. PHP does not. You have to explicitly call the base class constructor for a super class if you want to be invoked.

<?php
class base
{
    function __construct()
    {
    // statements
    }
}

class subclass extends base
{
    function __construct()
    {
        parent::__construct(); // call the parent constructor
    }
}
?>

Arrays

Arrays may use either indexed by number starting from 0 or may be associative arrays. Each type has its own syntax for adding, changing and retrieving values.

Indexed arrays

<?php
$paper[] = "Copier";
$paper[] = "Inkjet";
$paper[] = "Laer";
$paper[] = "Photo";

OR
        
$paper[0] = "Copier";
$paper[1] = "Inkjet";
$paper[2] = "Laer";
$paper[3] = "Photo";

foreach ($paper as $item)
{
    echo "$j: $item
"; ++$j; } ?>

Associative arrays

<?php
$paper['copier'] = "Copier & Multipurpose";
$paper['inkjet'] = "Inkjet Printer";
$paper['laser'] = "Laser Printer";
$paper['photo'] = "Photographic Paper";

OR

$paper = array(
'copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"
);

foreach ($paper as $item => $description)
    echo "$item: $description";

OR

while (list($item, $description) = each($paper))
{
    echo "$item: $description";
}
?>

is_array()

You can check that a variable holds an array before using an array operator on it.

<?php
if (is_array($var))
{
// statements
}
?>

count()

<?php
echo count($fred); // number of elements in 1 dimensional array
echo count($fred, 0); // number of top level elements in multidimensional array
echo count($fred, 1); // total number of elements in multidimensional array
?>

sort()

Sort() sorts the array in place and returns TRUE if the sort completes successfully.

<?php
sort($fred, SORT_NUMERIC);
sort($fred, SORT_STRING);
rsort($fred, SORT_NUMERIC); // sort in rverse order
rsort($fred, SORT_STRING); // sort in rverse order
?>

shuffle()

<?php
shuffle($cards); // puts elements into a random order
?>

explode

explode() is like split() in other languages. It splits a string into words at a given separator.

<?php
$temp = explode(' ', "This is a sentance");
?>

extract()

extract() can be used to create variables from an associative array such as th array from a form submitted using GET or POST

<?php
extract($_GET);
extract($_POST);
?>

To avoid conflicts with existing variables, you can specify a prefix to be added to the name of each of the variables created

<?php
extract($_GET, EXTR_PREFIX_ALL, 'fromget');
extract($_POST, EXTR_PREFIX_ALL, 'frompost');
?>

Compact

compact() can be used to create an associative array from a set of variables.

<?php
$forename = "Fred";
$surname = "Bloggs";
$phone = "01234 56789";
$contact = compact('forename',surname,'phone');
?>

reset()

When for foreach...as construct or the each function walks through array, they keep an internal PHP pointer that makes a note of which element of the array they should return next. You can return to the start of the array using reset() which also returns the first element of the array.

<?php
reset($fred); // discard the return value
$item = reset($fred);
?>

end()

end() move the internal PHP pointer to the last element of the array and return that element.

<?php
end($fred); // discard the return value
$item = end($fred);
?>

printf()

The printf() function in PHP is like that in C so I won't detail that here.

sprintf()

The sprintf() function in PHP is like that in C except that the string constructed is returned instead of saved in the first parameter.

<?php
$out = sprintf("customer name is %s %s", $forename, $surname);
?>

time()

time() returns the numbers of seconds sine 1 Jan 1970. This is a Unix convention.

<?php
echo time();
?>

mktime()

mktime() creates a date and time using the same covnetion as time() using these parameters:

<?php
hour (0-23)
minute (0-59)
seconds (0-59)
month (1-12)
day (1-31)
year (1970-2038 or 1901-2038 with PHP 5.10+)

echo mktime(0,0,0,1,1,2000);  // start of 1 Jan 2000
?>

date()

date() can be used to display Unix time in many different formats not detailed here. The date constants DATE_ATOM, DATE_COOKIE, DATE_RSS and DATE_W3C provide an easy way of providing some common formats.

<?php
echo date(DATE_W3C, time());
?>

checkdate()

checkdate() can be used to check a date is valid

<?php
if (checkdate($month, $day, $year) == TRUE)
{
    echo "Date is valid";
}
else
{
    echo "Date is invalid";
}
?>

File handling

file_exists()

<?php
if (file_exists("testfile.txt") == TRUE)
{
    echo "file exists";
}
?>

Creating a file

<?php
$filehandle = fopen("testfile.txt", w) or die("Failed to create file");
fwrite($filehandle, $test) or die("Could not write to file");
fclose($filehandle);
?>

fopen() modes

rRead from start
r+Read from start and allow writing
wWrite from start and truncate file
w+Write from file start, truncate file and allow reading
aAppend to file end
a+Append to file end and allow reading

Reading a file

<?php
$filehandle = fopen("testfile.txt", 'r') or die("File does not exist or you do not have permission");        
$line = fgets($filehandle);
fclose($filehandle);
echo $line;
        
OR

$filehandle = fopen("testfile.txt", 'r') or die("File does not exist or you do not have permission");        
$text = fgets($filehandle, 3);  // read 3 characters
fclose($filehandle);
echo $text;
?>

Copying a file

<?php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
?>

Renaming and moving files

<?php
if (rename('testfile.txt','testfile2.txt') == FALSE)
{
    echo "Could not rename file";
}
?>

Deleting a file

<?php
if (unlink('testfile.txt') == FALSE)
{
        echo("Could not delete file");
}
?>

Updating files

<?php
$filehandle = fopen("testfile.txt", 'r+') or die("Failed to open file");
$text = fget($filehandle);
fseek($filehandle, 0, SEKK_END);
fwrite($filehandle, "$text") or die("Could not write to file");
fclose($filehandle);
echo "File 'testfile.txt' successfully updated";
?>

Locking files for multiple access

<?php
$filehandle = fopen("testfile.txt", 'r+') or die("Failed to open file");
$text = fget($filehandle);

if (flock($filehandle, LOCK_EX) == TRUE)
{
    fseek($filehandle, 0, SEKK_END);
    fwrite($filehandle, "$text") or die("Could not write to file");
    flock($filehandle, LOCK_UN)
}
fclose($filehandle);
echo "File 'testfile.txt' successfully updated";
?>

Note: The flock() function is not supported on all operating systems Note: flock() only creates an advisory lock. It depends on other code that accesses the file also using flock(). Code the does not call flock() before accessing a file can still access it.

Reading an entire file

<?php
echo file_get_contents("testfile.txt");
?>

Uploading files

<?php // upload.php
echo <<<_END
<html>
<head>
<title>PHP Form Upload</title>
</head>
<body>
<form method='post' action='upload.php' enctype='multipart/form-data'>
Select file: <input type='file' name='filename' size='10' />
<input type='submit' value='Upload' />
</form>
__END

if ($_FILES)
{
    $name = $_FILES['filename']['name'];
    move_uploaded_file($_FILES['filename']['tmp_name'], $name);
    echo "Uploaded image '$name'<br /><img src='$name' />
}

echo "</body>";
echo "</html>";
?>

Note: Uploaded file will automatically be deleted when the PHP program ends so files need to copied to another location to preserve them if needed.

Unusual characters can be removed from the filename like this

<?php
$name = ereg_replace("[^A-Za-z0-9.]", "", $name);
?>

Using $_FILES

$_FILES is an associatve array

$_FILES['file']['name'] The name of the uploaded file e.g. smiley.jpg
$_FILES['file']['type'] The content type of the file r.g. image/jpeg
$_FILES['file']['size'] The file's size in bytes
$_FILES['file']['tmp_name'] The name of the temporary file stored on the server
$_FILES['file']['error'] Te error code resulting from the file upload

File validation

<?php // upload.php
if ($_FILES)
{
    $name = $_FILES['filname']['name'];
    
    switch($_FILES['filname']['type'])
    {
        case 'image/jpeg': $ext = 'jpg'; break;
        case 'image/gif': $ext = 'gif'; break;
        case 'image/png': $ext = 'png'; break;
        case 'image/tiff': $ext = 'tif'; break;
        default: $ext = ''; break;
    }
    if ($ext)
    {
        $n = 'image.$ext';
        move_uploaded_file($_FILES['filename']['tmp_name'], $n);
        echo "Uploaded image '$name' as '$n':<br />"
        echo "<img src='$n' />";
    }
    else
    {
        echo "'$name' is not an accepted image file";
    }
}
else
{
    echo "No image has been uploaded";
}
?>

System Calls

The exec() function can be used to call operating system commands by passing these parameters:

The command to run (operating system dependent)
An array to hold the output of the command
A variable to hold the return status of the command
<?php
$cmd = "ls"; // Linux
exec(escapeshellcmd($cmd), $output, $status);

if ($status)
{
    echo "Exec command failed";
}
else
{
    echo <pre>;
    foreach($output as $line) echo "$line\n";
    echo </pre>;    
}
?>

Note: System calling functions may have been turned off on your system as a security risk

Note: Calling systems functions may be slow because it requires starting an instance of the operating system shell

Connecting to MySQL database

<?php
        $db_hostname = 'localhost';
        $db_database = 'publications';
        $db_username = 'userame';
        $db_password = 'password';
        
        $db_server = mysql_connect($db_hostname, $db_username, $db_password);
        if ($db_server == FALSE)
        {
            die("Unable to connect to MySQL: ", mysql_error());
        }
        
        if (mysql_select($db_database) == FALSE)
        {
            die("Unable to select database: ", mysql_error());        
        }
        
        $query = "SELECT * from clssics";
        $result = mysql_query($query);
        
        if ($result == FALSE)
        {        
            die("Database access failed: ", mysql_error());        
        }
        
        // see next section for how to read the results
        
        mysql_close($db_server);
?>
    

Curiously the MySQL link identifier returned from mysql_connect() is not used again except to close the connection to the MySQL server.

Reading MySQL results

MySQL results can be read either by individual cells or by rows

<?php
$rows = mysq_num_rows($results);

for($rowIndex = 0; $rowIndex < $rows; ++$rowIndex)
{
    echo 'Author: '.mysql_result($result, $rowIndex, 'author').'<br />';
    echo 'Title: '.mysql_result($result, $rowIndex, 'title').'<br />';
    echo 'Category: '.mysql_result($result, $rowIndex, 'category').'<br />';
    echo 'Year: '.mysql_result($result, $rowIndex, 'year').'<br />';
    echo 'ISBN: '.mysql_result($result, $rowIndex, 'isbn').'<br /><br />';
}
?>
    

OR

<?php
$rows = mysq_num_rows($results);

for($rowIndex = 0; $rowIndex < $rows; ++$rowIndex)
{
    echo 'Author: '.$row[0].'<br />';
    echo 'Title: '.$row[1].'<br />';
    echo 'Category: '.$row[2].'<br />';
    echo 'Year: '.$row[3].'<br />';
    echo 'ISBN: '.$row[4].'<br /><br />';
}
?>
    

Potecting from SQL injection

<?php
$name = $_POST['name'];
if (get_magic_quotes_gpc())
{
    $name = stripslashes($name);
}
$name = mysql_real_escape_string($name);
?>
    

Reading data from HTML forms

<?php
if (isset($_POST['name']) == TRUE)
{
    $name = $_POST['name'];
}
?>
    

OR

?>
<?php
if (isset($_GET['name']) == TRUE)
{
    $name = $_GET['name'];
}
?>
    

Home page