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.

Opening a File<br />

61<br />

The form field for the shipping address is called address.This gives you a variable you<br />

can access as $_REQUEST[‘address’] or $_POST[‘address’] or $_GET[‘address’],<br />

depending on the form submission METHOD. (See Chapter 1,“<strong>PHP</strong> Crash Course,” for<br />

details.)<br />

In this chapter, you write each order that comes in to the same file.Then you construct<br />

a web interface for Bob’s staff to view the orders that have been received.<br />

Processing Files<br />

Writing data to a file requires three steps:<br />

1. Open the file. If the file doesn’t already exist, you need to create it.<br />

2. Write the data to the file.<br />

3. Close the file.<br />

Similarly, reading data from a file takes three steps:<br />

1. Open the file. If you cannot open the file (for example, if it doesn’t exist), you<br />

need to recognize this <strong>and</strong> exit gracefully.<br />

2. Read data from the file.<br />

3. Close the file.<br />

When you want to read data from a file, you have many choices about how much of the<br />

file to read at a time.We describe some common choices in detail. For now, we start at<br />

the beginning by opening a file.<br />

Opening a File<br />

To open a file in <strong>PHP</strong>, you use the fopen() function.When you open the file, you need<br />

to specify how you intend to use it.This is known as the file mode.<br />

Choosing File Modes<br />

The operating system on the server needs to know what you want to do with a file that<br />

you are opening. It needs to know whether the file can be opened by another script<br />

while you have it open <strong>and</strong> whether you (or the script owner) have permission to use it<br />

in that way. Essentially, file modes give the operating system a mechanism to determine<br />

how to h<strong>and</strong>le access requests from other people or scripts <strong>and</strong> a method to check that<br />

you have access <strong>and</strong> permission to a particular file.<br />

You need to make three choices when opening a file:<br />

1. You might want to open a file for reading only, for writing only, or for both reading<br />

<strong>and</strong> writing.<br />

2. If writing to a file, you might want to overwrite any existing contents of a file or<br />

append new data to the end of the file.You also might like to terminate your program<br />

gracefully instead of overwriting a file if the file already exists.

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

Saved successfully!

Ooh no, something went wrong!