Wednesday 28 August 2013

PHP File Uploading

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini
The process of uploading a file follows these steps
  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
  • The user clicks the browse button and selects a file to upload from the local PC.
  • The full path to the selected file appears in the text filed then the user clicks the submit button.
  • The selected file is sent to the temporary directory on the server.
  • The PHP script that was specified as the form handler in the form's action attribute checks that the file has arrived and then copies the file into an intended directory.
  • The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.

Creating an upload form:

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/php/file_uploader.php" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This will display following result:
File Upload:
Select a file to upload: 







NOTE: This is just dummy form and would not work.

Creating an upload script:

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables:
  • $_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web server.
  • $_FILES['file']['name'] - the actual name of the uploaded file.
  • $_FILES['file']['size'] - the size in bytes of the uploaded file.
  • $_FILES['file']['type'] - the MIME type of the uploaded file.
  • $_FILES['file']['error'] - the error code associated with this file upload.
The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page to /var/www/html directory which is document root of your PHP server and it will display all the file's detail upon completion. Please note that if you are going to display uploaded file then don't try with binary files like images or word document.
Here is the code of uploader.php script which will take care of uploading a file.
<?php
if( $_FILES['file']['name'] != "" )
{
   copy( $_FILES['file']['name'], "/var/www/html" ) or 
           die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name'];  ?>
<li>File size: <?php echo $_FILES['file']['size'];  ?> bytes
<li>File type: <?php echo $_FILES['file']['type'];  ?>
</ul>
</body>
</html>
When you will upload a file using upload form and upload script, it will display following result:
Uploaded File Info:
  • Sent file: uploadedfile.txt
  • File size: 2003 bytes
  • File type: image/jpg
You try out above example yourself on your webserver. If you have any problem then post it to Discussion Forums to get any further help.

PHP Coding standard

Every company follows a different coding standard based on their best practices. Coding standard is required because there may be many developers working on different modules so if they will start inventing their own standards then source will become very un-manageable and it will become difficult to maintain that source code in future.
Here are several reasons why to use coding specifications:
  • Your peer programmers have to understand the code you produce. A coding standard acts as the blueprint for all the team to decipher the code.
  • Simplicity and clarity achieved by consistent coding saves you from common mistakes.
  • If you revise your code after some time then it becomes easy to understand that code.
  • Its industry standard to follow a particular standard to being more quality in software.
There are few guidelines which can be followed while coding in PHP.
  • Indenting and Line Length - Use an indent of 4 spaces and don't use any tab because different computers use different setting for tab. It is recommended to keep lines at approximately 75-85 characters long for better code readability.
  • Control Structures - These include if, for, while, switch, etc. Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional.
    Examples:
    if ((condition1) || (condition2)) {
        action1;
    } elseif ((condition3) && (condition4)) {
        action2;
    } else {
        default action;
    }
    You can writ eswitch statements as follows:
    switch (condition) {
    case 1:
        action1;
        break;
    
    case 2:
        action2;
        break;
    
    default:
        defaultaction;
        break;
    }
  • Function Calls - Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:
    $var = foo($bar, $baz, $quux);
  • Function Definitions - Function declarations follow the "BSD/Allman style":
    function fooFunction($arg1, $arg2 = '')
    {
        if (condition) {
            statement;
        }
        return $val;
    }
  • Comments - C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged.
  • PHP Code Tags - Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PHP compliance and is also the most portable way to include PHP code on differing operating systems and setups.
  • Variable Names -
    • Use all lower case letters
    • Use '_' as the word separator.
    • Global variables should be prepended with a 'g'.
    • Global constants should be all caps with '_' separators.
    • Static variables may be prepended with 's'.
  • Make Functions Reentrant - Functions should not keep static variables that prevent a function from being reentrant.
  • Alignment of Declaration Blocks - Block of declarations should be aligned.
  • One Statement Per Line - There should be only one statement per line unless the statements are very closely related.
  • Short Methods or Functions - Methods should limit themselves to a single page of code.
There could be many more points which should be considered while writing your PHP program. Over all intension should be to be consistent throughout of the code programming and it will be possible only when you will follow any coding standard. YOu can device your own standard if you like something different.

PHP Sessions

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file calledsession.save_path. Bore using any session variable make sure you have setup this path.
When a session is started following things happen:
  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>

Destroying a PHP Session:

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is the example to unset a single variable:
<?php
   unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
   session_destroy();
?>

Turning on Auto Session:

You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies:

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to another page using SID.
<?php
   session_start();

   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

PHP-Sending Emails

PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.
The configuration for Windows should look something like this:
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = webmaster@tutorialspoint.com
Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.
The configuration for Linux should look something like this:
[mail function]
; For Win32 only.
SMTP = 

; For win32 only
sendmail_from = 

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i
Now you are ready to go:

Sending plain text email:

PHP makes use of mail() function to send an email. This function requires three mandatory arguments that specify the recipient's email address, the subject of the the message and the actual message additionally there are other two optional parameters.
mail( to, subject, message, headers, parameters );
Here is the description for each parameters.
ParameterDescription
toRequired. Specifies the receiver / receivers of the email
subjectRequired. Specifies the subject of the email. This parameter cannot contain any newline characters
messageRequired. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headersOptional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parametersOptional. Specifies an additional parameter to the sendmail program
As soon as the mail function is called PHP will attempt to send the email then it will return true if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma separated list.

Example:

Following example will send an HTML email message to xyz@somedomain.com. You can code this program in such a way that it should receive all content from the user and then it should send an email.
<html>
<head>
<title>Sending email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "This is simple text message.";
   $header = "From:abc@somedomain.com \r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )  
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending HTML email:

When you send a text message using PHP then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But PHP provides option to send an HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set to send an HTML email.

Example:

Following example will send an HTML email message to xyz@somedomain.com copying it to afgh@somedomain.com. You can code this program in such a way that it should recieve all content from the user and then it should send an email.
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
   $to = "xyz@somedomain.com";
   $subject = "This is subject";
   $message = "<b>This is HTML message.</b>";
   $message .= "<h1>This is headline.</h1>";
   $header = "From:abc@somedomain.com \r\n";
   $header = "Cc:afgh@somedomain.com \r\n";
   $header .= "MIME-Version: 1.0\r\n";
   $header .= "Content-type: text/html\r\n";
   $retval = mail ($to,$subject,$message,$header);
   if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>

Sending attachments with email:

To send an email with mixed content requires to set Content-type header tomultipart/mixed. Then text and attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number which can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create unique number. A final boundary denoting the email's final section must also end with two hyphens.
Attached files should be encoded with the base64_encode() function for safer transmission and are best split into chunks with the chunk_split() function. This adds \r\n inside the file at regular intervals, normally every 76 characters.
Following is the example which will send a file /tmp/test.txt as an attachment. you can code your program to receive an uploaded file and send it.
<html>
<head>
<title>Sending attachment using PHP</title>
</head>
<body>
<?php
  $to = "xyz@somedomain.com";
  $subject = "This is subject";
  $message = "This is test message.";
  # Open a file
  $file = fopen( "/tmp/test.txt", "r" );
  if( $file == false )
  {
     echo "Error in opening file";
     exit();
  }
  # Read the file into a variable
  $size = filesize("/tmp/test.txt");
  $content = fread( $file, $size);

  # encode the data for safe transit
  # and insert \r\n after every 76 chars.
  $encoded_content = chunk_split( base64_encode($content));
  
  # Get a random 32 bit number using time() as seed.
  $num = md5( time() );

  # Define the main headers.
  $header = "From:xyz@somedomain.com\r\n";
  $header .= "MIME-Version: 1.0\r\n";
  $header .= "Content-Type: multipart/mixed; ";
  $header .= "boundary=$num\r\n";
  $header .= "--$num\r\n";

  # Define the message section
  $header .= "Content-Type: text/plain\r\n";
  $header .= "Content-Transfer-Encoding:8bit\r\n\n";
  $header .= "$message\r\n";
  $header .= "--$num\r\n";

  # Define the attachment section
  $header .= "Content-Type:  multipart/mixed; ";
  $header .= "name=\"test.txt\"\r\n";
  $header .= "Content-Transfer-Encoding:base64\r\n";
  $header .= "Content-Disposition:attachment; ";
  $header .= "filename=\"test.txt\"\r\n\n";
  $header .= "$encoded_content\r\n";
  $header .= "--$num--";

  # Send email now
  $retval = mail ( $to, $subject, "", $header );
  if( $retval == true )
   {
      echo "Message sent successfully...";
   }
   else
   {
      echo "Message could not be sent...";
   }
?>
</body>
</html>
You try all the above examples. If you face any problem then you can post that problem in discussion forum.

PHP Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • Browser stores this information on local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
This chapter will teach you how to set cookies, how to access them and how to delete them.

The Anatomy of a Cookie:

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; 
                 path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].

