Configure The “php.ini” File
open your php.ini file and search for following keys and make some changes as i change like below :
1 . file_uploads = On
2 . upload_max_filesize = 50M
upload_max_filesize helps you to maximize file uploading size, by default it is 2, you can maximize as your need.
Read also : File uploading and View Script with PHP & MySQL
The html form :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
Make Sure : 1 . Method=”POST” : it should be POST. 2 . enctype=”multipart/form-data” : it’s specify content-type to be uploaded.
3 . type=”file” : attribute of the input
tag shows input field as a file selector with a “Browse” Button.
The PHP
We will use isset($_FILES[‘name_of_input’]) to make sure some file is selected.
here in this following script javascript was just used for message that file was upload or not.
put this script just above <!DOCTYPE html>
tag
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('successfully uploaded');</script><?php
}
else
{
?><script>alert('error while uploading file');</script><?php
}
}
?>
PHP Script explained :
1 . $folder : Directory where files are uploaded.
2 . move_uploaded_files : php function that moves selected file to the specified folder.
3 . rand() : this is the awesome function that enables you to upload same files multiple times.
Complete Script
index.php
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('successfully uploaded');</script><?php
}
else
{
?><script>alert('error while uploading file');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
copy-paste the above script and try to upload any file, You can use this for Uploading image’s ,PDF’s,MP3,Video, Doc any file types make sure you change the necessary parts in the script.
that’s it