Upload files with Php

When it comes to upload files with php, it's not so difficult, In the beggining we just need to type some  html markup



<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="upload.php" 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>
view raw index.html hosted with ❤ by GitHub
we just creating a form with

enctype="multipart/form-data"

it important to add this attribute it shows that we can upload file with this form

<input type="hidden" name="MAX_FILE_SIZE" value="30000" />

this hidden field indicate max file size , we need also to make security check in php side

<input name="userfile" type="file" />

this is the file input to upload a file
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
view raw upload.php hosted with ❤ by GitHub
move_uploaded_file() : take 2 paramatres the filename and destination path/file
NB : this just uploading directly files ,but in the production mode wee need security checks such as allowed file extensions and allowed max file size
$_FILES it's multidimensional array variable hols all uploaded file info

Comments

Popular posts from this blog

Realtime Chat Application with CakePHP and Socket.IO #1

Let's build a mobile application with Ionic Framework #1

Let's build a mobile application with Ionic Framework #3