#native_company# #native_desc#

How to Upload Images Using PHP

By PHP Builder Staff
on 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:

// 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"> 
        <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> 
    <form id="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post"> 
            Upload form 
            <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>"> 
            <label for="file">File to upload:</label> 
            <input id="file" type="file" name="file"> 
            <label for="submit">Press to...</label> 
            <input id="submit" type="submit" name="submit" value="Upload me!"> 


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:

<form id="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post"> 

The other important thing of course is the file <input> tag.

<input id="file" type="file" name="file">

Download: uploader.zip