Archive for the ‘PHP code of the week’ Category

PHP COTW: create, add, read and remove files

Monday, July 23rd, 2007

In this weeks PHP code of the week we cover the use of files: how to create, add content, read the file contents and delete them. Before you should consider any of the code below you should always perform checks say to make sure the file exists, is readable/writeable, etc.

Create Files

Firstly we want to create a file with no content which is easily done in PHP using the code below.

[php]$filename = ‘test.txt’;
fopen($filename, ‘a’);[/php]

We specify the filename which is test.txt and we use the fopen (file open) function to use the file. As the test.txt file doesn’t exist in our system, in order to use the file PHP creates the file for us.

The second parameter in fopen is the mode parameter and in our case we are using ‘a’ which means append and it appends any content we would of wrote to the file to the end of the file. You could also use ‘r’, ‘w’ and ‘x’ for the second parameter (more information can be found at the website).

Add Content

We will now add some content into the file as shown below.

[php]$filename = ‘test.txt’;
$content = “Some content here”;

$handle = fopen($filename, ‘a’);
fwrite($handle, $content);

So now we have specified some content to append (write) to our file. We open the file as usual, specify the open file reference to the $handle variable and then we use the function fwrite to append our content in $content to our file ‘test.txt’. After that content has been written we close the file using the fclose function.

Some checks you can add onto the above code are shown below:

[php]$filename = ‘test.txt’;
$content = “Some content here”;