Setting Cookies with PHP:

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:
  • Name - This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • Value -This sets the value of the named variable and is the content that you actually want to store.
  • Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
  • Path -This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • Domain - This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
  • Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Following example will create two cookies name and age these cookies will be expired after one hour.
<?php
   setcookie("name", "John Watkin", time()+3600, "/","", 0);
   setcookie("age", "36", time()+3600, "/", "",  0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies.Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
You can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
  if( isset($_COOKIE["name"]))
    echo "Welcome " . $_COOKIE["name"] . "<br />";
  else
    echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired:
<?php
  setcookie( "name", "", time()- 60, "/","", 0);
  setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

PHP Files and I/O

This chapter will explain following functions related to files:
  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
ModePurpose
rOpens the file for reading only.
Places the file pointer at the beginning of the file.
r+Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
wOpens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
w+Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
aOpens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
a+Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

Reading a file

Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
  • Open a file using fopen() function.
  • Get the file's length using filesize() function.
  • Read the file's content using fread() function.
  • Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>

<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
   echo ( "Error in opening file" );
   exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

</body>
</html>

Writing a file

A new file can be written or text can be appended to an existing file using the PHP fwrite()function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.
The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
   echo ( "Error in opening new file" );
   exit();
}
fwrite( $file, "This is  a simple test\n" );
fclose( $file );
?>

<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>

<?php
if( file_exist( $filename ) )
{
   $filesize = filesize( $filename );
   $msg = "File  created with name $filename ";
   $msg .= "containing $filesize bytes";
   echo ($msg );
}
else
{
   echo ("File $filename does not exit" );
}
?>
</body>
</html>
We have covered all the function related to file input and out in PHP File System Functionchapter.

PHP Functions and cookies

PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
  • Creating a PHP Function
  • Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
Please refer to PHP Function Reference for a complete set of useful functions.

Creating PHP Function:

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>

<?php
/* Defining a PHP Function */
function writeMessage()
{
  echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
You are really a nice person, Have a nice time!

PHP Functions with Parameters:

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is : 30

Passing Arguments by Reference:

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
   $num += 5;
}

function addSix(&$num)
{
   $num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result:
Original Value is 15
Original Value is 21 

PHP Functions retruning value:

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>
This will display following result:
Returned value from the function : 30

Setting Default Values for Function Parameters:

You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function printMe($param = NULL)
{
   print $param;
}
printMe("This is test");
printMe();
?>

</body>
</html>
This will produce following result:
This is test

Dynamic Function Calls:

It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
   echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
This will display following result:
Hello

PHP GET and POST Methods

There are two ways the browser client can send information to the web server.
  • The GET Method
  • The POST Method
Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
  • The GET method produces a long string that appears in your server logs, in the browser's Location: box.
  • The GET method is restricted to send upto 1024 characters only.
  • Never use GET method if you have password or other sensitive information to be sent to the server.
  • GET can't be used to send binary data, like images or word documents, to the server.
  • The data sent by GET method can be accessed using QUERY_STRING environment variable.
  • The PHP provides $_GET associative array to access all the sent information using GET method.
Try out following example by putting the source code in test.php script.
<?php
  if( $_GET["name"] || $_GET["age"] )
  {
     echo "Welcome ". $_GET['name']. "<br />";
     echo "You are ". $_GET['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="GET">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
  • The POST method does not have any restriction on data size to be sent.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
  • The PHP provides $_POST associative array to access all the sent information using GET method.
Try out following example by putting the source code in test.php script.
<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">

  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />

  <input type="submit" />
  </form>
</body>
</html>

The $_REQUEST variable

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
  if( $_REQUEST["name"] || $_REQUEST["age"] )
  {
     echo "Welcome ". $_REQUEST['name']. "<br />";
     echo "You are ". $_REQUEST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">

  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />

  <input type="submit" />
  </form>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.

PHP File Inclusion

You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.
  • The include() Function
  • The require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousand of files just change included file.

The include() Function

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php with the following content.
<a href="http://www.tutorialspoint.com/index.htm">Home</a> - 
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> - 
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> - 
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />
Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
This will produce following result
Home - ebXML - AJAX - PERL
This is an example to show how to include PHP file. You can include mean.php file in as many as files you like!

The require() Function

The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.
<html>
<body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This will produce following result
This is an example to show how to include wrong PHP file!
Now lets try same example with require() function.
<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This time file execution halts and nothing is displayed.
NOTE: You may get plain warning messages or fatal error messages or nothing at all. This depends on your PHP Server configuration.

PHP Web Concepts

This session demonstrates how PHP can provide dynamic content according to browser type, randomly generated numbers or User Input. It also demonstrated how the client borwser can be redirected.

Identifying Browser & Platform

PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment.
One of the environemnt variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.
PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the borwser.
Following example demonstrates how you can identify a client borwser and operating system.
NOTE: The function preg_match()is discussed in PHP Regular expression session.
<html>
<body>
<?php
   $viewer = getenv( "HTTP_USER_AGENT" );
   $browser = "An unidentified browser";
   if( preg_match( "/MSIE/i", "$viewer" ) )
   {
      $browser = "Internet Explorer";
   }
   else if(  preg_match( "/Netscape/i", "$viewer" ) )
   {
      $browser = "Netscape";
   }
   else if(  preg_match( "/Mozilla/i", "$viewer" ) )
   {
      $browser = "Mozilla";
   }
   $platform = "An unidentified OS!";
   if( preg_match( "/Windows/i", "$viewer" ) )
   {
      $platform = "Windows!";
   }
   else if ( preg_match( "/Linux/i", "$viewer" ) )
   {
      $platform = "Linux!";
   }
   echo("You are using $browser on $platform");
?>
</body>
</html>
This is producing following result on my machine. This result may be different for your computer depnding on what you are using.
You are using Mozilla! on Windows!

Display Images Randomly

The PHP rand() function is used to generate a random number.i This function can generate numbers with-in a given range. The random number generator should be seeded to prevent a regular pattern of numbers being generated. This is achieved using the srand() function that specifiies the seed number as its argument.
Following example demonstrates how you can display different image each time out of four images:
<html>
<body>
<?php
  srand( microtime() * 1000000 );
  $num = rand( 1, 4 );
   
  switch( $num ) 
  {
  case 1: $image_file = "/home/images/alfa.jpg";
          break;
  case 2: $image_file = "/home/images/ferrari.jpg";
          break;
  case 3: $image_file = "/home/images/jaguar.jpg";
          break;
  case 4: $image_file = "/home/images/porsche.jpg";
          break;
  }
  echo "Random Image : <img src=$image_file />";
?>
</body>
</html>

Using HTML Forms

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Try out following example by putting the source code in test.php script.
<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>
  • The PHP default variable $_PHP_SELF is used for the PHP script name and when you click "submit" button then same PHP script will be called and will produce following result:
  • The method = "POST" is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POSTchapter.

Browser Redirection

The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading.
The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.
Following example demonstrates how you can redirect a borwser request to another web page. Try out this example by puttingthe source code in test.php script.
<?php
  if( $_POST["location"] )
  {
     $location = $_POST["location"];
     header( "Location:$location" );
     exit();
  }
?>
<html>
<body>
   <p>Choose a site to visit :</p>
   <form action="<?php $_PHP_SELF ?>" method="POST">
   <select name="location">
      <option value="http://w3c.org">
            World Wise Web Consortium
      </option>
      <option value="http://www.google.com">
            Google Search Page
      </option>
   </select>
   <input type="submit" />
   </form>
</body>
</html>

Displaying "File Download" Dialog Box

Sometime it is desired that you want to give option where a use will click a link and it will pop up a "File Download" box to the user in stead of displaying actual content. This is very easy and will be achived through HTTP header.
The HTTP header will be different from the actual header where we send Content-Type astext/html\n\n. In this case content type will be application/octet-stream and actual file name will be concatenated alongwith it.
For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows.
#!/usr/bin/perl

# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";

# Actual File Content
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) )
{
   print("$buffer");
}