In this article, you will learn how to Upload File Using PHP Function. Initially, the file will be uploaded into a temp directory then resettled to a target destination by a PHP script.
In PHP move_uploaded_file() in built function is used to upload the file. There are two arguments in this function. First is the temporary location of the file and second is where to upload the file.
Here are the simple steps to upload the file
Step 1:
Create one form:<html> <head> <title>Demo: File Uploading using PHP</title> </head> <body> You can upload a file to the server. <br/> <form action="file-upload.php" method="post" enctype="multipart/form-data"> <br/>Type (or select) Filename: <input type="file" name="myfile"> <input type="submit" value="Upload my File"> </form> </body> </html>
Step 2:
file-upload.php<?php
if(isset($_FILES['myfile'])){
$errors= array();
$file_name = $_FILES['myfile']['name']; //get file name
$file_size =$_FILES['myfile']['size']; // get file size
$file_tmp =$_FILES['myfile']['tmp_name']; //get temporary name
$file_type=$_FILES['myfile']['type']; //get file type
$file_ext=strtolower(end(explode('.',$_FILES['myfile']['name'])));
$allowed_files= array("jpeg","jpg","png"); //allowed file types
if(in_array($file_ext,$allowed_files)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 5242880){ //5*1024*1024
$errors[]='File size should be 5 MB or less';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name); //upload file to IMAGES directory
echo "Success";
}else{
print_r($errors);
}
}
?>
Note: You can write your suggestion in the comment and read our other PHP articles.

No comments:
Post a Comment