When I Upload a Html File to My Website the Hrefs Dont Work

php-file-upload

Uploading files, images, and videos using PHP is as easy every bit adding a couple of scripts. This guide volition show you lot ii unlike ways on how to add together php file upload functionality to your site:

  • The Simple PHP Way – This is the simplest fashion of adding a PHP uploader to your service. The upside is that yous have consummate control of the files beingness uploaded.
  • Filestack'south PHP File Upload Service – This is an easier manner of adding PHP upload functionality. The upside is that you lot do not have to manage the circuitous file upload infrastructure behind-the-scenes.

Let's become started with some easy examples:

PHP File Upload – The Simple Way

To first, we'll create the following:

1. The HTML Form

Starting time, we'll create an HTML form that the user will meet when they desire to upload the file. Create a new folder for this case project, and within it, create an alphabetize.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-data">         Upload a File:         <input type="file" name="the_file" id="fileToUpload">         <input blazon="submit" name="submit" value="Outset Upload">     </form> </torso> </html>                  

A couple important things to detect in the example higher up:

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

Adjacent, open up your terminal and from the directory where you created the file, commencement the PHP server:

php-file-upload

And then, open your spider web browser and go to localhost:1234. Yous should see something like this:

php-file-upload

two. The PHP File Upload Script

Side by side, we'll handle the backend of the file upload. First, in the same directory, create a new directory called uploads. This will be where our script volition save the files.

Then, in the same directory as 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 code:

          <?php     $currentDirectory = getcwd();     $uploadDirectory = "/uploads/";      $errors = []; // Store errors here      $fileExtensionsAllowed = ['jpeg','jpg','png']; // These will be the only 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(stop(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) {           repeat "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 annotation:

  • The central used to admission 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 the tmp directory of the server
  • $fileExtension = strtolower(stop(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, it is set to the current working directory

Likewise note that in the code above, nosotros validate the file upload past checking both the file type and size. (Simply png and jpeg files that are less than 4MB)

Now there are a couple final steps before we tin start uploading files:

  • Go to your uploads/ directory and make it writable past running: chmod 0755 uploads/
  • Brand sure your php.ini file is correctly configured to handle file uploads (Tip: to detect your php.ini file, run php --ini):
          max_file_uploads = 20 upload_max_filesize = 2M post_max_size = 8M                  

Finally, if you now commencement the PHP server and become to localhost:1234, then upload a file, you should see it salvage in the uploads folder!

Go on in mind that the all of the code above requires additional security precautions earlier being released in product. For example, there are currently no checks to meet if the user has uploaded a virus disguised as an image. To learn more, cheque out this commodity which describes diverse ways to handle secure file uploads.

File Upload with Filestack

In this second example, nosotros'll utilize Filestack to upload a file. Filestack is an avant-garde file upload API and service that securely stores files in the cloud.

Why utilise a third party like Filestack over building information technology yourself? By using a third party you no longer need to bargain with the scaling, security, and maintenance that comes with building your own file upload system. This tin can free you upward to focus on building other important parts of your application.

And y'all 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 go beyond that corporeality, they offer pricing that scales with use.

So let'southward get started:

i. Sign upwardly for a Filestack Account

php-file-upload

Commencement, we'll sign upward for a Filestack account. Go to their registration page and later on you log in, go the API Key, which you lot will use in the later steps.

2. Commencement Uploading

Now that nosotros accept 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 instance, if they wanted to upload from a URL or from social media. Simply replace the contents of index.html with the following:

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

So, open your page and then upload a file using the upload widget. After uploading, you should exist able to log into your Filestack dashboard and run across your newly uploaded file:

filestack-dashboard

And that's it! You don't fifty-fifty demand the server to handle the file, which is better for scalability, security, and maintenance.

Filestack PHP Library (optional)

The above example covers the simplest case of uploading a file with Filestack. Just, what if y'all wanted to access the file on your server to run some kind of post-processing, like checking if an epitome is prophylactic for work? To practice that, yous tin apply the Filestack PHP library. We'll utilize Composer to install the Filestack PHP library. If yous don't take Composer already, you can install information technology by going to the folder you lot 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 decadent'; unlink('composer-setup.php'); } repeat PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"        

Later on you lot practise the to a higher place, yous should be able to see Composer'due south output by running php composer.phar.

And then run require --prefer-dist filestack/filestack-php to install the Filestack SDK.

At present that we have the Filestack library, let's make a new PHP script to check if a specific uploaded file is rubber for work. Create a new file called fileUploadFilestack.php and add the following (making sure to alter the YOUR_API_KEY, YOUR_SECURITY_SECRET, and YOUR_FILE_HANDLE variables):

          <?php   crave __DIR__ . '/vendor/autoload.php';   use Filestack\FilestackClient;   $client = new FilestackClient(YOUR_API_KEY);   $security = new FilestackSecurity(YOUR_SECURITY_SECRET);    $file_handle = YOUR_FILE_HANDLE;    # go 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 prophylactic 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'southward merely one case. Using the Filestack PHP SDK allows you lot to perform a variety of tasks on your uploaded files. Check out these other examples:

  • Transform a file earlier upload
  • Test if a file upload is "safe 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 be integrated into a form bank check out these links:

  • Upload epitome
  • Open picker
  • Open picker in inline fashion
  • Crop images
  • File preview
  • And more…

Summary

At present that you lot know how implement PHP file uploads ii ways, you can hands add together this characteristic to your website or awarding. If dealing with the scalability, security, and maintenance challenges of hosting your own file upload infrastructure seems too daunting, let Filestack handle it. Also be certain to check out our article on AJAX File Uploads every bit well!

Read More →

loftinotem1941.blogspot.com

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

0 Response to "When I Upload a Html File to My Website the Hrefs Dont Work"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel