File uploading in php, How to upload file in php
File Uploads :-
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
Example :-
<form method="post" action="add-product.php" enctype="multipart/form-data">
<input type="file" name="myfile" id="myfile" />
<input type="submit" name="submit" value="Submit" />
</form>
File Name : add-product.php
if(isset($_POST['submit']))
{
// it return the name of the file.
$filename = $_FILES['myfile']['name'];
move_uploaded_file($_FILES["myfile"]["tmp_name"],"products/" . $_FILES["myfile"]["name"]);
}
global variable $_FILES is used for uploading files. $_FILES variable is a double dimension array and it store all the information related to uploaded file.
$_FILES['myfile']['tmp_name'] ? the uploaded file in the temporary directory on the web server.
$_FILES['myfile']['name'] ? it return name of the uploaded file.
$_FILES['myfile']['size'] ? it return size in bytes of the uploaded file.
$_FILES['myfile']['type'] ? the MIME type of the uploaded file.
$_FILES['myfile']['error'] ? the error code associated with this file upload.
move_uploaded_file() accept two parameters. The first parameter is the filename of the uploaded file, and the second parameter is the destination path where you want to move the file.
Example
File Name : add-product.php
<?php
if(isset($_FILES['myfile'])){
$errors= array();
$file_name = $_FILES['myfile']['name'];
$file_size =$_FILES['myfile']['size'];
$file_tmp =$_FILES['myfile']['tmp_name'];
$file_type=$_FILES['myfile']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['myfile']['name'])));
$fileNameCmps = explode(".", $file_name);
$fileExtension = strtolower(end($fileNameCmps));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
$file_name = basename($_FILES["myfile"]["name"]);
// function basename() return name of the file.
Example
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Note :-
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form.
The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control
Example
File Name : upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Example
File Name : upload.php
move_uploaded_file($_FILES["file"]["tmp_name"],"../images/" . $_FILES["file"]["name"]);
$qry = "insert into employee_details (employee_id, date_of_joining, first_name, last_name, user_id, password, user_type, designation, date_of_birth, gender, temp_address, perm_address, profile_pics, qualification, email, mobile_no, bank_name, account_no, account_name, ifsc_code, bank_add) values ('$emp_id', '$doj', '$first_name','$last_name','$userid','$password','$usertype','$designation','$dob','$gender','$temadd','$peradd','".$_FILES['file']['name']."','$qualification','$email','$mobile','$bank_name','$ac_no','$ac_name','$ifsc_code','$bank_add')";
$result = mysqli_query($con,$qry);
if($result > 0)
{
header("Location:add_employee.php?msg= Your data inserted Successfully.");
}
else {
header("Location:add_employee.php?msg= Sorry! Please fillup the form again.");
}
Example : File exist or not in folder.
<?php
//check image file
if (file_exists("yourfile.jpg")){
echo "Yes, file exist";
}
//you can also specify the file path and check
if (file_exists("myfolder/yourfile.jpg")){
echo "Yes, file exist";
}
?>
File exist or not in folder.
File Name :
Check a Folder (directory) exists or not
<?php
//check image file
if (is_dir("yourfolder")){
echo "Yes, folder exist";
}
?>
How to check if a function exists in PHP?
<?php
if(function_exists('myown')){
echo "yes exists"
}else{
echo "no not exists"
}
function myown(){
}
?>
File Name :
<?php
session_start();
$message = '';
if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload')
{
if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)
{
// get details of the uploaded file
$fileTmpPath = $_FILES['uploadedFile']['tmp_name'];
$fileName = $_FILES['uploadedFile']['name'];
$fileSize = $_FILES['uploadedFile']['size'];
$fileType = $_FILES['uploadedFile']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
// sanitize file-name
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
// check if file has one of the following extensions
$allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc');
if (in_array($fileExtension, $allowedfileExtensions))
{
// directory in which the uploaded file will be moved
$uploadFileDir = './uploaded_files/';
$dest_path = $uploadFileDir . $newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path))
{
$message ='File is successfully uploaded.';
}
else
{
$message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
}
}
else
{
$message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
}
}
else
{
$message = 'There is some error in the file upload. Please check the following error.<br>';
$message .= 'Error:' . $_FILES['uploadedFile']['error'];
}
}
$_SESSION['message'] = $message;
header("Location: index.php");
set php.ini files
File Name :
; Whether to allow HTTP file uploads.
file_uploads = On
; Temporary directory for HTTP uploaded files.
; Will use system default if not set.
;upload_tmp_dir =
; Maximum allowed size for uploaded files.
upload_max_filesize = 16M
; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20
; Maximum size of POST data that PHP will accept.
post_max_size = 20M
max_input_time = 60
memory_limit = 128M
max_execution_time = 30
php.ini
File Name :
<?php
echo php_ini_loaded_file();
// It?ll return the following file path if you use XAMPP on Windows:
C:\xampp\php\php.ini
How to Upload Multiple Files in php?
File Name :
<?php
if(isset($_POST['submit'])){
// Count total files
$countfiles = count($_FILES['myfile']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['myfile']['name'][$i];
// Upload file
move_uploaded_file($_FILES['myfile']['tmp_name'][$i],'upload/'.$filename);
}
}
?>
<form method='post' action='' enctype='multipart/form-data'>
<input type="file" name="myfile[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
Upload Multiple Files
$files = array_filter($_FILES['myfile']['name']);
// Count the no of files in array
$total = count($_FILES['myfile']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmp_FilePath = $_FILES['myfile']['tmp_name'][$i];
if ($tmp_FilePath != ""){
$new_FilePath = "./uploadFiles/" . $_FILES['myfile']['name'][$i];
//File is uploaded to temp dir
if(move_uploaded_file($tmp_FilePath, $new_FilePath)) {
//Other code goes here
}
}
}
Example
<?php
if(isset($_POST['submit'])){
$countfiles = count($_FILES['file']['name']);
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
$sql = "INSERT INTO fileup(id,name) VALUES ('$filename','$filename')";
$db->query($sql);
move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$filename);
}
}
?>
<form method='post' action='' enctype='multipart/form-data'>
<input type="file" name="file[]" id="file" multiple>
<input type='submit' name='submit' value='Upload'>
</form>
?>
Previous
Next