Monthly Archive for April, 2011

How To: Read a file's contents with PHP

PHP provides three built-in functions which allow you to easily read the contents of a file on your webserver. This is useful when, for example, another program may write information to the file and you could access that information through your script.

In this example, we're going to use the following example 5 line file, saved as file.txt:

line 1
line 2
line 3
line 4
line 5

In the same directory as file.txt, we're going to work with the PHP file test.php. We'll outline the file reading functions below.

readfile()

readfile() is the least useful of the file functions. As a parameter, it takes a string which specifies the location of the file to read - this can be relative or absolute; since our file is the same directory as the script, we just need to pass the string 'file.txt' as this paramter. We call the function using the code readfile('file.txt') and it prints out the contents of the file straight to the browser:

// readfile() writes the contents of the file straight to the browser
echo 'Contents of file.txt using readfile():<br>';
readfile('file.txt');

The disadvantage of readfile() is that it doesn't allow you to manipulate the file contents before displaying it - the next two functions we're going to look at will allow you to do that.

file()

The code file('file.txt') will read the contents of file.txt into an array, which you can then manipulate in your scripts and display yourself. Each line of the file is stored in a seperate element of the array, this means that we can access and manipulate each line of the file seperately using normal array notation.

// file() loads the contents of file.txt into an array, $lines
// each line in the file becomes a seperate element of the array.
$lines = file('file.txt');

// now loop through the array to print the contents of the file
echo 'Contents of file.txt using file():<br>';
foreach ($lines as $line)
{
echo htmlspecialchars($line) . '<br>';
}

// we can also access each line of the file seperately
echo '3rd line of the file: "' . htmlspecialchars($lines[2]) . '"<br>';

In this example, we've loaded the contents of file.txt into an array called $lines then used foreach to loop through the array and display each line on the user's browser. We then use $lines[2] to access the third line of the file (the element at array index 2, since line 1 is $lines[0]).

You may notice that we've used a function called htmlspecialchars() when displaying the file's contents - this enables that special characters used in HTML, such as > and " are displayed correctly. This illustrates the power of file() over readfile() since readfile() was unable to perform this kind of processing.

get_file_contents()

The last method we will look at is get_file_contents('file.txt') which is similar to file() however rather than returning an array, it returns a string with all the lines of the file. We can manipulate and display this in a similar way as with file():

// file_get_contents() reads the file and places the contents in a string
$fileString = file_get_contents('file.txt');
echo 'Contents of file.txt using file_get_contents():<br>';
echo nl2br( htmlspecialchars($fileString) );

Since we have no way of seperating the lines with this method, we've used the nl2br() function which converts line breaks in the string (represented by the special character n) into the HTML line break <br /> so that the file will display correctly on the visitor's browser.

The full contents of test.php is below:

<?php 
// file() loads the contents of file.txt into an array, $lines
// each line in the file becomes a seperate element of the array.
$lines = file('file.txt');

// now loop through the array to print the contents of the file
echo 'Contents of file.txt using file():
';
foreach ($lines as $line)
{
echo htmlspecialchars($line) . '<br>';
}

// we can also access each line of the file seperately
echo '3rd line of the file: "' . htmlspecialchars($lines[2]) . '"<br>';
echo '<br>';

// file_get_contents() reads the file and places the contents in a string
$fileString = file_get_contents('file.txt');
echo 'Contents of file.txt using file_get_contents():
';
echo nl2br( htmlspecialchars($fileString) );
echo '<br>';

// readfile() writes the contents of the file straight to the browser
echo 'Contents of file.txt using readfile():<br>';
readfile('file.txt');
?>

The output from test.php is:

Contents of file.txt using file():
line 1
line 2
line 3
line 4
line 5
3rd line of the file: "line 3 "

Contents of file.txt using file_get_contents():
line 1
line 2
line 3
line 4
line 5

Contents of file.txt using readfile():
line 1 line 2 line 3 line 4 line 5

How To: Find Items in PHP Arrays

The problem: we have an array of items in PHP and we want to find out if a specific item is in the array. In code we can define the array as:

IE we have an array called $fruitBasket which contains 5 strings, each of which is the name of a fruit. We want to find out if there is an Apple in the $fruitBasket - is there an element "Apple" in the array?

We do this with the following code:

<?
// create an array of strings called $fruitBasket:
$fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
// use the in_array() function to check if "Apple" is in the array:
if( in_array("Apple", $fruitBasket) )
{
  echo "Apple is in the array";
}
else
{
  echo "Apple is not in the array";
}
?>

This code uses the in_array() method to check if the element "Apple" exists in the array $fruitBasket:
in_array("Apple", $fruitBasket)

in_array() takes two parameters here: firstly the object we're looking for, in this case "Apple", and secondly the array which we're looking in, $fruitBasket. It then returns a boolean value: true if "Apple" is in the array, or false if it isn't.

References: php.net manual: in_array() function

What is the difference between require() and include() in PHP?

The key difference between require() and include() is that if you require() a file that can't be loaded (eg if it isn't there) then it generates a fatal error which will halt the execution of the page completely, and no more output will be generated. On the other hand, if you include() a file that can't be loaded, then this will merely generate a warning and continue building the page.

What one you should use depends on the situation; require() is best suited for loading files that are essential to the rest of the page - for example if you have a database driven website then using require() to include a file containing the database login and password is clearly preferred over using include(). If you used include() in this situation, then you may end up generating more warnings and errors than you had intended.

