Examples

In the following examples it is assumed that you are using an HTML form field <input type="file" name="f" /> in order to upload files. For example:

HTML form for simple file upload

The following form can be used in order to test the single file upload example.

<?php
// sample code from below goes here
?>
<html>
 <head>
 </head>
 <body>
  <form name="fileuploadexample" method="post" enctype="multipart/form-data"
   action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
   <input type="file" name="f" />
   <input type="submit" name="submit" value="Submit" />
  </form>
 </body>
</html>

Simple file upload

The following code looks at the request and checks if a valid file was uploaded through the form. If that is the case, the file is moved to the subdirectory uploads.

<?php
require_once "HTTP/Upload.php";

$upload = new HTTP_Upload("en");
$file $upload->getFiles("f");

if (
$file->isValid()) {
    
$moved $file->moveTo('uploads/');
    if (!
PEAR::isError($moved)) {
        echo 
'File was moved to uploads/' $file->getProp('name');
    } else {
        echo 
$moved->getMessage();
    }
} elseif (
$file->isMissing()) {
    echo 
"No file was provided.";
} elseif (
$file->isError()) {
    echo 
$file->errorMsg();
}
?>

Internally, HTTP_Upload_File::moveTo() calls $file->setName('safe'); which replaces special characters in the name with an underscore. You should always use $file->getProp('name') after moving to retrieve the new filename.

HTML form for multiple file upload

The following form can be used in order to test the multiple file upload example.

<?php
// sample code from below goes here
?>
<html>
 <head>
 </head>
 <body>
  <form name="fileuploadexample2" method="post" enctype="multipart/form-data"
   action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
   <input type="file" name="f1" />
   <input type="file" name="f2" />
   <input type="submit" name="submit" value="Submit" />
  </form>
 </body>
</html>

Multiple files, more extensive checks

Multiple files can uploaded by replacing the name of the form field (f) with f[] and creating multiple <input /> fields with this name.

<?php
$upload 
= new HTTP_Upload("en");
$files $upload->getFiles();

foreach(
$files as $file){
    if (
PEAR::isError($file)) {
        echo 
$file->getMessage();
    }

    if (
$file->isValid()) {
        
$file->setName("uniq");
        
$dest_name $file->moveTo("uploads/");

        if (
PEAR::isError($dest_name)) {
            echo 
$dest_name->getMessage();
        }

        
$real $file->getProp("real");

    } elseif (
$file->isMissing()) {
        echo 
"No file was provided.";
    } elseif (
$file->isError()) {
        echo 
$file->errorMsg();
    }

    
print_r($file->getProp());
}
?>