13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

76 Chapter 2 Storing <strong>and</strong> Retrieving Data<br />

Using Other Useful File Functions<br />

Numerous other file functions are useful from time to time. Some are described next.<br />

Checking Whether a File Is There: file_exists()<br />

If you want to check whether a file exists without actually opening it, you can use<br />

file_exists(), as follows:<br />

if (file_exists("$DOCUMENT_ROOT/../orders/orders.txt")) {<br />

echo 'There are orders waiting to be processed.';<br />

} else {<br />

echo 'There are currently no orders.';<br />

}<br />

Determining How Big a File Is: filesize()<br />

You can check the size of a file by using the filesize() function:<br />

echo filesize(“$DOCUMENT_ROOT/../orders/orders.txt”);<br />

It returns the size of a file in bytes <strong>and</strong> can be used in conjunction with fread() to read<br />

a whole file (or some fraction of the file) at a time.You can even replace the entire original<br />

script with the following:<br />

$fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, ‘rb’);<br />

echo nl2br(fread( $fp, filesize(“$DOCUMENT_ROOT/../orders/orders.txt” )));<br />

fclose( $fp );<br />

The nl2br() function converts the \n characters in the output to HTML line breaks<br />

().<br />

Deleting a File: unlink()<br />

If you want to delete the order file after the orders have been processed, you can do so<br />

by using unlink(). (There is no function called delete.) For example,<br />

unlink(“$DOCUMENT_ROOT/../orders/orders.txt”);<br />

This function returns false if the file could not be deleted.This situation typically<br />

occurs if the permissions on the file are insufficient or if the file does not exist.<br />

Navigating Inside a File: rewind(), fseek(), <strong>and</strong> ftell()<br />

You can manipulate <strong>and</strong> discover the position of the file pointer inside a file by using<br />

rewind(), fseek(), <strong>and</strong> ftell().<br />

The rewind() function resets the file pointer to the beginning of the file.The<br />

ftell() function reports how far into the file the pointer is in bytes. For example, you<br />

can add the following lines to the bottom of the original script (before the fclose()<br />

comm<strong>and</strong>):

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!