How to Upload File Using PHP

How to Upload File Using PHP - PHP, as server-side-scripting, is very possible to handle uploading files to the server. There are several things to note in uploading this file, namely:
1. In the HTML Form should be added attributes:
ENCTYPE="multipart/form-data"
2. Input form upload file can use tag <input> with value attribute TYPE = "FILE".
3. To handle inputan, PHP provides a global array variable that is $_FILES. Index of these variables include:
  • $_FILES['file']['name']: The original name of the uploaded file.
  • $_FILES['file']['tmp_name']: The temporary name of the uploaded file.
  • $_FILES['file']['size']: The size of the original file (in bytes).
  • $_FILES['file']['type']: MIME file type uploaded.
4. Destination file upload folder should be writable (accessible), usually with permissions 777 or 775.
For more details, here I give an example of its application to a php application program.
Program 1
File Name: form_upload.php
Description: The program displays file upload form.
Type the following html code into notepad.
<html>
<head><title>Upload File</title></head>
<body>
  <FORM ACTION="upload.php" METHOD="POST" ENCTYPE="multipart/form-data">
   Upload File : <input type="file" name="file"><br>
   <input type="submit" name="Upload" value="Upload">
</FORM>
</body>
</html>

How to Upload File Using PHP
Html code

Save the html code with the name form_upload.php in the htdocs folder.
Program 2
File Name: upload.php
Description: Program file upload process.
Type the following php code into notepad.
<?php
if (isset($_POST['Upload'])) {
$dir_upload = "images/";
 $nama_file = $_FILES['file']['name'];
//
 if (is_uploaded_file($_FILES['file']['tmp_name'])) {
  $cek = move_uploaded_file ($_FILES['file']['tmp_name'],
$dir_upload.$nama_file);
if ($cek) {     die ("The file was uploaded successfully"); 
  } else {
   die ("File failed to upload"); 
   }
 }
}
?>

How to Upload File Using PHP
php code

Save it with the name upload.php in the htdocs folder.
Program Explanation 2
Program 2 above is a simple file handling program. The is_uploaded_file() function on line 6 will upload the selected file via the form in program 1 to the temporary folder. Next on line 7, files that have been uploaded to the temporary folder will be moved (move) to the desired directory using the move_uploaded_file() function, see line 7!
To run the program open a browser, type http://localhost/form_upload.php in the address bar then enter. Then the results will look like below.
How to Upload File Using PHP
Program view

How to Upload File Using PHP
Upload files

How to Upload File Using PHP
File uploaded successfully

How to Upload File Using PHP
Result of file upload

So tutorial How to Upload File Using PHP from me. Hopefully can help you and improve our ability in studying php programming language. Also read the tutorial How to Copy and Rename a File in PHP.

Comments