THE ZEPINT NETWORK

programmer assist

PHP PHP XML Feeds

PHP Questions PHP Solutions PHP Articles

PHP is a popular open-source programming language used primarily for developing server-side applications and dynamic web content, and more recently, other software. The name is a recursive acronym for "PHP: Hypertext Preprocessor".

Handling File Uploads With PHP

DiggBlinkRedditDeliciousTechnorati

article by Srirangan

This is a minimalistic guide on how to handle file uploads using PHP and XHTML forms. Prerequisites are basic XHTML and PHP skills.

Step 1: Creating an XHTML form

A form needs to be created through which a user can select the file that needs to be uploaded and pass it on to the PHP script which uploads the file. It's a very simple form using the "input type=file" attribute.

<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>


Step 2: Processing the upload

Now comes the PHP part. The approach I use here is to make use of the move_uploaded_file() and the global $_FILES variable.

<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if ( is_uploaded_file($_FILES['userfile']['tmp_name']) && move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) ){
echo "File is valid, and was successfully uploaded.
";
} else {
echo "Possible file upload attack!
";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>


Notes

- Provide your file with sufficient permissions, ie. the requisite write permissions in your operating system

- Modify the $uploaddir variable suitably to point to the writable folder where you want to save the uploaded files

References

[1] PHP Documentation

Got a PHP Question?

Just Sign Up and ask the top PHP experts!

Search via Google

User Login

Email Address

Password

PHP Experts

Rank Expert Points
#1 Srirangan 2650
#2 Anurag 600
#3 mastercomputers 100
This a list of the Top PHP experts, how many points do you have?

Leading Experts

Rank Expert Points
#1 frankzzsword 4650
#2 Bejaan 2950
#3 csfreak 1100
#4 Anurag 700
#5 keyvez 700
#6 nnarasimha 600
#7 Nakata 600
#8 martinig 600
#9 mastercomputers 550
#10 Abhishek Chatterjee 250
#11 Abels 250
#12 Huntress 150
#13 Adkron 150
#14 Yogesh 100
#15 lexxwern 100
This is a list of overall best performing experts, how many points do you have?