PHPBuilder - How to Upload Images Using PHP



RSS Twitter
Articles Php Functions

How to Upload Images Using PHP

by: PHP Builder Staff
|
January 29, 2009

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:
  1. An HTML form with a browse button to allow the client to choose which file to upload.
  2. A script to process the upload, validate the file, name it and place it in the file system.
  3. 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">

1
|
2
Next Page »

Download: uploader.zip

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.