Sunday, October 15, 2017

PHP File Upload

skptricks PHP File Upload

With the help of php, it is very easy to upload files to the server. PHP file upload features allows you to upload binary and text files both. Depending upon the requirement one can upload single and multiple files through PHP script by modifying the few line of codes.

NOTE : Make sure you have mentioned/used proper authentication mechanism in you code, while uploading the files to server. Otherwise small loop holes create a trouble in future and indirectly you are providing access to unauthorized users.

PHP $_FILES

The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.

Lets see the more examples, through which you will learn how to access the $_FILES global.

$_FILES['filename']['name']

It will return the file name

$_FILES['filename']['type']

It will return MIME type of the file.

$_FILES['filename']['size']

It will return size of the file in bytes.

$_FILES['filename']['error']

It will return error code associated with this file.

$_FILES['filename']['tmp_name']

It will return temporary file name of the file which was stored on the server.

move_uploaded_file() function

The move_uploaded_file() function moves the uploaded file to a new location. User have to provide desire location wherever want to move files through script. 

Syntax:
bool move_uploaded_file ( string $filename , string $destination )

Some Important Points to remember to secure upload process while uploading files through HTML Form:
  1. Make sure that the form uses method="post"
  2. Make sure that the form uses enctype="multipart/form-data"
PHP File Upload Example

Lets see the below example to upload the image file at desire location using PHP script

imageUploadForm.html
<form action="uploaderScript.php" method="post" enctype="multipart/form-data">  
    Select File:  
    <input type="file" name="fileToUpload"/>  
    <input type="submit" value="Upload Image" name="submit"/>  
</form>

uploaderScript.php
<?php  
$tdestination_path = "c:/temp/";  
$destination_path = $destination_path.basename( $_FILES['fileToUpload']['name']);   
  
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $destination_path)) {  
    echo "File uploaded successfully!";  
} else{  
    echo "unable to upload file, please try again...";  
}  
?>



1 comment:

  1. thanking you

    this is very great article & again thanks for sharing article .


    http://www.goodluckwears.co/jeggings-manufacturer-in-india.php

    ReplyDelete