The move_uploaded_file() function is used to upload file in PHP.
bool move_uploaded_file ( string $filename , string $destination )
To upload a file in PHP, you can follow these steps:
- Create an HTML form with an input field of type “file” to allow users to select the file they want to upload.
- Use the
$_FILES
superglobal array to access information about the uploaded file. - Use the
move_uploaded_file()
function to move the uploaded file to the desired location on the server.
Here’s an example:
HTML form (upload_form.html):
<!DOCTYPE html>
<html>
<head>
<title>File Upload Form</title>
</head>
<body>
<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>
</body>
</html>
PHP script (upload.php):
<?php
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size (you can adjust the size limit as needed)
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats (you can adjust the allowed file types as needed)
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Make sure to create a directory named “uploads” in the same directory where your PHP scripts reside to store the uploaded files. Also, ensure that the directory has appropriate permissions for the web server to write files.