Upload File to Directory on Server Php

php-file-upload

Uploading files, images, and videos using PHP is equally easy as adding a couple of scripts. This guide will show you two dissimilar means on how to add together php file upload functionality to your site:

  • The Simple PHP Way – This is the simplest way of adding a PHP uploader to your service. The upside is that yous take complete command of the files being uploaded.
  • Filestack'due south PHP File Upload Service – This is an easier mode of adding PHP upload functionality. The upside is that you do not have to manage the complex file upload infrastructure behind-the-scenes.

Let's get started with some piece of cake examples:

PHP File Upload – The Simple Mode

To get-go, we'll create the following:

1. The HTML Grade

Offset, we'll create an HTML form that the user will run into when they want to upload the file. Create a new folder for this example project, and inside it, create an index.html file with the post-obit code:

          <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-viii">     <title>PHP File Upload</title> </caput> <torso>     <form action="fileUploadScript.php" method="mail service" enctype="multipart/form-information">         Upload a File:         <input type="file" name="the_file" id="fileToUpload">         <input type="submit" name="submit" value="Start Upload">     </form> </body> </html>                  

A couple important things to notice in the example above:

  • activity="fileUploadScript.php" – This references the PHP script that will handle the file upload on the backend
  • method="mail service" – This tells the browser action the form will utilise when sending the file to the server (for uploads, this is almost always a POST activity, sometimes a PUT)
  • enctype="multipart/grade-information" – This determines the content-type that the class submits

Adjacent, open your terminal and from the directory where y'all created the file, start the PHP server:

php-file-upload

Then, open your web browser and go to localhost:1234. You should see something like this:

php-file-upload

2. The PHP File Upload Script

Next, we'll handle the backend of the file upload. First, in the same directory, create a new directory chosen uploads. This will be where our script will save the files.

And so, in the same directory as alphabetize.html, create a file called fileUploadScript.php. Notice that this is the same proper noun as the activeness attribute in the form. Then add this code:

          <?php     $currentDirectory = getcwd();     $uploadDirectory = "/uploads/";      $errors = []; // Store errors hither      $fileExtensionsAllowed = ['jpeg','jpg','png']; // These will exist the only file extensions immune       $fileName = $_FILES['the_file']['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 not 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 mistake occurred. Please contact the ambassador.";         }       } else {         foreach ($errors as $error) {           echo $error . "These are the errors" . "\n";         }       }      } ?>                  

A couple things to note:

  • The key used to admission the file from the $_FILES object matches the proper noun attribute used in the form
  • $fileName = $<em>FILES['the</em>file']['name']; – This is the proper noun 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 the tmp directory 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 be stored on the server. In the script above, information technology is set to the electric current working directory

Also notation that in the code to a higher place, we validate the file upload by checking both the file type and size. (Only png and jpeg files that are less than 4MB)

At present there are a couple final steps before nosotros tin can commencement uploading files:

  • Go to your uploads/ directory and make information technology writable by running: chmod 0755 uploads/
  • Make sure your php.ini file is correctly configured to handle file uploads (Tip: to discover your php.ini file, run php --ini):
          max_file_uploads = xx upload_max_filesize = 2M post_max_size = 8M                  

Finally, if you at present start the PHP server and become to localhost:1234, then upload a file, you should see it relieve in the uploads folder!

Keep in mind that the all of the code in a higher place requires additional security precautions before being released in production. For example, there are currently no checks to run across if the user has uploaded a virus disguised every bit an image. To learn more, check out this article which describes various ways to handle secure file uploads.

File Upload with Filestack

In this 2nd example, nosotros'll utilise Filestack to upload a file. Filestack is an advanced file upload API and service that securely stores files in the deject.

Why use a third party like Filestack over building it yourself? Past using a third party you no longer need to deal with the scaling, security, and maintenance that comes with building your own file upload system. This can complimentary you up to focus on edifice other important parts of your application.

And you can get started for gratis. Filestack has a gratis plan that handles upwardly to 100 monthly uploads with 1GB storage and 1GB bandwidth. If you need to become across that amount, they offering pricing that scales with use.

So permit'southward get started:

1. Sign up for a Filestack Account

php-file-upload

Offset, we'll sign up for a Filestack business relationship. Go to their registration page and afterward you log in, go the API Key, which you will use in the later steps.

two. Start Uploading

Now that we have the Filestack library, let'southward integrate their JavaScript file uploader widget, which allows your users to connect to a variety of other sources from which to upload from. For case, if they wanted to upload from a URL or from social media. Simply supersede the contents of index.html with the following:

          <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-eight">     <championship>PHP File Upload</title> </head> <body>     <style>       .picker-content{         meridian:300px;         width:200px;       }     </way>     <script src="//static.filestackapi.com/filestack-js/ii.x.x/filestack.min.js"></script>     <script type="text/javascript">       certificate.addEventListener("DOMContentLoaded", role(consequence) {          const customer = filestack.init(YOUR_API_KEY);           let options = {           "displayMode": "inline",           "container": ".picker-content",           "take": [             "image/jpeg",             "paradigm/jpg",             "image/png"           ],           "fromSources": [             "local_file_system"           ],           "uploadInBackground": false,           "onUploadDone": (res) => panel.log(res),         };          picker = client.picker(options);         picker.open();       });     </script>     <div class="picker-content"></div> </body> </html>                  

Then, open up your folio and then upload a file using the upload widget. After uploading, you should exist able to log into your Filestack dashboard and encounter your newly uploaded file:

filestack-dashboard

And that'southward information technology! You don't fifty-fifty demand the server to handle the file, which is improve for scalability, security, and maintenance.

Filestack PHP Library (optional)

The in a higher place example covers the simplest example of uploading a file with Filestack. Simply, what if you wanted to access the file on your server to run some kind of mail service-processing, similar checking if an paradigm is safe for work? To practise that, you can utilise the Filestack PHP library. Nosotros'll use Composer to install the Filestack PHP library. If y'all don't have Composer already, you tin install information technology by going to the folder you created originally and running (run 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 { echo 'Installer corrupt'; unlink('composer-setup.php'); } repeat PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"        

Afterward you do the above, you should exist able to see Composer'due south output by running php composer.phar.

Then run crave --prefer-dist filestack/filestack-php to install the Filestack SDK.

Now that we take the Filestack library, allow's make a new PHP script to bank check if a specific uploaded file is safe for work. Create a new file chosen 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;   $customer = 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);    # 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 consequence of the prophylactic-for-work check volition exist saved in the $json_result variable. And that's just 1 example. Using the Filestack PHP SDK allows y'all to perform a variety of tasks on your uploaded files. Check out these other examples:

  • Transform a file before upload
  • Exam if a file upload is "safety for work"
  • Transcode uploaded video or audio
  • Catechumen a file upload to pdf
  • And more…

In improver, if you lot want to see more than examples of how the file upload picker can be integrated into a form bank check out these links:

  • Upload paradigm
  • Open picker
  • Open picker in inline mode
  • Crop images
  • File preview
  • And more…

Summary

At present that yous know how implement PHP file uploads 2 ways, you can easily add together this feature to your website or application. If dealing with the scalability, security, and maintenance challenges of hosting your own file upload infrastructure seems too daunting, permit Filestack handle it. As well be sure to check out our article on AJAX File Uploads as well!

Read More than →

conyersandeaphs1986.blogspot.com

Source: https://blog.filestack.com/thoughts-and-knowledge/php-file-upload/

0 Response to "Upload File to Directory on Server Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel