PHP file upload Script :: online picture upload

Upload one file with validation

A secure upload flow validates the PHP upload status, checks size and content type, generates a server-side filename, and moves only an accepted temporary upload. Do not trust the original filename or browser-supplied MIME type by itself.

if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $tmp = $_FILES['file']['tmp_name'];
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
    $mime = $finfo->file($tmp);
    if (isset($allowed[$mime]) && $_FILES['file']['size'] <= 2 * 1024 * 1024) {
        $name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
        move_uploaded_file($tmp, __DIR__ . '/uploads/' . $name);
    }
}

The examples below show additional variations and practical file-handling cases.

Security note: Treat the original filename and browser-reported MIME type as untrusted metadata. Validate the temporary file on the server and generate the stored filename yourself.

upload.php

<form ACTION='uploadck.php' METHOD=POST  enctype='multipart/form-data' >
Upload this file: <input type=file name='file_up'>
<input type=submit value='Upload Image'></FORM>
This html code will display a file selection button and one upload button . The form tag is bit different than the normal form tag used ( see the encrypte = enctype='multipart/form-data'). Here the attribute METHOD=POST

Upload this file:


File Upload Above code will allow uer to select the file to upload through file browser and on click of the Submit button all details are submitted to uploadck.php file.

uploadck.php

(Download all the source code at the end of this page.)
  • Check the PHP upload error and file size.
  • Detect the MIME type from the temporary file with finfo and compare it with an allowlist.
  • Generate a server-side filename and store the upload with move_uploaded_file() in a non-executable upload directory.
The destination directory must be writable by the PHP process, but it should not be made world-writable. Configure the narrowest filesystem permissions required by the web server account.

If you are uploading large files then read about maximum file execution time allowed and its adjustments.

Note that we used 'file_up' as name attribute in above html code while showing the file upload form. We can display all elements of the global array $_FILES['file_up'] inside uploadck.php file.
foreach($_FILES['file_up'] as $key => $val) {
echo htmlspecialchars(strval($key), ENT_QUOTES, 'UTF-8') . ' -> ' . htmlspecialchars(strval($val), ENT_QUOTES, 'UTF-8') . '<br>';
}
$_FILES['file_up'];
So to get the file size we have to use
$_FILES['file_up']['size']
Same way all other information can be collected from the global variable.
$file = $_FILES['file_up'] ?? null;
if (is_array($file)) {
    echo 'File size: ' . intval($file['size'] ?? 0) . ' bytes<br>';
    echo 'Upload error: ' . intval($file['error'] ?? UPLOAD_ERR_NO_FILE);
}

Maximum allowed file upload size.

In PHP installation ( php.ini file )there is a file size limit for uploading files. You can check your phpinfo() to know about this upper limit. You can also run this code to read other parameters affecting your file upload.
<?Php
echo "Maximum allowed file size: ".ini_get('upload_max_filesize');
echo "<br>";
echo "Maximum input time : ".ini_get('max_input_time');
echo "<br>";
echo "Maximum execution time : ".ini_get('max_execution_time');
echo "<br>";
echo "Maximum Post size : ".ini_get('post_max_size');
?>
From this you can add a check in the script and display message to the user saying about the error. Here is the code for that.
if (($_FILES['file_up']['size'] ?? 0) > 250000) {
    $msg = 'The uploaded file is larger than 250 KB.';
}
Here is the full code to handle file upload.

