How to upload photos/file to server using php?

Member

by dedrick , in category: PHP General , a year ago

How to upload photos/file to server using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 5 months ago

@dedrick 

To upload photos or files to a server using PHP, you can use the following steps:

  1. Create a HTML form that allows users to select and upload files. The form should include an input field with type "file" and an enctype attribute set to "multipart/form-data" to allow file uploads.
1
2
3
4
5
<form action="upload.php" method="post" enctype="multipart/form-data">
   Select file to upload:
   <input type="file" name="fileToUpload" id="fileToUpload">
   <input type="submit" value="Upload File" name="submit">
</form>


  1. Create a PHP script (upload.php) that handles the file upload process. This script will check if a file has been uploaded, move the file to a specified directory on the server, and provide feedback to the user on the success or failure of the upload. Here is an example of how the upload.php script might look:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file is an actual file or fake file
if(isset($_POST["submit"])) {
   $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
   if($check !== false) {
      echo "File is an image - " . $check["mime"] . ".";
      $uploadOk = 1;
   } else {
      echo "File is not an image.";
      $uploadOk = 0;
   }
}

// Check if file already exists
if (file_exists($target_file)) {
   echo "Sorry, file already exists.";
   $uploadOk = 0;
}

// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
   echo "Sorry, your file is too large.";
   $uploadOk = 0;
}

if ($uploadOk == 0) {
   echo "Sorry, your file was not uploaded.";

} else {
   if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
      echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
   } else {
      echo "Sorry, there was an error uploading your file.";
   }
}
?>


  1. Make sure to create a directory named "uploads" in the same directory as the upload.php script to store the uploaded files.
  2. Test the file upload by selecting a file to upload in the HTML form and submitting the form. The file should be uploaded to the specified directory on the server.


Please note that you should always validate and sanitize user input to prevent security vulnerabilities, such as file injection attacks. It is also important to set appropriate file size limits and file type restrictions to ensure the security and stability of your application.