Sample upload file code

The following code is a sample to upload a file.

Create a folder name "upload".

Save the following codes into "upload.php".

  1. <?php
  2. //create 'upload' directory if not yet created
  3. if (!is_dir('upload')) {
  4. mkdir('upload', 0777, true);
  5. }
  6. $target_file = "upload/".$_FILES["fileToUpload"]["name"];
  7. //$target_file can be saved into database table to relate to specific user data
  8.  
  9. if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  10. echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  11. echo "<a href='$target_file'></a>";
  12. } else {
  13. echo "Sorry, there was an error uploading your file.";
  14. }
  15. ?>
  16.  
  17. <form action="upload.php" method="post" enctype="multipart/form-data">
  18. Select image to upload:
  19. <input type="file" name="fileToUpload" id="fileToUpload">
  20. <input type="submit" value="Upload Image" name="submit">
  21. </form>

Last modified: Saturday, 23 February 2019, 10:53 AM