Can I Run Php on a Server Once a File Gets Uploaded?
Uploading files, images, and videos using PHP is as easy as calculation a couple of scripts. This guide volition evidence you 2 dissimilar ways on how to add php file upload functionality to your site:
- The Simple PHP Way – This is the simplest way of calculation a PHP uploader to your service. The upside is that you have complete control of the files existence uploaded.
- Filestack's PHP File Upload Service – This is an easier way of adding PHP upload functionality. The upside is that you lot do not have to manage the circuitous file upload infrastructure behind-the-scenes.
Permit's go started with some easy examples:
PHP File Upload – The Simple Manner
To start, we'll create the post-obit:
1. The HTML Form
Start, we'll create an HTML course that the user volition encounter when they want to upload the file. Create a new binder for this instance project, and inside it, create an index.html
file with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-viii"> <title>PHP File Upload</championship> </head> <torso> <grade activeness="fileUploadScript.php" method="post" enctype="multipart/grade-data"> Upload a File: <input type="file" name="the_file" id="fileToUpload"> <input type="submit" name="submit" value="Get-go Upload"> </form> </torso> </html>
A couple important things to notice in the example to a higher place:
-
action="fileUploadScript.php"
– This references the PHP script that volition handle the file upload on the backend -
method="post"
– This tells the browser action the grade will use when sending the file to the server (for uploads, this is almost always a POST activity, sometimes a PUT) -
enctype="multipart/form-data"
– This determines the content-type that the form submits
Next, open your terminal and from the directory where you created the file, start the PHP server:
So, open your web browser and get to localhost:1234
. You should encounter something like this:
2. The PHP File Upload Script
Side by side, nosotros'll handle the backend of the file upload. Offset, in the same directory, create a new directory called uploads. This will be where our script will save the files.
And so, in the aforementioned directory as index.html, create a file called fileUploadScript.php. Notice that this is the aforementioned name as the action attribute in the form. Then add this code:
<?php $currentDirectory = getcwd(); $uploadDirectory = "/uploads/"; $errors = []; // Shop errors here $fileExtensionsAllowed = ['jpeg','jpg','png']; // These volition be the just file extensions allowed $fileName = $_FILES['the_file']['proper name']; $fileSize = $_FILES['the_file']['size']; $fileTmpName = $_FILES['the_file']['tmp_name']; $fileType = $_FILES['the_file']['type']; $fileExtension = strtolower(end(explode('.',$fileName))); $uploadPath = $currentDirectory . $uploadDirectory . basename($fileName); if (isset($_POST['submit'])) { if (! in_array($fileExtension,$fileExtensionsAllowed)) { $errors[] = "This file extension is non immune. 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 fault occurred. Please contact the ambassador."; } } else { foreach ($errors as $error) { echo $mistake . "These are the errors" . "\northward"; } } } ?>
A couple things to annotation:
- The cardinal used to access the file from the
$_FILES
object matches the name attribute used in the form -
$fileName = $<em>FILES['the</em>file']['name'];
– This is the proper noun of the actual 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 exist stored on the server. In the script in a higher place, information technology is set to the electric current working directory
Also notation that in the code above, we validate the file upload by checking both the file type and size. (Just png and jpeg files that are less than 4MB)
Now there are a couple last steps earlier we tin can start uploading files:
- Go to your
uploads/
directory and make information technology writable past 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 get-go the PHP server and get to localhost:1234, then upload a file, you should see it save in the uploads folder!
Proceed in mind that the all of the code to a higher place requires additional security precautions earlier existence released in product. For example, there are currently no checks to see if the user has uploaded a virus disguised as an epitome. To learn more, check out this commodity which describes various ways to handle secure file uploads.
File Upload with Filestack
In this second instance, we'll use Filestack to upload a file. Filestack is an advanced file upload API and service that securely stores files in the cloud.
Why employ a third party similar Filestack over building information technology yourself? By using a third party you no longer demand to deal with the scaling, security, and maintenance that comes with building your ain file upload arrangement. This tin can free yous upwardly to focus on building other of import parts of your application.
And you can get started for free. Filestack has a free programme that handles up to 100 monthly uploads with 1GB storage and 1GB bandwidth. If you need to get beyond that amount, they offer pricing that scales with use.
And then allow's get started:
1. Sign up for a Filestack Business relationship
Start, we'll sign up for a Filestack account. Go to their registration folio and after y'all log in, get the API Fundamental, which y'all volition use in the after steps.
2. Beginning Uploading
Now that we have the Filestack library, let's integrate their JavaScript file uploader widget, which allows your users to connect to a variety of other sources from which to upload from. For example, if they wanted to upload from a URL or from social media. Simply supplant the contents of index.html with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <championship>PHP File Upload</title> </head> <body> <way> .picker-content{ height:300px; width:200px; } </style> <script src="//static.filestackapi.com/filestack-js/two.x.10/filestack.min.js"></script> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function(event) { const customer = filestack.init(YOUR_API_KEY); let options = { "displayMode": "inline", "container": ".picker-content", "take": [ "image/jpeg", "epitome/jpg", "paradigm/png" ], "fromSources": [ "local_file_system" ], "uploadInBackground": fake, "onUploadDone": (res) => console.log(res), }; picker = client.picker(options); picker.open(); }); </script> <div class="picker-content"></div> </body> </html>
Then, open up your page and then upload a file using the upload widget. After uploading, you should be able to log into your Filestack dashboard and come across your newly uploaded file:
And that's information technology! You don't even need the server to handle the file, which is meliorate 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 you lot wanted to admission the file on your server to run some kind of mail service-processing, like checking if an image is safe for work? To exercise that, you tin can use the Filestack PHP library. We'll apply Composer to install the Filestack PHP library. If you lot don't have Composer already, you lot can install information technology by going to the folder you created originally and running (come across this for official documentation):
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { repeat 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"
Afterward you do the to a higher place, you lot should be able to run into Composer'due south output by running php composer.phar
.
Then run crave --prefer-dist filestack/filestack-php
to install the Filestack SDK.
Now that nosotros have the Filestack library, let's make a new PHP script to check if a specific uploaded file is safety for work. Create a new file called fileUploadFilestack.php and add the post-obit (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; # get tags with client $result_json = $client->getTags($file_handle); # get 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 result of the safe-for-work check will be saved in the $json_result
variable. And that's just one example. Using the Filestack PHP SDK allows yous to perform a diverseness of tasks on your uploaded files. Check out these other examples:
- Transform a file before upload
- Examination if a file upload is "prophylactic for work"
- Transcode uploaded video or audio
- Convert a file upload to pdf
- And more…
In addition, if y'all want to see more examples of how the file upload picker can be integrated into a form check out these links:
- Upload epitome
- Open picker
- Open picker in inline style
- Crop images
- File preview
- And more…
Summary
Now that you know how implement PHP file uploads two ways, you tin 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 as well daunting, permit Filestack handle it. Also exist certain to check out our commodity on AJAX File Uploads as well!
Read More →
spellmanhatinarthady.blogspot.com
Source: https://blog.filestack.com/thoughts-and-knowledge/php-file-upload/
Post a Comment for "Can I Run Php on a Server Once a File Gets Uploaded?"