Archive for July, 2007

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.

$filename = 'test.txt';
fopen($filename, 'a');

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 php.net website).

Add Content

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

$filename = 'test.txt';
$content = “Some content here”;

$handle = fopen($filename, 'a');
fwrite($handle, $content);
fclose($handle);

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:

$filename = 'test.txt';
$content = “Some content here”;

if (is_writable($filename)) {

if ($handle = fopen($filename, 'a')) {

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

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.

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

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.

unlink(‘test.txt’);

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 www.php.net)

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.

session_start();
header("Cache-control: private"); //IE 6 Fix

$_SESSION['username'] = $form_username;
$_SESSION['password'] = $form_password;

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.

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.

$_SESSION = array();
session_destroy();

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.

$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’].

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.

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.

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

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

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

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.

$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

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