PHP programming language allows uploading a file on server with html form.
File uploading with PHP is very easy to move a file to a folder. File name is passed into move_uploaded_file() function which is uploaded in folder on server .
To upload a file we must create a form with enctype.
We can set file uploading parameters in php.ini file like upload_max_filesize and upload_tmp_dir for increasing file size to upload and folder to upload file temporarily.
Also read:
Upload multiple images with Jquery and PHP
Ajax image upload with jQuery and PHP
Let’s see how to upload a file in PHP.
<?php if(isset($_FILES['image'])){ $errors= array(); $filename = $_FILES['image']['name']; $filesize =$_FILES['image']['size']; $filetemp =$_FILES['image']['tmp_name']; $filetype=$_FILES['image']['type']; $fileext=strtolower(end(explode('.',$_FILES['image']['name']))); $extensions= array("jpeg","jpg","png","gif"); if(in_array($fileext,$extensions)=== false){ $errors[]="please choose a JPEG or PNG file."; } if($file_size > 2097152){ $errors[]='File size must be exactly 2 MB'; } if(empty($errors)==true){ move_uploaded_file($filetemp,"images/".$filename); echo "Your file uploaded Successfully"; } else{ print_r($errors); } } ?> <html> <body> <form action="" method="POST" enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit" value="Upload"/> </form> </body> </html>
Going to discuss briefly about the important points used above:
multipart/form-data : It is used to allow a form to upload file successfully
Post method : this method inform browser that want to send form data to server with post method
Input name=”image” : image is a name of file to access in PHP script