codescracker


php

PHP File Upload



« Previous Tutorial Next Tutorial »


You are free to upload files such as images, audios, videos, etc, using PHP. Information present in the phpinfo.php page describes the temporary directory that is used for the file uploads as upload_tmp_dir and the maximum size of files that is permitted to upload is stated as upload_max_filesize. These parameters are set into the PHP configuration file php.ini

Configure php.ini File to Upload File

Before going to upload file using PHP, first make sure that PHP is configured to allow file uploads. To check, open your php.ini file, seach for file_uploads directive, and set it to On like this:

file_uploads = On

Create HTML File Upload Form

The following HTML code, creates an uploader form. This form is having the method attribute set to post and enctype attribute is set to multipart/form-data

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>Upload Your File</h3>
Select a file to upload:<br />
<form action="/php/file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="60" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

Here is the output produced:

Upload Your File

Select a file to upload:


Don't change these attributes and values, to successfully upload file using PHP:

PHP Code to Create Upload File

There is one global variable available in PHP called $_FILES, is an associate double dimension array and keeps all the information related to the upload file. Here is the code to create upload file form in PHP:

<?php
if( $_FILES['file']['name'] != "" )
{
   copy( $_FILES['file']['name'], "/var/www/html" ) or 
           die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name'];  ?>
<li>File size: <?php echo $_FILES['file']['size'];  ?> bytes
<li>File type: <?php echo $_FILES['file']['type'];  ?>
</ul>
</body>
</html>

It will display following result after file will be uploaded:

Uploaded File Info:

Sent file: uploadedfile.txt

File size: 2003 bytes

File type: image/jpg

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test