if (is_writable($filename)) {

if ($handle = fopen($filename, ‘a’)) {

if (fwrite($handle, $somecontent)) {
echo “Success”;

Read Files

As for reading the file there are many functions available which include file(), fopen() and file_get_contents(). In our case as we might want to get a certain line of information we can use the file() function as seen below.

[php] $filein = file(‘test.txt’);
echo $filein[0]; // Output the first line of the file
echo $filein[2]; // Output the third line of the file [/php]

So we specify the file we want to read and assign the file to the variable $filein. The file function creates a element in the variable array for each line. So the first element in the array is 0 and that would be line 1 in our file.

Now say we wanted to edit a certain line and replace that line we would have to find the line in the file, replace that line with the new line and use fopen and fwrite to re-write the entire file with the replaced content.

Delete Files

To delete files we can use the unlink function as shown below. You are just required to input the file you want to remove and that file will be removed.


That’s the basics of using files in PHP. This concludes our PHP code of the week, you should now know most of the basics and regularly used functions to help you develop or improve your own code. (If you ever want to find out what a certain PHP function does, just look it up on

PHP COTW: sessions

Sunday, July 15th, 2007

In this weeks PHP code of the week we cover the use of session; how to create, add, extract and delete them.

Sessions are another way that you can store information about a user and use that information on another page. They work by storing temporary information in a session id which is stored on the local user’s computer or is passed through in the URL. Sessions must be the first thing listed in the PHP file or else you’ll run into problems.

Below is an example of how the session function would be used in a file and how we store information in the session.

header(“Cache-control: private”); //IE 6 Fix

$_SESSION[‘username’] = $form_username;
$_SESSION[‘password’] = $form_password;[/php]

Firstly we start/access the session using the session_start() function and below that is just an IE 6 Fix for session. We the use the $_SESSION[‘name’] to store information into the session.

Checking for a session is simple and you can check the specific variable name you assigned. We can extract session information as we did with cookies.

[php]if($_SESSION[‘username’]) {

// Session present code
$username = $_SESSION[‘username’]);
$password = $_SESSION[‘password’]);


To remove the session we unset all the of session data and then we destroy the session.

[php]$_SESSION = array();

There you have an overview on how to use sessions. Sessions are similar to cookies and are being used more often than cookies. In the next PHP code of the week we’ll cover using creating, editing and deleting files in PHP

PHP COTW: cookies

Sunday, July 8th, 2007

In this weeks PHP code of the week we cover the use of cookies; how to create, add, extract and delete them.

Cookies are one of the ways that you can store information about a user and use that information on another page. They work by creating a text file on a user’s computer and retrieving that information when been called by in other pages. Cookies have the ability to expire at a certain time which can be set by the code creating them.

Below is an example of how we set a cookie and in this example the cookie contains a username and password.

[php]$username = “Alex”;
$password = “mypass”;
$cookie_data = $username . ‘-‘ . $password;

if(setcookie(“cookie_info”, $cookie_data, time()+3600) == FALSE) {

echo “You computer does not support cookies.”;


We have $username and $password set and we are combining the username and password values with a hyphen in between them.

We use the setcookie() function to set the cookie and specify the cookie name (cookie_info), the value that it will be assigned ($cookie_data) and the time it will expire (the current time + 3600 seconds which is 1 hour).  Other paramarters you can specify are the domain and path the cookie is only allowed to be accessed from, if the cookie can only be sent over HTTPs or only by a HTTP connection.

The setcookie function is wrapped in an if statement which allows us to perform an action if setting the cookie was unsuccessful, in this case it would print out “You computer does not support cookies”.

You can check if there is a cookie present by using the isset command we covered in our earlier PHP code of week. We can the cookie by using $_COOKIE[‘name’].

[php]if (isset($_COOKIE[‘cookie_info’])) {

$cookie_info = explode(“-“, $_COOKIE[‘cookie_info’]);
$username = $cookie_info[0];
$password = $cookie_info[1];


If the cookie is present we can extract the cookies information. We have both the username and password in a string, so we use the explode function to break the string into username and password.

Say once a user logs out and we want to delete the cookie we can use the set cookie function and we just can just set the expiration time to be 1 hour ago so that it will remove the cookie straight away. We don’t need to specify a value as we want the cookie to contain no information.

[php]if (isset($_COOKIE[‘cookie_info’])) {

setcookie (“cookie_info”, “”, time() – 3600);


There you have an overview on how to use cookies. In the next PHP code of the week we’ll talk about using sessions, another way to store and retrieve user information.

PHP COTW: implode and explode

Sunday, July 1st, 2007

This weeks PHP code of the week is implode and explode which allow you to combine arrays and split up chunks of text by certain characters.

implode as mentioned above allows you to combine an array with more than one element into a string with elements separated by certain characters.

Say we have a username, address and suburb in an array and want to combine it into one string to save space, we could use implode like so.

[php]$myarray[0] = “alex”;
$myarray[1] = “123 fake st”;
$myarray[2] = “sunnybank”;

$mycombinedstring = implode(“|”, $myarray);

echo $mycombinedstring; // Prints alex|123 fake st|sunnybank[/php]

It’s recommended that the certain character or characters be some character that you don’t accept in user input or some special code if needed.

explode is basically the opposite of implode, it breaks up a string based on certain characters and places each chunk into an element of the choose array.

[php]$mycombinedstring = “alex|123 fake st|sunnybank”;

$myarray = explode(“|”, $mycombinedstring);

echo $myarray[0]; // Prints alex
echo $myarray[1]; // Prints 123 fake st
echo $myarray[2]; // Prints sunnybank[/php]

Using implode and explode is just that simple. In the next PHP code of the week we’ll talk about using cookies.

PHP COTW: mysql_fetch_array, while and count

Sunday, June 24th, 2007

This weeks PHP code of the week is mysql_fetch_array, mysql while rows and count which allow you to retrieve a MySQL row from queries performed, loop through all the rows performing a certain action and how to count an array.

mysql_fetch_array can be used to retrieve the row(s) returned from the query and be placed into an associative array. Say if we wanted to retrieve user details such as name, address and suburb by using a username we could do something as shown below.

[php]$sql = “SELECT name, address, suburb FROM userdata WHERE username = ‘alex'”;

if ( !($result = mysql_query($sql)) ) {
die(‘Could not query users table’);

$userdata = mysql_fetch_array($result, MYSQL_ASSOC);[/php]

So we have the standard SQL query been performed and then we use mysql_fetch_array with the arguments as our result from the MySQL query and the second argument saying that we want an associative array.

This means that name, address and suburb are in the array of $userdata. An array is a variable which can contain other variables at different ‘addresses’. Arrays are in the format shown below.

[php]$myarray[0] = “Hi”;
$myarray[1] = 234;
$myarray[5] = “Test”;

echo $myarray[0]; // Prints out Hi
echo $myarray[1]; // Prints out 234
echo $myarray[5]; // Prints out Test[/php]

The start of an array always begins at 0 and it’s important to remember this as sometimes you may forget and it’s naturally to believe 1 should be the start of the array.

So regarding our $userdata example, we used an associative array and therefore the array is not indexed by numbers but rather words. In this case we always put the word in quotation marks. In this case the words are the columns we have selected our query to return to us.

[php]echo $userdata[‘name’]; // Prints out the user’s name
echo $userdata[‘address’]; // Prints out the user’s address
echo $userdata[‘suburb’]; // Prints out the user’s suburb[/php]

While is a function that loops until a certain condition is meet. In our case we might want to get a list of all users’ usernames and their address that have the suburb as “Sunnybank”.

[php]$sql = “SELECT username, address FROM userdata WHERE suburb = ‘Sunnybank'”;

if ( !($result = mysql_query($sql)) ) {
die(‘Could not query users table’);

while ($row = mysql_fetch_array($result)) {
echo $row[‘username’] . “ “ . $row[‘address’];

The code above says while there is another row from the result of the MySQL query then print out the username and address. If there are no more rows from the result then $row would be equal to 0 and therefore 0 is false and the while loop would finish.

We could also have something which lets us process the rows at a later time. This could be as a form of an array ($users) as shown below. We left the $users array index empty as while the loop progresses an empty index will assign the current $row to the last available position on the $users array. This means when printing out anything from the $users array we firstly would need a numeric index and then the associative word.

[php]while ($row = mysql_fetch_array($result)) {
$users[] = $row;

echo $users[0][‘name’]; // Prints out the name of the user in the first row[/php]

count can be used to count the number of items in an array. So if our array $users had 3 items ($users[0], $users[1] and $users[2]) then count would return the number 3.

[php]echo count($users); // Prints out 3[/php]

So you should now have an understanding how to use mysql_fetch_array, arrays and the count function. Next week we’ll be covering the implode/explode function.

PHP COTW: mysql_connect, mysql_select_db, mysql_query and mysql_close_db

Sunday, June 17th, 2007

This weeks PHP code of the week is mysql_connect, mysql_select_db and mysql_query which allow you to connect to a MySQL server, select a MySQL database and perform queries on the MySQL database.

mysql_connect allows you to connect to a local or remote MySQL server by the use of our username and password. Below is a common example of what mysql_connect could look like.

[php]$dbconnect = mysql_connect (“localhost”, “myuser”, “mypass”) or die (‘I cannot connect to the database because: ‘ . mysql_error());[/php]

The above mysql_connect uses the MySQL server ‘localhost’ with the username ‘myuser’ and the password ‘mypass’. The next part basically says if it can’t connect to the MySQL server for what ever reason it should terminate the script (‘die’) and print out some text along with the specific MySQL error returned (mysql_error).

mysql_select_db allows you to select the database on the MySQL server. If you have more than one MySQL connection, mysql_select_db has an option to allow you to choose which MySQL connection you are referring to.

[php]mysql_select_db (“mydatabase”);[/php]

To refer to a specific connection:
[php]mysql_select_db (“mydatabase”, $dbconnect2);[/php]

mysql_query enables you to perform SQL commands on the MySQL database which also allows you to perform the query on a specific MySQL connection.

[php]mysql_query(“INSERT INTO users (username, password)
VALUES (‘$form_username’,’$form_password’)”);[/php]

For specific connections do the same as in mysql_select_db:

[php]mysql_query(“INSERT INTO users (username, password)
VALUES (‘$form_username’,’$form_password’)”, $dbconnect2);[/php]

If you would like to know if your mysql_query was performed or not you can do something similar to:

[php]$sql = “INSERT INTO users (username, password)
VALUES (‘$form_username’,’$form_password’)”;

if ( !($result = mysql_query($sql)) ) {
die(‘Could not insert into users table’);

So above if it isn’t successful in the query it will terminate the script and print out the message configured. Generally you shouldn’t print out the mysql_error as you are giving away too much information, more than the average user needs to know.

mysql_close closes the MySQL connection which we have active. Usually this is not needed as all MySQL connections are closed at the end of the file


So there you have the basic functionality of connecting/disconnecting, selecting databases and querying a MySQL Server. Next week we’ll cover fetching rows, looping through rows using while, arrays and count.

PHP COTW: isset and empty

Sunday, June 10th, 2007

The third PHP code of the week is isset and empty which allow you to determine if a variable has a value or not.

isset checks to see if the variable has a value. This function is mostly used for POST and GET variables. If used with POST or GET, it allows you to not have to do the processing for the variables unless they have a value present.

empty is basically the opposite of isset, it checks to see that the variable is empty.

Below are some examples:

[php]if ( isset ($HTTP_POST_VARS[‘username’]) ) {
// execute code if POST var is set

if ( empty ($HTTP_POST_VARS[‘username’]) ) {
// execute code if POST var is not set

The next PHP code of the week we’ll cover mysql_connect, mysql_select_db, mysql_query and mysql_close.

PHP COTW: htmlspecialchars, intval and str_replace

Saturday, June 2nd, 2007

The second PHP code of the week are htmlspecialchars, intval and str_replace which can all be used to process user form input before you use that input in your code.

htmlspecialchars basically converts the HTML characters like single and double quotes, less than, more than and ampersand signs to entities; which means that using this function we can prevent the users text from containing HTML characters.

echo htmlspecialchars(“<a href=’test’>Test</a>”);

This example will output in the browsers source code:
[php]<a href=’test’>Test</a>[/php]

intval is a way we can convert anything to an integer since we are expecting an integer. This means we can covert a string containing a number to a integer. We can be sure that we will only receive a number and nothing else.

[php]echo intval(‘035’);[/php]

The example will output 35. If the string contains any other characters other than digits it will return 0 (unless the digits are at the start of the string).

A full example of htmlspecialchars and intval would be:

[php]$sort_order = htmlspecialchars($HTTP_POST_VARS[‘order’]);
$form_status = intval($HTTP_POST_VARS[‘status’]);[/php]

str_replace is used to protect us from SQL injections into our database. If you aren’t protected from SQL injections, this means a user could perform any SQL query that you have access to.

For example, you could be updating a users email address in your database and the user types into the email address field.

[php]’; DROP some_table; some_fake_query_here(‘[/php]

The original query is below.

[php]UPDATE userdata SET email_address = ‘$form_email’ WHERE user_id = ‘$user_id’;[/php]

So what is going on you say? Below is what the resulting SQL statement looks like after the form has been processed.

[php]UPDATE userdata SET email_address = ”; DROP some_table; some_fake_query_here(” WHERE user_id = ‘5234’;[/php]

So what happens is the first query is processed we try not to break this query or all other queries would then fail. The second query to drop the table is successful and the table is therefore dropped and the last query fails.

So if we want to protect ourselfs from an SQL injection we use this code below.

[php]str_replace(“\'”, “””, $variable_name);[/php]

If form fields that a user submits contain a quote they are automatically re-written as \’. What our code will do is make it database friendly. It converts \’ to ” which for the database means it will be represented as a single quote. We have therefore solved the SQL injection issue.

On the next PHP code of the week we will cover isset and empty which are other functions which should be considered when processing forms.


Sunday, May 27th, 2007

Over the following weeks I will be covering PHP code which stands out to myself and some code which I use regularly. These PHP codes will be mentioned every week with an explanation on their uses. The section is called “PHP code of the week“.

We begin with our first PHP code of the week: HTTP_POST_VARS and HTTP_GET_VARS. Without these two functions we wouldn’t be able to get data from forms or simplify the way we specify user input in our code.

HTTP_POST_VARS is the function we call when we want to retrieve variable input from a form that the user has submitted. Say we have a field in the form called username. To retrieve the value of username we would write it as:

[php]$username = $HTTP_POST_VARS[‘username’];[/php]

So we have the username fields value being assigned to a local variable $username.

is commonly used when searching forums, looking up user names, etc so you have most likely seen it been used. It is a simple way to input values into your code and is done by placing a question mark (?) and variable name and the value after the file we are requesting.


In the above case, we can see that we are requesting the view_user.php file and are wanting to find more information on the userid number 5.

The inside code would look like:

[php]$user_id = $HTTP_GET_VARS[‘userid’];[/php]

That’s pretty simple, we have the userid variable being assigned to the local variable $user_id.

Using HTTP_GET_VARS you are also able to retrieve more than one variable by placing a ampersand sign after each value. Such as:


So there you go, you now know how to retrieve user data.

If you are requesting the values and say the user didn’t input anything in the POST/GET request, 0 (false) is assigned to the local variables.

Note: These examples aren’t recommended to be placed directly into code as there are security issues. You should use functions such as htmlspecialchars, intval and str_replace before touching the variables. These functions will be covered in the next PHP code of the week.