05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Files are stored in the server’s default temporary files directory, which is specified in<br />

php.ini with the upload_tmp_dir option. To move a file, use the move_uploaded_file()<br />

function:<br />

move_uploaded_file($_FILES['toProcess']['tmp_name'], "path/to/put/file/$file);<br />

The call to move_uploaded_file() automatically checks whether it was an uploaded<br />

file. When a script finishes, any files uploaded to that script are deleted from the<br />

temporary directory.<br />

Form Validation<br />

When you allow users to input data, you typically need to validate that data before<br />

using it or storing it for later use. There are several strategies available for validating<br />

data. The first is JavaScript on the client side. However, since the user can choose to<br />

turn JavaScript off, or may even be using a browser that doesn’t support it, this cannot<br />

be the only validation you do.<br />

A more secure choice is to use <strong>PHP</strong> itself to do the validation. Example 7-9 shows a<br />

self-processing page with a form. The page allows the user to input a media item;<br />

three of the form elements—the name, media type, and filename—are required. If the<br />

user neglects to give a value to any of them, the page is presented anew with a message<br />

detailing what’s wrong. Any form fields the user already filled out are set to the<br />

values she entered. Finally, as an additional clue to the user, the text of the submit<br />

button changes from “Create” to “Continue” when the user is correcting the form.<br />

Example 7-9. Form validation<br />

<br />

<br />

The name, media type, and filename are required fields. Please fill<br />

them out to continue.<br />

<br />

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

Saved successfully!

Ooh no, something went wrong!