How to upload a file to a server using PHP?

To upload a file to a server using PHP, you can follow these steps:

  1. Create a HTML form with an input element of type file for users to select the file they want to upload. Set the enctype attribute of the form to multipart/form-data to allow file uploads.
<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileToUpload"> <input type="submit" value="Upload"> </form>
  1. In a PHP file (e.g. "upload.php"), access the uploaded file using the $_FILES superglobal. Check for any errors during the upload using the $_FILES['fileToUpload']['error'] value.
if ($_FILES['fileToUpload']['error'] === UPLOAD_ERR_OK) { // File was successfully uploaded $tempFilePath = $_FILES['fileToUpload']['tmp_name']; $fileName = $_FILES['fileToUpload']['name']; $destinationPath = 'uploads/' . $fileName; // Move the file from temp location to desired destination move_uploaded_file($tempFilePath, $destinationPath); } else { // Handle file upload errors here echo "Error uploading file: " . $_FILES['fileToUpload']['error']; }
  1. Create a directory on the server to store the uploaded files. In the example above, the directory "uploads" (relative to the PHP file) is used as the destination directory. You may need to set proper file permissions for the directory to have write access.
// Make sure 'uploads' directory exists if (!is_dir('uploads')) { mkdir('uploads'); }
  1. After moving the file to the destination directory, you can perform any desired operations such as saving the file details to a database or displaying a success message to the user.

Note: Ensure that your PHP configuration (php.ini) allows file uploads by checking the values of upload_max_filesize and post_max_size. You may need to modify these values if your files exceed the default limits.

Remember to implement appropriate security measures to ensure that only valid file uploads are allowed and to prevent any form of abuse.