Tutorials PHP Uploading Files

Uploading Files

Today you will learn how to upload files to your website.

What types of files can you upload?

You can upload anything. Although it is highly recommended you filter your results with size and type to prevent unauthorized files. You should be careful with executable files as those could contain viruses and other malware.

What do you use to upload files?

You use a form to upload files. Pay attention to the form enctype which is required if you want to send binary data like files.

<form enctype="multipart/form-data" method="post" action="upload.php">
<p>Choose file to upload:</p>
<input name="image" type="file"/>
<input type="submit" name="submit" value="Upload" />

The PHP functionality:

$allowed_types = array(

// upload directory
$dir = 'images/';

$name   = $_FILES['image']['name'];
$type   = $_FILES['image']['type'];
$size   = $_FILES['image']['size'];
$tmp_nm = $_FILES['image']['tmp_name'];
$error  = $_FILES['image']['error'];

if (!empty($error)) {
  echo 'Error: ' . $error;
} else if (!in_array($type, $allowed_types)) {
  die ('Only jpeg, png, gif, jpg allowed.');
} else if ($size > 10486000) {
  die ('Max file size is 10 MB.');
} else if (move_uploaded_file($tmp_nm, $dir . $name)) {
  echo 'Stored in: ' . $dir . $name;
} else {
  'Error uploading. Please try again later.';

Posted by on . Category: PHP


No comments posted yet

You need to register or login to post new comments.