PHP Uploading A File



With PHP, uploading a file is really easy!

Lets start with the upload form (this is just a simple bit of HTML) in file upload01.php

upload1.php


<form enctype="multipart/form-data" action="upload02.php" method="POST">
Choose a file to upload: <input name="upload_file" type="file" />
<input type="submit" value="Upload" />
</form>



This form simply posts data to upload02.php, a PHP file in the same directory as upload01.php.

In reality upload01.php uploads the file to a temporary storage location on your server. It is the job of upload02.php to move it from its temporary location into the location you want it at (if the file is not moved from its temporary location, it will simply be deleted).

Now let's deal with the code for upload02.php:

upload02.php


<?php

$targetDirectory = "files/";
$targetFile = $targetDirectory . basename( $_FILES['upload_file']['name']);

if(move_uploaded_file($_FILES['upload_file']['tmp_name'], $target_path))
{
echo basename( $_FILES['upload_file']['name'])." has been uploaded";
}
else
{
echo "Error uploading the file, please try again!";
}
?>


It's as easy as that!

Trouble with larger files?
In case you do get errors when trying to upload larger files, it may be because PHP limits the maximum file size to 2MB by default. This can be increased by editing php.ini and and changing the 'upload_max_filesize' and 'post_max_size' directives to larger values.


No comments:

Post a Comment