In this lesson, you will learn about how to upload files and images to the web server. This action is relatively easy to perform in PHP. When we mention files and images, we are talking about all sort of data and images on your computer such as MS word files, pdf files, images, etc. It depends on what you want to allow the user to upload into the web server.

Upload file to the server using PHP

There are two ways to upload files to the web server. Either you can upload files or images in the database as a blob, or you can save the data or pictures directly to a folder on your web server.

In this lesson, we are going to demonstrate the second method to upload files.

Here is the simple HTML web form that has only one element which allows users to choose the file.

<form method="post" action="fileupload_ac.php" enctype="multipart/form-data">
<label for="filename">Choose file to upload</label>
<input type="file" name="filename" multiple><br>
<input type="submit" name="submit" value="Upload">
</form>

The form is using the post method to submit the data to the web server. The action attribute is set to the fileupload_ac.php file which has the script to process the upload. The last attribute is the enctype which determines the encryption method of the file while the form will be submitted.

File Upload Form

To enable multiple files to be uploaded, add the attribute “multiple” with file element and if you want to allow the user to upload only one file, omit this attribute.

Once this form is submitted, $_FILES is the array; you need to need to look for the information about the upload.

<?php 
echo "<pre>";
print_r($_FILES);
echo "</pre>";
?>

The output

Array
(
[filename] => Array
(
[name] => bitcoin.jpg
[type] => image/jpeg
[tmp_name] => C:\wamp64\tmp\php5F8F.tmp
[error] => 0
[size] => 90356
)

)

The filename here is the name of the input element which stores the file being uploaded.

  • $_FILES[‘filename’][‘name’] has the name of the file being uploaded.
  • $_FILES[‘filename’][‘type’] has the type of the file. In this case, it is image/jpeg as the file uploaded was a jpeg image.
  • $_FILES[‘filename’][‘tmp_name’] has the file’s temporary name.
  • $_FILES[‘filename’][‘error’] has the error code
  • $_FILES[‘flename’][‘size’] stores the size of the file/image.

File upload error codes

PHP gives you with some error code to know the status of the file being uploaded.

  • UPLOAD_ERR_OK or 0 means there is no error, the file uploaded successfully.
  • UPLOAD_ERR_INI_SIZE or 1 means the file has exceeds the upload_max_filesize. You can change this directive from php.ini if you have to upload more substantial file than the allowed limit. By default, the value is 2MB.
  • UPLOAD_ERR_FROM_SIZE or 2 means the file exceeds the max_file_size.
  • UPLOAD_ERR_PARIAL or 3 means file is uploaded but partially.
  • UPLOAD_ERR_NO_FILE or 4 means no file was uploaded.

So what is the use of these values or error codes?

Let’s say you want that user couldn’t upload any file heavier than 50KB.

<?php

if ($_FILES['filename']['size'] > 51200) {
$error = 'Please, Upload files less than 50KB';

?>

To let users only upload jpeg images use the following piece of code.

<?php
if ($_FILES['filename']['type'] != 'image/jpeg') {
$error = 'Only jpeg images are allowed';
?>

Enable file upload in PHP

To enable file upload in PHP, you need to set a few configuration options in the php.ini file.

Set file_uploads directive in php.ini to On. upload_max_filesize will allow you to set the maximum size for uploaded files. By default, the value is set to 2MB which may not be enough if you have to upload more than one pictures.

To increase the size of the file upload, you need to change the value as per your requirements. If the file being uploaded exceeds upload_max_filesize, PHP will throw a file exceeds error.

You can also make changes in php.ini default settings using the .htacess file. Just copy paste the following lines of code in your .htaccess file and upload it in the root directory.

php_value upload_max_filesize 10M
php_value post_max_size 50M
php_value memory_limit 128M

Example of file upload in PHP

In this example, we are going to upload an image to the server using a simple web form.
First, Let create two files:

  1. fileinput.php
  2. fileinput_ac.php

Now open fileinput.php and copy the following code, save and open in the browser.

<!DOCTYPE html>

<html>
<head>
<style>
body{font-family: 'Open Sans', sans-serif; color:#333; font-size:14px; padding:50px;}
#book_form{padding:50px;}
label{display:inline-block; width:140px; }
th, td{width:120px;}
table{width:50%; text-align:left;}

</style>

</head>
<body>

<form enctype="multipart/form-data" action="fileinput_ac.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000" />

Select file to upload:
<input type="file" name="data" />

<input type="submit" name="submit" value="Upload File" /></form>
</body>
</html>

Open fileinput_ac.php
Copy the following code, and save.

<?php
if (isset($_POST['submit'])) {

// check uploaded file size
if ($_FILES['data']['size'] == 0) {
die("Error: Empty file");
}

// check if file being uploaded is an image.
$allowedFileTypes = array("image/gif", "image/jpeg", "image/pjpeg");

if (!in_array($_FILES['data']['type'], $allowedFileTypes)) {
die("Error: Only images are allowed");
}
// check if this is a valid upload
if (!is_uploaded_file($_FILES['data']['tmp_name'])) {
die("Error: Invalid file type"); }

// set the name of the directory to save the file being uploaded
$uploadDir = "./uploads/";
move_uploaded_file($_FILES['data']['tmp_name'], $uploadDir . $_FILES['data']['name']) or die("Cannot copy uploaded file");

echo "Image successfully uploaded to " . $uploadDir .$_FILES['data']['name'];
}
?>

move_uploaded_file() function

move_uploaded_file() function is the key to upload files to the web server in PHP. It moves the uploaded file from the temporary location to the new location being specified.

Syntax of move_uploaded_file()

move_uploaded_file ( string $filename , string $destination ) : bool

This function will check first if the file mentioned by $filename is uploaded. If it is a valid file, PHP will move the file to the destination given by $destination. This It will return true on success, false on failure.

PHP Send Email Tutorial Home PHP Date and Time
Last modified: April 22, 2019