One of the most frequently asked questions in the PHP Forums is “How can I upload images using PHP?” In this tutorial we are going to look at the basics, and show you how you can use such a script on your website.
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
- Lastly a page to advise the client the upload was a success
Let’s start with the HTML form.
<?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
?
<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 accidentally omitted making file uploads impossible. This item is contained in the