Write a code to upload a file in PHP ?
To upload a file in PHP, you can use the following code:
<?php
if(isset($_POST['submit'])){
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$file_ext = strtolower(end(explode('.',$_FILES['file']['name'])));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
echo "Extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152) {
echo 'File size must be less than 2 MB';
}
$upload_path = "uploads/".$file_name;
if(move_uploaded_file($file_tmp,$upload_path)){
echo "Success";
}else{
echo "Error";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="submit" value="Upload" />
</form>
In this code, we first check if the form has been submitted using the isset()
function. Then, we retrieve the file name, size, temporary name, type, and extension using the $_FILES
superglobal array. We also define an array of allowed extensions and check if the uploaded file's extension is in that array. We also check if the file size is less than 2 MB.
Then, we define the upload path and use the move_uploaded_file()
function to move the file from its temporary location to the specified upload path. If the file is successfully uploaded, we display a success message, otherwise, we display an error message.
Finally, we create a form with an input field of type file and a submit button. The form's enctype
attribute is set to multipart/form-data
to allow file uploads.