by WebDeveloper forum member bokeh
One of the most frequently asked questions about PHP is “how can I use PHP to upload an image”. In this article we’ll discuss the details of how you can do just that!
Uploading images can be broken down into the three following steps which will be looked at in turn:
- An HTML form with a browse button to allow the client to choose which file to upload.
- A script to process the upload, validate the file, name it and place it in the file system.
- A page to advise the client the upload was a success.
Let’s start with the HTML form.
PHP Code: <?php // filename: upload.form.php // first let's set some variables // make a note of the current working directory relative to root. $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']); // make a note of the location of the upload handler script $uploadHandler = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.processor.php'; // set a max file size for the html upload form $max_file_size = 30000; // size in bytes // now echo the html page ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <link rel="stylesheet" type="text/css" href="stylesheet.css"> <title>Upload form</title> </head> <body> <form id="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post"> <h1> Upload form </h1> <p> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>"> </p> <p> <label for="file">File to upload:</label> <input id="file" type="file" name="file"> </p> <p> <label for="submit">Press to...</label> <input id="submit" type="submit" name="submit" value="Upload me!"> </p> </form> </body> </html>
The form is just basic HTML but has one very important part which is often accidently omitted making file uploads impossible. This item is contained in the <form> tag, be sure to include it:
Code: <form id="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post">
The other important thing of course is the file <input> tag.
Code: <input id="file" type="file" name="file">