Php Upload Text and Multiple Images at Once
Uploading files, images, and videos using PHP is as easy as adding a couple of scripts. This guide volition show you lot two unlike ways on how to add php file upload functionality to your site:
- The Simple PHP Mode – This is the simplest way of adding a PHP uploader to your service. The upside is that you have complete control of the files being uploaded.
- Filestack's PHP File Upload Service – This is an easier mode of adding PHP upload functionality. The upside is that y'all exercise 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 start, we'll create the following:
1. The HTML Form
First, we'll create an HTML form that the user will meet when they want to upload the file. Create a new binder for this example projection, and within it, create an index.html file with the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP File Upload</title> </head> <body> <form action="fileUploadScript.php" method="post" enctype="multipart/form-information"> Upload a File: <input blazon="file" name="the_file" id="fileToUpload"> <input blazon="submit" name="submit" value="Start Upload"> </form> </torso> </html> A couple important things to discover in the example above:
-
action="fileUploadScript.php"– This references the PHP script that will handle the file upload on the backend -
method="post"– This tells the browser action the class volition apply when sending the file to the server (for uploads, this is almost e'er a POST activeness, sometimes a PUT) -
enctype="multipart/form-information"– This determines the content-blazon that the course submits
Adjacent, open your terminal and from the directory where you created the file, start the PHP server:
So, open your web browser and go to localhost:1234. You should see something like this:
2. The PHP File Upload Script
Next, we'll handle the backend of the file upload. Start, in the same directory, create a new directory called uploads. This will be where our script will salve the files.
Then, in the same directory as alphabetize.html, create a file called fileUploadScript.php. Notice that this is the aforementioned name every bit the action aspect in the form. Then add together this code:
<?php $currentDirectory = getcwd(); $uploadDirectory = "/uploads/"; $errors = []; // Store errors here $fileExtensionsAllowed = ['jpeg','jpg','png']; // These volition exist the merely 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 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 $error) { echo $error . "These are the errors" . "\n"; } } } ?> A couple things to note:
- The key used to access the file from the
$_FILESobject matches the proper noun attribute used in the form -
$fileName = $<em>FILES['the</em>file']['name'];– This is the proper name 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 thetmpdirectory of the server -
$fileExtension = strtolower(cease(explode('.',$fileName)));– This gets the file extension from the file name -
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);– This is where the files will exist stored on the server. In the script higher up, information technology is set to the current working directory
Also note that in the lawmaking in a higher place, we validate the file upload by checking both the file type and size. (Simply png and jpeg files that are less than 4MB)
Now there are a couple final steps earlier nosotros can start uploading files:
- Go to your
uploads/directory and make it writable by running:chmod 0755 uploads/ - Make sure your
php.inifile is correctly configured to handle file uploads (Tip: to discover your php.ini file, runphp --ini):
max_file_uploads = 20 upload_max_filesize = 2M post_max_size = 8M Finally, if y'all now start the PHP server and get to localhost:1234, then upload a file, you should run into it save in the uploads binder!
Continue in mind that the all of the lawmaking above requires additional security precautions before being released in production. For example, at that place are currently no checks to see if the user has uploaded a virus disguised as an prototype. To learn more, check out this article which describes various ways to handle secure file uploads.
File Upload with Filestack
In this second example, we'll use Filestack to upload a file. Filestack is an advanced file upload API and service that deeply stores files in the cloud.
Why utilise a third political party like Filestack over edifice it yourself? By using a third political party you no longer need to deal with the scaling, security, and maintenance that comes with edifice your own file upload arrangement. This can free yous upwards to focus on building other important parts of your awarding.
And y'all can get started for free. Filestack has a free plan that handles up to 100 monthly uploads with 1GB storage and 1GB bandwidth. If yous need to go beyond that amount, they offer pricing that scales with employ.
So allow's get started:
1. Sign upwards for a Filestack Business relationship
First, we'll sign up for a Filestack account. Go to their registration page and after you log in, go the API Cardinal, which you volition employ in the afterward steps.
ii. Commencement Uploading
Now that we have the Filestack library, permit'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. Only replace the contents of index.html with the following:
<!DOCTYPE html> <html lang="en"> <caput> <meta charset="UTF-8"> <title>PHP File Upload</title> </caput> <body> <style> .picker-content{ height:300px; width:200px; } </mode> <script src="//static.filestackapi.com/filestack-js/ii.x.10/filestack.min.js"></script> <script type="text/javascript"> certificate.addEventListener("DOMContentLoaded", function(consequence) { const client = filestack.init(YOUR_API_KEY); permit options = { "displayMode": "inline", "container": ".picker-content", "take": [ "image/jpeg", "image/jpg", "image/png" ], "fromSources": [ "local_file_system" ], "uploadInBackground": imitation, "onUploadDone": (res) => console.log(res), }; picker = client.picker(options); picker.open(); }); </script> <div class="picker-content"></div> </trunk> </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 meet your newly uploaded file:
And that'south it! Y'all don't fifty-fifty need the server to handle the file, which is better for scalability, security, and maintenance.
Filestack PHP Library (optional)
The in a higher place example covers the simplest case of uploading a file with Filestack. But, what if you wanted to access the file on your server to run some kind of mail-processing, like checking if an image is safe for work? To practice that, y'all tin can use the Filestack PHP library. We'll use Composer to install the Filestack PHP library. If y'all don't have Composer already, yous can install information technology by going to the folder you created originally and running (see 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 { echo 'Installer corrupt'; unlink('composer-setup.php'); } repeat PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');" Afterward you practice the above, you should exist able to see 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, 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 together the following (making certain to modify the YOUR_API_KEY, YOUR_SECURITY_SECRET, and YOUR_FILE_HANDLE variables):
<?php crave __DIR__ . '/vendor/autoload.php'; utilize Filestack\FilestackClient; $client = new FilestackClient(YOUR_API_KEY); $security = new FilestackSecurity(YOUR_SECURITY_SECRET); $file_handle = YOUR_FILE_HANDLE; # get tags with customer $result_json = $customer->getTags($file_handle); # get tags with filelink $filelink = new Filelink($file_handle, YOUR_API_KEY, $security); $json_result = $filelink->getTags(); # get safety for work flag with filelink $json_result = $filelink->getSafeForWork(); ?> When this script is run, the consequence of the safe-for-work bank check will be saved in the $json_result variable. And that'due south just i example. Using the Filestack PHP SDK allows you to perform a multifariousness of tasks on your uploaded files. Check out these other examples:
- Transform a file earlier upload
- Test if a file upload is "rubber for work"
- Transcode uploaded video or audio
- Convert a file upload to pdf
- And more…
In addition, if you want to see more examples of how the file upload picker can exist integrated into a form check out these links:
- Upload image
- Open picker
- Open picker in inline mode
- Crop images
- File preview
- And more than…
Summary
At present that you know how implement PHP file uploads two ways, you can hands add this characteristic 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. Too be sure to check out our article on AJAX File Uploads likewise!
Read More →
pickeringhavoccon.blogspot.com
Source: https://blog.filestack.com/thoughts-and-knowledge/php-file-upload/
Post a Comment for "Php Upload Text and Multiple Images at Once"