include() should be used when it isn't essential for that file to be loaded to execute the page. This is best used in situations where the file isn't essential to the processing of the page (for example a footer file), so if the file isn't present then the user can still view the site. You should, of course, make sure that all files you include() and require() are going to be available.

In PHP versions prior to 4.0.2. there was slightly different behaviour of require(). If you used a require() statement in an if block then the require() statement will always make sure that the file you're require()ing is readable, regardless of whether the condition was true for that if block to be processed. This is best illustrated with the following code example:

<?
$a = 1;
  if($a == 2) {
    require("header.php");
  }
?>

In this example, PHP versions before 4.0.2. will always make sure that header.php is available, but it will only actually execute the contents of it if $a is equal to 2.

From php.net:

Note: Prior to PHP 4.0.2, the following applies: require() will always attempt to read the target file, even if the line it's on never executes. The conditional statement won't affect require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed. Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

How to use PHP in pages with a .html extension (or any other)

To be able to use php code on a page with an extension other than .php, you need a server which supports .htaccess files.

To add an extension to be parsed for php, create or edit a file called .htaccess (with the dot first) containing the following line:
AddType application/x-httpd-php .html .moo .htm
This tells the server to check for php code and execute it in files with extensions .html, .moo or .htm. So upload that .htaccess file in the same folder as your .html files with PHP code inside them (using PHP tags: <?php ... ?>) then when you view them in the browser, the PHP should be dealt with as you'd expect from a PHP page.

Google Currency Conversion

Google has a currency conversion feature built in to its search, all you have to do is search for 100 GBP in USD, for example, to convert £100 (UK Pounds Sterling) to US Dollars. If you don't know the acronym for the currency you're converting to then don't worry as you can also do conversions with a search like 100 USD in Czech money, if you were planning a trip to the Czech Republic.

Google: Filter By Usage Rights

I'm not sure how long this has been there (a while now; I'm imporing this from an old blog of mine), but Google has added a filter on its Advanced Search page which allows you to filter search results by the license that content on a website is released under, which would be useful, for example, if you are looking for content which you can republish on your page.

Add Notepad To Your "Send To" Menu

What I've always found useful since I started using Windows is to add notepad to the "Send To" menu, which is available when you right click on any file in Windows. This means that if you come across a text file with an extension which is not associated with Notepad then you can open it in Notepad quickly and easily.

To do this on your computer:

  1. Browse to your "SendTo" folder - this is a folder which contains shortcuts which appear in the Send To Menu.
    Your user folder is located at:
    C:\Documents and Settings\<username>\SendTo
    eg, mine is: C:\Documents and Settings\Tiposaurus\SendTo
  2. Right click somewhere in this folder, then from the right click menu, select New -> Shortcut.
  3. As the location of the item, enter "Notepad" (without the quotes) then Windows will figure out the correct path to it. Alternatively you can enter the full path to it; if your Windows directory is C:\Windows then the full path to notepad will be c:\windows\system32\notepad.exe
  4. As the name of the shortcut type whatever you want to see appearing in the "Send To" menu - I chose NotePad above.
  5. When you click 'Finish' then you should see the shortcut you've just created appearing in the" Send To" menu 

How To: Redirect Output on the Windows Command Line

This tip will show you how to write the output of a command at the Windows command line to a file. It's not hard (infact it's one of the very basics of command line programming).

Start Command Line within Windows by choosing Start->Run then entering 'cmd' and pressing enter.

Suppose you want to capture the output from a directory listing, say c:blah. To get the directory listing to display on the screen you would type the command dir c:blah which may generate the output:

C:\>dir c:\blah

Volume in drive C is Windows
Volume Serial Number is XXXX-YYYY

Directory of c:\blah

07/01/2006 21:08 <DIR> .
07/01/2006 21:08 <DIR> ..
07/01/2006 21:07 <DIR> folder1
07/01/2006 21:07 <DIR> folder2
06/03/2005 11:58 5,442,634 music.mp3
07/01/2006 21:07 17 text1.txt
2 File(s) 5,442,651 bytes
4 Dir(s) 12,453,460,480 bytes free

If you want to capture this listing to the file c:folder.txt then you would append > c:\folder.txt to the original command, ie:
C:\>dir c:\blah > c:\folder.txt

Notice now that nothing appears on the command line window after this and it simply moves on to the next prompt. If we now check the file c:\folder.txt then we see that it has the contents of the directory.

A slight variant of this is to use the greater than symbol, >, twice, ie:

C:\>dir c:\blah >> c:\folder.txt

This will append the output of the dir command to what is already contained in the file c:\folder.txt.

List all processes with the Windows Command Line

To view all the currently running processes in windows from the command line (choose Run then type "cmd"), you can use the command 'tasklist'. The output will look something like this:
C:>tasklist

Image Name               PID Session Name     Session#    Mem Usage
===================== ====== ================ ======== ============
System Idle Process        0 Console                 0         16 K
System                     4 Console                 0         52 K
smss.exe                 592 Console                 0        108 K
csrss.exe                648 Console                 0      5,868 K
winlogon.exe             680 Console                 0      2,632 K
services.exe             724 Console                 0      2,376 K
(...)

Kill a Process from the Windows Command Line

To terminate a process from the command line of windows, use the taskkill command:
When you know the name of the program to stop:
taskkill /IM notepad.exe
Or when you know the process ID, eg 784:
taskkill /PID 784
For more usage variants, type taskkill /?

Some of this information about what processes are running can be obtained by the tasklist command, e.g. this tells you the Process ID (PID).