upload.php : To show the HTML form with file upload and submit buttons.
<form action='uploadck.php' method=post  enctype='multipart/form-data' >
Upload this file: <input type=file name='file_up'>
<input type=submit value='Upload Image'></FORM>
uploadck.php : To process the uploaded data after the above form submit.
<?php
$file = $_FILES['file_up'] ?? null;
if (!is_array($file) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    exit('Upload failed');
}
if (($file['size'] ?? 0) > 250000) {
    exit('File is larger than 250 KB');
}
$tmp = $file['tmp_name'] ?? '';
if (!is_uploaded_file($tmp)) {
    exit('Invalid upload');
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
$mime = $finfo->file($tmp);
if (!isset($allowed[$mime])) {
    exit('Unsupported file type');
}
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
$destination = __DIR__ . '/upload/' . $name;
if (!move_uploaded_file($tmp, $destination)) {
    exit('Could not store upload');
}
echo 'File successfully uploaded';
?>
Uploading file by using JQuery Ajax
Without refreshing pages we can upload files along with other input data by using multipart/form-data. The details we enter along with the uploaded file name can be stored in a MySQL database table.
How to Install and test
  • Download the zip file at the end of this page.
  • upload.php : HTML page showing upload button.
  • uploadck.php : PHP script to check & manage upload.
  • ini_text.php: Check your php.ini file settings.
  • readme.txt : Read the instructions.
Upload Multiple file using single form Thumbnail Image from uploaded picture Upload and create a profile picture of a member



File Deleting File Checking if file exists before deleting
PHP


Subscribe to our YouTube Channel here



plus2net.com







shabeer

02-09-2009

how di move the uploaded images from the server to my file in c:drive
smo

03-09-2009

After uploading you can display the hyper link by adding the file name. Once the link is clicked then a new window will ask you to save or open the file. That time you browse and show the location of C drive.
Robert

30-09-2009

I understand the pointing to the php file in the particular directory...but when it is online it opens a window with just the code in it?? help
lana

29-10-2009

i have added to my site and it works excellently except for large files... it seems to take forever... any tips - or is php inefficent at large scale images? 2ndly is there a way to provide the error messages underneath the form itself instead of on a new page? thanks.
sandeep

08-02-2010

thnk the discription above is very good nd easily understandble i learn very well thanks again
Jayrajsinh Radadiya

20-07-2010

this is very useful for the upload image
mohamed ashaf

23-02-2011

thks the script above is very useful for me.
none

07-10-2011

how to i make it custom extension, for example the file can only be an mu1 file?
yogesh

25-04-2012

1-How to upload images in PHP all the process with code and step wise give answers pls help.. 2-How to remove or Modified image in PHP.
ramesh

21-06-2012

thnk the discription above is very good nd easily understandble i learn very well thanks again
jarold

30-01-2013

thanks it gives me an idea....recently we are trying to make a program to upload a photo but we need to make it as our profile picture...can anyone help me or give code for this
Jothi

20-06-2014

how to use this coding i am so confussed.
prince kumar

07-09-2014

how to upload multiple images and store in the folder
smo1234

07-09-2014

There is a link at the end to next tutorial on multiple file upload. You can upload and give them a unique file name to store in a directory.
pravin dabhi

17-09-2014

this is very useful code....please tell me how to display stored images in HTML table format
parul

29-01-2015

how to use this coding very confusing.......and where i cn put this folder thumnail
aruna

18-02-2015

It will help for us only short commendline we want more information about uploading files are images thank you...........!!!!!!!!!!!!
Aamir

10-03-2015

Yes i totally understand the stuff here you give...and Thanks for this.
devi

25-03-2015

This is the output im getting after using the code above.. could you help me to correct it.. i created 2 php pages one the home page and 2nd the uploadck and the php code was pasted in uploadck .php and when it was previewed in firefox, the below thing was shown. please help me.



250000) { $msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.
"; $file_upload="false"; } if (!($_FILES[file_up][type] =="image/jpeg" OR $_FILES[file_up][type] =="image/gif")) {$msg=$msg."Your uploaded file must be of JPG or GIF. Other file types are not allowed
"; $file_upload="false";} $file_name=$_FILES[file_up][name]; $add="upload/$file_name"; if($file_upload=="true"){ if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){ }else{echo "Failed to upload file Contact Site admin to fix the problem";} }else{ echo $msg; } ?>
smo

25-03-2015

Replace <? with <?Php in both the fiels, or download a fresh copy of zip file.
Lisa

03-05-2015

I sometimes need a new banner image and we save it using the same file name: on_air_banner.jpg, we upload it wanting it to override the previous file but it won't...what do I do?
smo1234

03-05-2015

This may happen because of browser showing the image from cache. Try to open in another device and see if the image is changed.
mike

18-05-2015

Is there a way to allow the ability to take a pic with computer camera and or phone camera and use that as profile without going through the upload process?
Yogesh

15-06-2015

Amazing code. Thankyou so much
HAMEED FAIZEL

10-03-2016

I want save my photo in my pc in specific folder,i don't no to how to set a path...
Govind Verma

16-03-2016

this is easy to learn and implement in program
Dharam

05-08-2016

nice code for upload image
A nkit

23-08-2016

How to make an webpage which upload images and then give the link of image where it uploads
smo1234

03-09-2016

Check how the profile photo is displayed. Link is there at the end of the article.
smo1234

03-09-2016

To take directly a photo by using computer camera is possible by using additional plugins , not sure how that works.




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer