Script for file upload in PHP and CHMOD to 755

Last updated December 6th, 2023 06:12

Sometimes, it is necessary to use a simple form to upload files to the FTP of your website. Here is a complete script for file upload in PHP using the chmod function to change permissions to 755 and with a form for selecting the file (you can adjust the permissions using chmod in the script to your own desired ones). Keep in mind that the maximum file size is governed by the limit set in the php.ini file of the website. Therefore, you will likely be limited by the file size, especially if you are using shared web hosting. Here’s how to write a simple script for file upload in PHP using the chmod function to change permissions to 755.

Script for file upload in PHP and CHMOD to 755

The script uses the ‘upload’ folder for file uploads. Once again, if you need to modify the target folder, adjust it in the script to your desired one.

This script is designed for uploading .jpg, .jpeg, and .png files. Once again, it can be adjusted as needed.

				
					<!DOCTYPE html>
<html>
<head>
   <title>File Upload</title>
</head>
<body>
   
   <form action="" method="POST" enctype="multipart/form-data">
      <input type="file" name="file"/>
      <input type="submit" value="Upload"/>
   </form>
   
   <?php
   
   if(isset($_FILES['file'])) {
      $errors = array();
      $file_name = $_FILES['file']['name'];
      $file_size = $_FILES['file']['size'];
      $file_tmp = $_FILES['file']['tmp_name'];
      $file_type = $_FILES['file']['type'];
      $file_ext = strtolower(end(explode('.',$_FILES['file']['name'])));
      
      $extensions = array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions) === false){
         $errors[] = "Extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 2097152) {
         $errors[] = 'File size must be less than 2 MB';
      }
      
      if(empty($errors) == true) {
         move_uploaded_file($file_tmp,"upload/".$file_name);
         chmod("upload/".$file_name, 0755);
         echo "Success";
      } else {
         print_r($errors);
      }
   }
   
   ?>
   
<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode-wpr",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script></body>
</html>

				
			
PHP skript pro připojení k MySQL databázi

Explanation

  • <form>: This part of the code defines a form where a file is selected for upload. The action attribute specifies the target page to submit the form (in this case it’s empty, meaning the data will be submitted to the same page). The method attribute specifies how the data will be sent to the target page (in this case, the POST method is used). The enctype attribute specifies the encoding type of the data to be sent (in this case, multipart/form-data is used for file uploads).
  • <input type=”file” name=”file”> defines a field for file selection on the user’s computer in an HTML form. This type of field is used for uploading files to a server. The type attribute specifies the field type as “file”, which means the user can select a file from their computer. The name attribute defines the name of the field, in this case, “file”. This name is used in the PHP script as the key to access information about the uploaded file.
  • <input type=”submit” value=”Upload”>: This is the form button that allows the user to submit the file to the server. The value attribute specifies the text that will be displayed on the button.
  • if (isset($_FILES[‘file’])): This block of code is executed only when a file has been selected and submitted using the form. The isset() function returns true if the variable has been set and is not null. In this case, it checks whether the file was selected using the form.
  • $errors: This variable is used to store errors that occur during file validation.
  • $file_name = $_FILES[‘file’][‘name’]: This variable is used to store the name of the file that was submitted. The $_FILES variable contains information about the submitted file, and the ‘name’ index contains the file name.
  • $file_size = $_FILES[‘file’][‘size’]: This variable is used to store the size of the file that was submitted. The $_FILES variable contains information about the submitted file, and the ‘size’ index contains the file size in bytes.
  • $file_tmp = $_FILES[‘file’][‘tmp_name’]: This variable is used to store the temporary name of the file that was submitted to the server. The $_FILES variable contains information about the submitted file, and the ‘tmp_name’ index contains the temporary file name on the server.
  • $file_type = $_FILES[‘file’][‘type’]: This variable is used to store the file type that was submitted. The $_FILES variable contains information about the submitted file, and the ‘type’ index contains the MIME type of the file.
  • $file_ext = strtolower(end(explode(‘.’,$_FILES[‘file’][‘name’]))): This variable gets the file extension and converts it to lowercase using the strtolower() function. The explode(‘.’,$_FILES[‘file’][‘name’]) function splits the file name into individual parts based on the period and returns an array. The end() function gets the last element of the array.
  • $extensions = array(“jpeg”,”jpg”,”png”): This variable contains a list of allowed file extensions.
  • in_array($file_ext,$extensions) === false: This function checks whether the file extension is not in the array of allowed extensions. If it is not, an error message is added to the $errors variable.
  • if($file_size > 2097152): This function checks whether the file size is not larger than 2 MB. If it is, an error message is added to the $errors variable.
  • empty($errors) == true: This function checks whether the $errors variable is empty, meaning there were no errors during file validation. If it is empty, the file can be processed and uploaded to the server.
  • move_uploaded_file($file_tmp,”upload/”.$file_name): This function moves the uploaded file from the temporary directory on the server to the upload/ directory with the name $file_name.
  • chmod(“upload/”.$file_name, 0755): This function sets file permissions to 755, which allows the owner to read, write, and execute the file, but only allows other users to read the file.
  • print_r: This function is used to print the contents of an array, in this case, the $errors array. The print_r function displays information about the array, such as keys and their values. If the $errors array is empty, nothing will be displayed. However, if the array contains a value, the value will be printed on the page. These values should be error messages that will appear if a file has an invalid extension or is too large.

This script will upload files without any restrictions on the file extension and will have a maximum file size of 128 MB.

Please note the capital “U” in the “Upload” folder. It may be necessary to adjust the size, as Linux servers distinguish between uppercase and lowercase letters.

				
					<!DOCTYPE html>
<html>
<head>
   <title>File Upload</title>
</head>
<body>
   
   <form action="" method="POST" enctype="multipart/form-data">
      <input type="file" name="file"/>
      <input type="submit" value="Upload"/>
   </form>
   
   <?php
   
   if(isset($_FILES['file'])) {
      $errors = array();
      $file_name = $_FILES['file']['name'];
      $file_size = $_FILES['file']['size'];
      $file_tmp = $_FILES['file']['tmp_name'];
      $file_type = $_FILES['file']['type'];
      
      if($file_size > 128000000) {
         $errors[] = 'File size must be less than 128 MB';
      }
      
      if(empty($errors) == true) {
         move_uploaded_file($file_tmp,"upload/".$file_name);
         chmod("upload/".$file_name, 0755);
         echo "Success";
      } else {
         print_r($errors);
      }
   }
   
   ?>
   
</body>
</html>

				
			

The website is created with care for the included information. I strive to provide high-quality and useful content that helps or inspires others. If you are satisfied with my work and would like to support me, you can do so through simple options.

Byl pro Vás tento článek užitečný?

Klikni na počet hvězd pro hlasování.

Průměrné hodnocení. 0 / 5. Počet hlasování: 0

Zatím nehodnoceno! Buďte první

Jak užitečný vidíte tento článek.

Sledujte mě na sociálních médiích.

Je mi líto, že pro Vás nebyl článek užitečný.

Jak mohu vylepšit článek?

Řekněte mi, jak jej mohu zlepšit.

newsletter

Subscribe to the Newsletter

Stay informed! Join our newsletter subscription and be the first to receive the latest information directly to your email inbox. Follow updates, exclusive events, and inspiring content, all delivered straight to your email.

Odebírat
Upozornit na
guest
0 Komentáře/ů
Nejstarší
Nejnovější Nejvíce hlasováno
Vložené zpětné vazby.
Zobrazit všechny komentáře.

Pokud mi chcete napsat rychlou zprávu, využije, prosím, níže uvedený
kontaktní formulář. Děkuji.

Další Kontaktní údaje