Archive

Posts Tagged ‘Cookies’

PHP – Advanced

February 8th, 2009 No comments

This article will guide you through some of the more complex features of PHP. a more basic introduction article is also available.

User Data

When browsing the internet you will come across some websites that store information about you or your visits to the site. There are two main methods of storing this data, these are through Cookies and Sessions.

Cookies

Cookies are the older of the two methods, it consists of a client side file that the browser writes to. With PHP you can create new cookies and also retrieve existing values, examples of both are below

To create new cookies the setcookie function is used, the main parameters are:

  • Name – The Name of the cookie
  • Value – Data that the cookie is to store
  • Expire – Time & Date when the cookie will expire

When creating cookies in PHP you must call the setcookie function before any HTML tags are used in the page, an example is shown below:

<?PHP
setcookie(“yeltuor”, “MyValue”, time()+86400);
?>
<HTML>
<BODY>
The cookie named yeltuor has been ’set’
It will expire 24 Hours (86400 seconds) from now.
</BODY>
</HTML>

With the cookie now created, the next stage is to read back the values stored in it. The values in the cookie can be called in the same way variables are:

<HTML>
<BODY>
<?PHP
//Check whether the cookie named yeltuor is set
if (isset($_COOKIE["yeltuor"]))
echo “Welcome back ” . $_COOKIE["yeltuor"] . “<br>”;
else
echo “Welcome newbe <br>”;
?>
</BODY>
</HTML>

Sessions

A Sessions is a server side file that is written to, again PHP support the creation and retrieval of session data. When a session is created a unique session ID is used to reference it, this is all taken care within the underlying PHP code.

The advantage of using sessions is that the user can’t view or edit the data within them; unlike the client side cookie’s. Before using sessions on a PHP page, the session_start(); function must be called, after this a session can be created, however like the cookie functions all session calls must be done before any HTML code on the page:

Below is an example of setting up a server side session:

<?PHP
//start session
session_start();
//if session variable total doesn’t exist create one
if(!isset($_SESSION['total']))
$_SESSION['total'] = ‘0′;
?>
<HTML>
<BODY>
The session variable total set to 0, unless it already existed.
</BODY>
</HTML>

To reference existing session variables and dispose of variables that are no longer required, the following code can be used:

<?PHP
//start session
session_start();
?>
<HTML>
<BODY>
<?PHP
echo “The total is ” . $_SESSION['total'];
//Finished with session variable, disposing of it
unset($_SESSION['total']);
?>
</BODY>
</HTML>

For the security minded individuals, a list of more advanced session functions that are available can be seen here.

Files

PHP supports various file related operations, some examples are below:

Opening a file is done with the fopen( ); function, the first parameter is the filename, the second is the mode to open the file in:

Mode Description
r Read Only, pointer at the beginning of the file
r+ Read and Write, pointer at the beginning of the file
w Write Only, existing file will be truncated or new file will be created.
w+ Write and Read, existing file will be truncated or new file will be created.
a Write Only, Places pointer at end of the file or new file will be created.
a+ Write and Read, Places pointer at end of the file or new file will be created.
x Write Only, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.
x Write and Read, If the file already exists the fopen( ) function will return FALSE, or a new file will be created.

Some examples of using the fopen( ) function are below:

<HTML>
<BODY>
<?PHP
//Open file hello.txt, in the case of an error exit
$f=fopen(“hello.txt”,”r”) or exit(“Cant open file”);
//if reached the end of the file
if (feof($f))
echo “End of file”;
//Loop through file 1 char at a time, echo value
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
//Close file handle when finished
fclose($f) ;
?>
</BODY>
</HTML>

This function below accepts a parameter of a filename and location and returns the file data as a variable called contents:

function fileContents($filename){
// get contents of a file into a string
$f = fopen($filename, “r”);
$contents = fread($f, filesize($filename)) ;
fclose ($f);
return $contents;
}

Functions

Functions are used in the same way that procedures are used in other programming languages, they are used to aid with the re-use of code. examples of using functions can be seen below:

<HTML>
<BODY>
<?PHP
function echoHelloWorld($name)
{
echo “Hello World my name is ” . $name;
}
//Using the created function
echoHelloworld(“Borris”)
?>
</BODY>
</HTML>

Functions can also return values as an output by the return command from within the function.

<HTML>
<BODY>
<?PHP
function addnum($num1,$num2)
{
$tot = $num1 + $num2;
return $tot;
}
//Using the function addnum
echo “1 + 2 = ” . addNum(1,2);
?>
</BODY>
</HTML>

Require

The require function works in the same way as a function, except that it is used to call another file which is inserted into the current page. This is useful when a header is being used;

<HTML>
<BODY>
<?PHP
require(“header.php”)
?>
<h3>More text here.</h3>
</BODY>
</HTML>

Email

PHP has built in email support by using the mail() function, it requires the usual email parameters;

Parameter Description
to The recipients address in the form of abc@xyz.com
subject Subject of the email
message Content of the email; use the \n command for a new line
headers An optional parameter which may contain and Cc’s of Bcc’s
parameters Additional parameters that the sendmail program accepts i.e. From

An example of the code for a mail function with error checking is shown below, to send emails to multiple recipients, a comma: , should be used as a delimiter.

<HTML>
<BODY>
<?PHP
$to = “bob@email.com”;
$subject = “Test email”;
$message = “Hello! World \n this is a test email”;
$from = “tom@email.com”;
$headers = “From: $from”;
if (mail($to,$subject,$message,$headers))
echo “Mail Sent sucessfully”;
else
echo “Failed to Send Mail”;
?>
</BODY>
</HTML>

This is very basic example of using emailing, however for a more complete guide to PHP emailing please see PHP Mail article.