How to Upload Files Using Php Code
Uploading files, images, and videos using PHP is every bit like shooting fish in a barrel equally calculation a couple of scripts. This guide will bear witness yous two different ways on how to add php file upload functionality to your site:
- The Elementary PHP Mode – This is the simplest way of adding a PHP uploader to your service. The upside is that yous have complete command of the files being uploaded.
- Filestack's PHP File Upload Service – This is an easier way of adding PHP upload functionality. The upside is that you lot practise non accept to manage the complex file upload infrastructure behind-the-scenes.
Let's get started with some easy examples:
PHP File Upload – The Elementary Manner
To outset, we'll create the following:
1. The HTML Form
Get-go, nosotros'll create an HTML course that the user will come across when they want to upload the file. Create a new folder for this case projection, and within it, create an index.html
file with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-eight"> <championship>PHP File Upload</title> </head> <body> <class action="fileUploadScript.php" method="post" enctype="multipart/form-data"> Upload a File: <input type="file" name="the_file" id="fileToUpload"> <input blazon="submit" name="submit" value="Start Upload"> </course> </torso> </html>
A couple important things to notice in the case higher up:
-
activity="fileUploadScript.php"
– This references the PHP script that will handle the file upload on the backend -
method="post"
– This tells the browser action the form will utilise when sending the file to the server (for uploads, this is about always a POST action, sometimes a PUT) -
enctype="multipart/form-data"
– This determines the content-type that the form submits
Next, open your concluding and from the directory where yous created the file, start the PHP server:
Then, open your web browser and become to localhost:1234
. You should run into something similar this:
2. The PHP File Upload Script
Next, nosotros'll handle the backend of the file upload. First, in the same directory, create a new directory called uploads. This will exist where our script will relieve the files.
Then, in the aforementioned directory equally index.html, create a file called fileUploadScript.php. Notice that this is the same name as the action attribute in the class. Then add this lawmaking:
<?php $currentDirectory = getcwd(); $uploadDirectory = "/uploads/"; $errors = []; // Shop errors here $fileExtensionsAllowed = ['jpeg','jpg','png']; // These will exist the but file extensions allowed $fileName = $_FILES['the_file']['name']; $fileSize = $_FILES['the_file']['size']; $fileTmpName = $_FILES['the_file']['tmp_name']; $fileType = $_FILES['the_file']['blazon']; $fileExtension = strtolower(end(explode('.',$fileName))); $uploadPath = $currentDirectory . $uploadDirectory . basename($fileName); if (isset($_POST['submit'])) { if (! in_array($fileExtension,$fileExtensionsAllowed)) { $errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file"; } if ($fileSize > 4000000) { $errors[] = "File exceeds maximum size (4MB)"; } if (empty($errors)) { $didUpload = move_uploaded_file($fileTmpName, $uploadPath); if ($didUpload) { echo "The file " . basename($fileName) . " has been uploaded"; } else { echo "An error occurred. Please contact the administrator."; } } else { foreach ($errors as $fault) { echo $error . "These are the errors" . "\n"; } } } ?>
A couple things to note:
- The cardinal used to admission the file from the
$_FILES
object matches the name attribute used in the grade -
$fileName = $<em>FILES['the</em>file']['name'];
– This is the proper name of the bodily file -
$fileSize = $<em>FILES['the</em>file']['size'];
– This is the size of the file in bytes -
$fileTmpName = $<em>FILES['the</em>file']['tmp_name'];
– This is the a temporary file that resides in thetmp
directory of the server -
$fileExtension = strtolower(end(explode('.',$fileName)));
– This gets the file extension from the file proper noun -
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
– This is where the files will be stored on the server. In the script in a higher place, it is gear up to the current working directory
Also notation that in the code above, nosotros validate the file upload by checking both the file blazon and size. (Just png and jpeg files that are less than 4MB)
Now there are a couple concluding steps before nosotros can start uploading files:
- Go to your
uploads/
directory and make it writable by running:chmod 0755 uploads/
- Make sure your
php.ini
file is correctly configured to handle file uploads (Tip: to find your php.ini file, runphp --ini
):
max_file_uploads = 20 upload_max_filesize = 2M post_max_size = 8M
Finally, if you lot at present start the PHP server and become to localhost:1234, then upload a file, y'all should encounter it save in the uploads binder!
Go along in listen that the all of the code in a higher place requires boosted security precautions before existence released in production. For instance, there are currently no checks to come across if the user has uploaded a virus disguised every bit an image. To learn more than, check out this article which describes various ways to handle secure file uploads.
File Upload with Filestack
In this 2nd example, nosotros'll apply Filestack to upload a file. Filestack is an advanced file upload API and service that securely stores files in the cloud.
Why use a third party like Filestack over building it yourself? By using a tertiary party you no longer demand to bargain with the scaling, security, and maintenance that comes with building your own file upload system. This can free you up to focus on building other important parts of your application.
And you lot can become started for free. Filestack has a free plan that handles upwards to 100 monthly uploads with 1GB storage and 1GB bandwidth. If you demand to go beyond that corporeality, they offer pricing that scales with utilise.
So permit's get started:
1. Sign up for a Filestack Business relationship
First, we'll sign upwardly for a Filestack business relationship. Get to their registration page and after you log in, go the API Key, which you lot will utilize in the later steps.
two. Start Uploading
Now that we take the Filestack library, permit'south integrate their JavaScript file uploader widget, which allows your users to connect to a diverseness of other sources from which to upload from. For example, if they wanted to upload from a URL or from social media. Merely replace the contents of index.html with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-eight"> <championship>PHP File Upload</championship> </head> <body> <style> .picker-content{ height:300px; width:200px; } </style> <script src="//static.filestackapi.com/filestack-js/2.x.10/filestack.min.js"></script> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function(event) { const client = filestack.init(YOUR_API_KEY); allow options = { "displayMode": "inline", "container": ".picker-content", "accept": [ "image/jpeg", "image/jpg", "image/png" ], "fromSources": [ "local_file_system" ], "uploadInBackground": false, "onUploadDone": (res) => console.log(res), }; picker = client.picker(options); picker.open up(); }); </script> <div class="picker-content"></div> </body> </html>
Then, open your page and and so upload a file using the upload widget. Afterwards uploading, yous should be able to log into your Filestack dashboard and see your newly uploaded file:
And that's it! You don't fifty-fifty demand the server to handle the file, which is ameliorate for scalability, security, and maintenance.
Filestack PHP Library (optional)
The above example covers the simplest example of uploading a file with Filestack. But, what if y'all wanted to access the file on your server to run some kind of post-processing, like checking if an prototype is condom for piece of work? To practise that, you can use the Filestack PHP library. Nosotros'll use Composer to install the Filestack PHP library. If you don't have Composer already, you can install it past going to the folder you lot created originally and running (see this for official documentation):
php -r "re-create('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"
Afterwards you do the above, y'all should be able to run into Composer's output by running php composer.phar
.
Then run require --prefer-dist filestack/filestack-php
to install the Filestack SDK.
Now that we have the Filestack library, allow'due south make a new PHP script to check if a specific uploaded file is safe for work. Create a new file chosen fileUploadFilestack.php and add the following (making sure to change the YOUR_API_KEY, YOUR_SECURITY_SECRET, and YOUR_FILE_HANDLE variables):
<?php require __DIR__ . '/vendor/autoload.php'; use Filestack\FilestackClient; $client = new FilestackClient(YOUR_API_KEY); $security = new FilestackSecurity(YOUR_SECURITY_SECRET); $file_handle = YOUR_FILE_HANDLE; # become tags with client $result_json = $customer->getTags($file_handle); # become tags with filelink $filelink = new Filelink($file_handle, YOUR_API_KEY, $security); $json_result = $filelink->getTags(); # get safe for work flag with filelink $json_result = $filelink->getSafeForWork(); ?>
When this script is run, the upshot of the safe-for-work cheque will be saved in the $json_result
variable. And that's but i example. Using the Filestack PHP SDK allows y'all to perform a diverseness of tasks on your uploaded files. Check out these other examples:
- Transform a file earlier upload
- Exam if a file upload is "prophylactic for work"
- Transcode uploaded video or audio
- Convert a file upload to pdf
- And more…
In add-on, if yous want to come across more examples of how the file upload picker can exist integrated into a form cheque out these links:
- Upload image
- Open picker
- Open picker in inline manner
- Crop images
- File preview
- And more…
Summary
Now that you lot know how implement PHP file uploads two ways, you tin can easily add this feature to your website or application. If dealing with the scalability, security, and maintenance challenges of hosting your own file upload infrastructure seems also daunting, let Filestack handle information technology. Also be sure to cheque out our commodity on AJAX File Uploads besides!
Read More →
Source: https://blog.filestack.com/thoughts-and-knowledge/php-file-upload/