PHP File Upload

PHP allows you to upload single and multiple files to server.

Configure the php.ini File

Set file_uploads = On  in php.ini configure file to upload files in server.

PHP $_FILES

PHP $_FILES is used to get file name, file type, file size, temp file name and errors associated with file.

$_FILES['filename']['name']  - It returns file name.

$_FILES['filename']['type'] - It returns type of the file.

$_FILES['filename']['size'] - It returns size of the file.

$_FILES['filename']['tmp_name'] - It returns temporary file name of the file.

$_FILES['filename']['error'] - It returns error code associated with this file.

PHP move_uploaded_file() function

php move_uploaded_file() function is used to move browsed file to new location. It moves the file if it is uploaded through the POST method.

PHP Syntax:

bool move_uploaded_file (string $filename, string $destination);

it returns that file is uploaded or not?

PHP copy() Function

Also you can use copy() function to upload file into server.

PHP Syntax:

copy(source_file,target_file,context);

PHP file_exists() Function

Function file_exists() check if file already exists!

PHP Syntax:

file_exists($target_file);

 

Create the HTML Form

We need to create the HTML Form to upload files to server. You can choose any files to upload in server using below html form.
Upload HTML Form Example :

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
  Choose file to upload:
  <input type="file" name="uploadfile" id="uploadfile">
  <input type="submit" value="Upload File" name="submit">
</form>

</body>
</html>

Follow the below rules for above HTML form.

  1. Method should be post i.e method="post"
  2. Form attribute enctype must be mandatory. i.e  enctype="multipart/form-data"
  3. <input> tag should have type="file" attribute.

PHP Script to upload file

move_uploaded_file() function is used to upload file in destination location in server.

Example :

File : upload.php

<?php
echo "<br/> File name : ".$filename=$_FILES['uploadfile']['name'];

echo "<br/> File size : ".$filesize=$_FILES['uploadfile']['size'];

echo "<br/> Temp File name : ".$filetempname=$_FILES['uploadfile']['tmp_name'];
// copy(source,destination); // Also you can use copy() function
if(move_uploaded_file($filetempname,"doc/".$filename))
{
    echo "<br/> $filename File is uploaded successfully..";    
}else
{
        echo "<br/> $filename File is not uploaded successfully..";
}

?>

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

70421