To upload a file to a server using PHP, you can follow these steps:
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>
$_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'];
}
// Make sure 'uploads' directory exists
if (!is_dir('uploads')) {
mkdir('uploads');
}
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.