Upload and Resize an Image with PHP
Wall Script
Follow Me:
Monday, March 16, 2009

Upload and Resize an Image with PHP

Are you looking for image upload and Resize PHP script. I had implemented a simple PHP script to re-sizing image into different dimensions. It's very useful to your web projects to save hosting space and bandwidth to reduce the original image to compressed size.


Download Script

New Tutorials: Ajax Upload and Resize an Image with PHP

PHP Code
This script resize an Image into two 60px and 25px. Take a look at $newwidth you have to modify size values.
<?php 

 define ("MAX_SIZE","400");

 $errors=0;
 
 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
        $image =$_FILES["file"]["name"];
 $uploadedfile = $_FILES['file']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['file']['name']);
        $extension = getExtension($filename);
  $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") 
&& ($extension != "png") && ($extension != "gif")) 
  {
echo ' Unknown Image extension ';
$errors=1;
  }
 else
{
   $size=filesize($_FILES['file']['tmp_name']);
 
if ($size > MAX_SIZE*1024)
{
 echo "You have exceeded the size limit";
 $errors=1;
}
 
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else 
{
$src = imagecreatefromgif($uploadedfile);
}
 
list($width,$height)=getimagesize($uploadedfile);

$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
//If no errors registred, print the success message

 if(isset($_POST['Submit']) && !$errors) 
 {
   // mysql_query("update SQL statement ");
  echo "Image Uploaded Successfully!";

 }
 ?>



Extention PHP funtion
Finds file extensions.
function getExtension($str) {

         $i = strrpos($str,".");
         if (!$i) { return ""; } 
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

Download Script

289 comments:

  1. Nice one dude! thanks!

    Sean
    http://twitter.com/SeanNieuwoudt

    ReplyDelete
  2. Hey some js files are missing...

    There is only php file in the download script

    ReplyDelete
  3. To Niju Mohan: this code does not require javascript at all, which is why it's so good. Pure PHP excellence!

    ReplyDelete
  4. hello i m jack here i just see u php tutorial ,upload and resize an image with php ,but i face a problem i using the script to upload a png
    files format but after upload my files background is black colour. the oroginal files is transparency.how to make the png files still keep the transparency? thank you .

    ReplyDelete
  5. The jsquery does not download while downloading the script can you help it.....

    ReplyDelete
  6. Thanks, really helped me out! To set both a max width and height of 500 and 350 I added this:

    $newwidthX=500;
    $newheightX=($height/$width)*$newwidthX;
    if($newheightX > 350) {
    $newheight=350;
    $newwidth=($newwidthX/$newheightX)*$newheight;
    } else {
    $newheight = $newheightX;
    $newwidth = $newwidthX; }

    ReplyDelete
  7. Actually i am a java programmer. But now working in PHP. This article was very much useful for me..

    very nice and simple..

    ReplyDelete
  8. Hi i need to know the following, what if two users have different photos with the same name?

    Is there anyway to put the users ID number in front of the picture? Or rename the picture to there userid/pic.jpg?

    ReplyDelete
  9. @Russell Harrower

    Registration time you have to create folder with the name of username in hosting area.

    pic.jpg uploads into that particular folder.

    eg: <?php echo $username ?>/pic.jpg

    99% web projects no option for changing username

    ReplyDelete
  10. good work, thanks for the code. I've just addapted it for our gallery on our site.

    ReplyDelete
  11. hi again,
    sometimes it's important to upload with a unique image name.

    maybe you should add this part to your code for this;

    i've changed this block;

    $filename = "img/". $_FILES['file']['name'];

    $filename1 = "img/small". $_FILES['file']['name'];

    with this;

    $image_name=time().'.'.$extension;

    $filename = "img/". $image_name;

    $filename1 = "img/small_". $image_name;

    to upload images with a unique name via using time().

    ReplyDelete
  12. @yusuf önaldı


    Nice : "to upload images with a unique name via using time()."

    Thanks

    ReplyDelete
  13. First of all thanks!

    I have a question!
    When I upload png or gif with transparency it turns the transparency black. Do you know any solution to make it transparent again?

    ReplyDelete
  14. i want to display image from database..any idea?

    ReplyDelete
  15. Store image path in database table

    ReplyDelete
  16. Do you have any answer on how to get the transparency right in uploaded pictures?

    If not just say it so I don't have to come back and look if you have answered.

    ReplyDelete
  17. PNG transparency issue.

    I'm trying to solve this problem give some time.

    ReplyDelete
  18. Hvala, ti, res dobra in enostavna skripta.

    Tnx you, realy nice and easy script.

    ReplyDelete
  19. where image create ?

    i am not able to find created image

    ReplyDelete
  20. yes me too, i'm not able t find where they stored image...

    ReplyDelete
  21. <?php echo ("Testing can you use php in comments"); ?>

    ReplyDelete
  22. This is great! Thanks for this. 2 thumbs up!

    ReplyDelete
  23. Awesome script, worked out of the box for me.. with a few minor changes I have it doing unique ident image names + store to MySQL, so it really fits what we are trying to achieve.

    Cheers,
    Karl. [K$]

    ReplyDelete
  24. Why does this fail for large file sized images? For example, I can upload all the windows sample pictures which range in size from 27 KB to 103 KB. However, I can’t upload an image that is 1 MB such as this one http://tinyurl.com/yg4zfak

    I believe it hangs up on the line $src = imagecreatefromjpeg($uploadedfile); (or png, gif).

    How can I make it so this script will allow all sizes of images?
    Thanks.

    ReplyDelete
  25. @Scotty

    If you want to upload more than 1MB file, you have to increase the size value.

    ($size > MAX_SIZE*1024)

    ReplyDelete
  26. thanks for the script! :)
    question: what if i have multiple images? should i just create several input boxes? err.. help! :P

    ReplyDelete
  27. your script so cool but i think beginners must modify this script a little bit simply by adding 'move_uploaded_file()' function and must create a directory name 'images'


    kind regards and thanks for sharing!

    ReplyDelete
  28. excellent man, works good. thanks for the example

    ReplyDelete
  29. nice script and as stated above this is alot for newbies if you could please help with how and where the changes could go am a learn as you go and am building my site from tutorials, so if you could please help as to where in page this goes so that the images could show I would really appreciate it my site is not up yet but am gonna place this code in the section so that visitor could post there pics of the party they have being and so! its gonna go on the section called subetusfotos.html Thanks Maria and Rey

    ReplyDelete
  30. hi. what about if i would like upload 2 or more photos? what to do? i`m new in php:/ help pls..
    regards

    ReplyDelete
  31. very good stuff buddy !

    ReplyDelete
  32. to solve the png transparency
    new width and heigt are ratios that i am working with
    $temp=imagecreatetruecolor($newwidth,$newheight);

    if($extension=="jpg" || $extension=="jpeg" ){
    $img=imagecreatefromjpeg($upload);
    imagecopyresampled($temp,$img, 0, 0, 0, 0,$newwidth,$newheight,$width,$height);
    imagejpeg($temp,$path,100);
    }
    else if($extension=="png"){
    $img=imagecreatefrompng($upload);
    imagecopyresampled($temp,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
    imagepng($temp,$path);
    }
    else if($extension=="gif"){
    $img=imagecreatefrompng($upload);
    imagecopyresampled($temp,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
    imagepng($temp,$path,100);
    }

    ReplyDelete
  33. Nice one!
    Only if you're file is to big, then he will also store it.. I build in a specification while it is exists or not and even a max height..

    Thanks a lot dude!

    ".$filename1;

    if(file_exists($filename)) {
    $change='Het bestand '.$filenam.' bestaat al.';
    $errors=1;
    }
    elseif(file_exists($filename1)){
    $change='Het bestand '.$filenam.' bestaat al.';
    $errors=1;
    }
    else{

    $filename = stripslashes($_FILES['file']['name']);

    $extension = getExtension($filename);
    $extension = strtolower($extension);


    if (($extension != "jpg"))
    {

    $change='Het plaatje dient een .jpg bestand te zijn ';
    $errors=1;
    }
    else
    {

    $size=filesize($_FILES['file']['tmp_name']);


    if ($size > MAX_SIZE*1024)
    {
    $change='You have exceeded the size limit! ';
    $errors=1;
    }
    else{

    if($extension=="jpg" || $extension=="jpeg" )
    {
    $uploadedfile = $_FILES['file']['tmp_name'];
    $src = imagecreatefromjpeg($uploadedfile);

    }

    echo $scr;

    list($width,$height)=getimagesize($uploadedfile);


    $newwidth=505;
    $newheight=($height/$width)*$newwidth;
    if($newheight>500){
    $newheight=500;
    $newwidth=($width/$height)*$newheight;
    }
    $tmp=imagecreatetruecolor($newwidth,$newheight);


    $newwidth1=80;
    $newheight1=($height/$width)*$newwidth1;
    if($newheight1>95){
    $newheight1=80;
    $newwidth1=($width/$height)*$newheight1;
    }
    $tmp1=imagecreatetruecolor($newwidth1,$newheight1);

    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

    imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);


    $filename = "schilderijen/". $_FILES['file']['name'];

    $filename1 = "thumbs/th_". $_FILES['file']['name'];



    imagejpeg($tmp,$filename,100);

    imagejpeg($tmp1,$filename1,100);

    imagedestroy($src);
    imagedestroy($tmp);
    imagedestroy($tmp1);
    }}

    }
    }//Als bestandgrootte kleiner is dan 1 MB
    }//als de bestanden nog niet bestonden.
    //If no errors registred, print the success message
    if(isset($_POST['Submit']) && !$errors)
    {

    // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
    $change=' Image Uploaded Successfully!';
    }

    ReplyDelete
  34. I have a better solution for the png transparency
    else if($extension=="png"){
    $img=imagecreatefrompng($upload);
    //If our image have white background imagealphablending($temp,false);
    //we capture the bg of our image $color=imagecolorallocatealpha($temp, 0, 0, 0, 127);
    //fill the bg we capture before to put it in the resized one
    imagefill($temp,0,0,$color);
    //we restore the transparency(bg) imagesavealpha($temp,true);
    //then we follow the steps of our friend =) imagecopyresampled($temp,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
    imagepng($temp,$p.'_m'.".".$extension); I hope it helps you :D
    move_uploaded_file($upload,$p.".".$extension);

    ReplyDelete
  35. nice, i want to make an image resize but like (50x50, 20x20,...).
    thanks..

    ReplyDelete
  36. Works great but I have a problem with gif extension. Uploaded gif images is black.
    Output:
    Warning: imagecreatefromgif() [function.imagecreatefromgif]: '/tmp/phpThbsBn' is not a valid GIF file in /home/rapidm/public_html/test/untitled.php on line 70

    Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/rapidm/public_html/test/untitled.php on line 79

    Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/rapidm/public_html/test/untitled.php on line 85

    Help, anyone pls.
    Thanks

    ReplyDelete
  37. Yeah! I got it finally...Thank u very much...I was facing a problem with resizing images since 2 days and your script helped me to complete my task..

    ReplyDelete
  38. Hi,

    Thanks for the script. I just cant get it working though?

    I have made a folder called images and one inside that called small.

    Im testing it but nothing happens. IT just says its uploaded successfully except the images folder is empty.

    Please help

    ReplyDelete
  39. yes me aswell - It says "uploaded successfully" but not an image being placed in the images folder on mine ftp.... me too I think is something wrong with what Im doing here?

    ReplyDelete
  40. Thanks man! I'm from Brazil!
    I love the web too!!!

    ReplyDelete
  41. To get file extension just need a bit code :

    $ext = substr(strrchr("hello.php", "."), 1);

    Vasim Padhiyar

    http://scriptforphp.blogspot.com

    ReplyDelete
  42. Dude, you rock. I got this working on the first try! Much love.

    ReplyDelete
  43. How to add multiple images?

    ReplyDelete
  44. What happens when an image already exist with the file name? As I see it's doesn't upload an image if another image is already uploaded with the same name... Is it possible to rename uploaded image if another image already exists?

    ReplyDelete
  45. @levani

    Add Timestamp or Username to image file name.

    eg: logo.png

    to

    eg : levanilogo.png or 1270723550logo.png

    ReplyDelete
  46. Did someone already found a solution for the black .GIF output?

    Thanks for the script b.t.w, it really helped me a lot!

    ReplyDelete
  47. @ John:

    Remember to give permissions to folders, the file wont upload to the server if you dont give the right permissions.

    @Srinivas

    Thanks friend, you helped me a lot.

    @ every reader

    If you are using a form to store data in the server and in the database, you may be using an ID for each entry to the DB, just include the ID and that way you will be able to find who or which entry the image belongs to.

    ReplyDelete
  48. there are missing some js files ?!
    Or clear script code !

    ReplyDelete
  49. hi
    can u give me d code to add watermark to images?
    thanks in advance

    ReplyDelete
  50. Hi,

    is that possible by any means that the image is resized at the client side without sending it to the server. Then it can be submitted.
    It will be helpfull for slower connections.??

    ReplyDelete
  51. Very nice script working fine on server but how to run this on local host?

    Can anyone help me?

    ReplyDelete
  52. can u post a new code for image upload using php,such that after upload we can have cropping and rename the image using random number.
    plz help me ...

    ReplyDelete
  53. This is an awesome script. It's works very well and help me to finish my work faster.
    Thank you

    ReplyDelete
  54. @ Anonymous, Is this script running on localhost. I want to work with this script for one project but it doesn't work on local but fine on server.

    same problem with u?

    ReplyDelete
  55. Great script! Thx for sharing it!

    ReplyDelete
  56. damn... nice...

    ReplyDelete
  57. hey....great code snippet..thanx for sharing :)

    ReplyDelete
  58. thanx for the code..but i have few questions:

    1) where does the image created being stored?
    2) how do you store the image links inside the database?

    im kinda new for php..can someone fill me in please..

    ReplyDelete
  59. 1) i tried the code..it shows no error but yet the produced image is not in the folder i specified

    2) how can i save the produced image links inside the database?

    ReplyDelete
  60. 1) the code has no error..yet i cant seem to found the produced image..

    2) how do i save the image links inside the database?

    can someone please help me in this..really need your help..

    ReplyDelete
  61. @Azarul

    Big Image :
    $filename = "images/". $_FILES['file']['name'];

    Small Image:
    $filename1 = "images/small".$_FILES['file']['name'];

    Images uploading in "images" folder

    Eg: "abc.jpg" if you upload this file. It will upload to

    images/adc.jpg
    images/smallabc.jpg

    So you have to store this path in database table

    ReplyDelete
  62. sory for the 3 comments i post earlier..thought that my post wasnt coming up :(

    @srinivas
    i tried to create the images folder inside my htdocs..but the produced images arent there..can u help me figure out why this happen?

    ReplyDelete
  63. thanks... works great... very simple...

    took me not more than 30 seconds for it to be fully functional on my computer.

    Regards,
    Basit

    ReplyDelete
  64. Hy, I just edit your code and make multi pic uploads
    http://www.box.net/shared/2s3i7nsqch
    I'm new in PHP programing, just learning, sorry if bad programing but it works like a charm ,
    Thanks again

    ReplyDelete
  65. Hy again, I edit it for second time, so I can esaly define how many uploads are,
    in array just add a variable

    http://www.box.net/shared/0jzcd8689s

    $slike = array(file, flie1, fliel2, file3 ...)

    but the hole file is acting funny , , sometimes , he uploads 3 images , sometimes 2 sometimes 1 , without errors ,
    Help

    ReplyDelete
  66. Looks like I'm fighting with my sellf.
    Now its workig
    Multi uploads

    just add more variables in array $slike(file, file1, file2, file3 ......)

    http://www.box.net/shared/tdf0zpaieu

    ReplyDelete
  67. Hy,
    This is new Multi Upload with Highslide. Ther wear som problems with naming images by time so i aded something.
    Stil if you wont add more pictures yust add more variables in array $slike = array(file, file1, file2, file3, .....)
    http://www.box.net/shared/n85bj1hbh1

    ReplyDelete
  68. Hi munge83,

    Great adds to the script, could you please tell me how to give each uploaded picture their own path so that I can add 3 image paths straight into a mysql database and call each picture straight from the database?

    Many thanks in advance
    Dan

    ReplyDelete
  69. Hy,

    I created a database conection vith the picture like you asked.

    you wil haw to create a mysql database caled "test" and table "slike_ap" like this http://www.box.net/shared/nz1hepy50p

    and new php with highslide is here
    http://www.box.net/shared/7dux1fdvrm

    ReplyDelete
  70. Thank you so much. Srinivas!!!

    @munge83: Thank you for your multiple upload script.

    Could you please help me? I want to resize 5 images to be a square size like this http://img251.imageshack.us/img251/4406/tarsan200x200.jpg
    (keep original ratio image in the middle of white background.)


    also, I want to use these 5 pictures in my next php file. However I cannot find what their name in your code. Could you please point me to the name of each one. So I can use them in my next php file.

    Thank you vey much,

    ReplyDelete
  71. """"also, I want to use these 5 pictures in my next php file. However I cannot find what their name in your code. Could you please point me to the name of each one. So I can use them in my next php file.""""

    From above, I mean....

    How can I write a code to show pic1, pic2, pic3, pic4, pic5 on my webpage. These 5 pictures will be shown horizontaly inside a big frame.

    Thank you so much.

    ReplyDelete
  72. I copied the scrip exactly as it is shown and nothing gets uploaded..
    $image = Null $_FILES["file"]["name"];
    $uploadedfile = Null $_FILES['file']['tmp_name'];

    If it works for other people it should work for me But it dosen't work... for me...

    ReplyDelete
  73. Can you convert it to ajax? Thanks!

    ReplyDelete
  74. This should do it:
    $file = $_FILES['file']['name'];

    I would really like to see the script modified so that the resized photos are pasted onto a square canvas and so you can upload multiple images.

    I need to be able to upload up to 4 images at a time > resize original and create a thumbnail also > add thumbnails to a square canvas. Im almost there.

    ReplyDelete
  75. Great Script... Thanks dude..

    One problem that I have is when I try uploading a bigger size image such as 1MB.

    Even though I changed the MAX_SIZE to a bigger value, the page runs for a bit and then it just stops... and the only thing I see is a white screen.

    Even If I try to upload an image that exceeds the maximum size it does not give me the message "Limit Exceeded..." it just stops on the white background.

    If you have any solution for this it would be great..

    Thnks in advance..

    ReplyDelete
  76. check your php.ini for size restirctions

    ReplyDelete
  77. great script but when you press upload without a selected image it says "Successful Upload". Is there any fix for this?

    ReplyDelete
  78. Really nice, simple script! Worked without a problem. I cut it up and put a few pieces into a photo gallery I just built. Very very nice!

    ReplyDelete
  79. hi is any way to change the size of the uploaded image other then 60 x 40
    thank you

    ReplyDelete
  80. Hi thank for the script it works grate , to change the size of one of the pics i change the line number 75 on the script

    FROM : $newwidth=60;

    TO : $newwidth=500;

    then everything works.
    one more time thanks

    ReplyDelete
  81. Can't you use $_FILE['file']['type'] for image file type check instead of dealing with extension?

    ReplyDelete
  82. hi am trying this script.. But i unable to resize my image. the resized images is not display. just a black image only display. can you help me to avoid this problem?

    ReplyDelete
  83. @Stjepan: the Mime-type can be easily modified by a user, so they aren't safe to use..

    ReplyDelete
  84. hi muthu , look on your server path like ../image
    some times this is the reason because things don't work that happens to me on godaddy every time i create some application with fireworks ore Dreamweaver , like all Java script generated by them , what i find on those cases is that i have to make some little changes on my script let me give you an example :
    ORIGINAL : img src="imagenes/spacer.gif" width="7" height="1" border="0" alt=""
    I HAVE TO CHANGED TO :
    img src="/imagenes/spacer.gif" width="7" height="1" border="0" alt=""


    GOOD LUCK !!!!

    ReplyDelete
  85. how to use this code in zend framwork

    plz give me solution step by step and with download script

    ReplyDelete
  86. Awsum code...just loved it...:)

    ReplyDelete
  87. Nice code, helped out alot. However you can shrink the get extension function thus..

    function getExtension($str) {
    return end(explode(".", strtolower($str)));
    }

    ReplyDelete
  88. guys it really works for me... i can easily implement this code..
    thank you..!!

    ReplyDelete
  89. hey man great job but i have an important question
    .i have used your php script for one of my pages and .gif images with white background are turning black any idea why??

    ReplyDelete
  90. Absolutely fantastic! Many thanks for this script.
    I have been trying to get this functionality into a web page without success and your script does the job simply and quickly.

    ReplyDelete
  91. Hi!

    Thanks for very nice code!

    I added the following code...

    $ratio = $width/$height;

    if ($newwidth/$newheight > $ratio) {
    $newwidth = $newheight*$ratio;
    $newwidth1 = $newheight1*$ratio;
    $newwidth2 = $newheight2*$ratio;
    } else {
    $newheight = $newwidth/$ratio;
    $newheight1 = $newwidth1/$ratio;
    $newheight2 = $newwidth2/$ratio;
    }


    ... after the following line:

    list($width,$height)=getimagesize($uploadedfile);

    to make sure that the longest side alwas are the
    same independent of if it's a Landscape or Portrait image.

    Any one how can tell why pictures bigger then 3.638 x 3.139px or 3.335 x 3.335px isn't possible to upload - this is fact independent of file size in kb.

    thks

    ReplyDelete
  92. hi .. i am newbie here ....do anyone know to store image path in database?

    thanks guys ...

    ReplyDelete
  93. can anyone make it where, when upload multiple. can highlight a unlimited files to re-size at one time into ftp?

    i saw the adjustment for multiple upload, but that's still one at a time sorta.

    ReplyDelete
  94. Thanks man nice script

    ReplyDelete
  95. i still have the big image size problem when uploading the image more then 1MB, can anyone help please

    ReplyDelete
  96. welldone!! the only problem i have when i upload image bigger then 1mb nothing happens can anyone tell me solution?

    ReplyDelete
  97. Nice Script.
    But is is also possible to use this script with an insert code? I'm new at php and don't know how to get it working with an insert sql.
    Thnx a lot.

    Elsa

    ReplyDelete
  98. Is it also possible to use this script with an insert sql? Please help.
    Like the script and would love to have it working.

    Elsa

    ReplyDelete
  99. hi all


    how can i change uploaded image name not abc.jpg
    i want to be random numbers 2131231.jpg

    ReplyDelete
  100. Really nice Script. I love it. I love U!!!!

    ReplyDelete
  101. violet.wang@gmail.comApril 1, 2011 at 12:12 PM

    Hey, do you have a script that only resize? i mean the weight of the image

    ReplyDelete
  102. That is a Great Tutorial Dude... Thank's

    ReplyDelete
  103. is very good, but not as original size is maintained

    ReplyDelete
  104. Hi srinivas , i want code for automatically send mail to the user like "Thank for registration with us " please help me dude

    ReplyDelete
  105. very useful post. thanx to share.

    ReplyDelete
  106. try this:

    function getExtension($str) {
    return return pathinfo($str, PATHINFO_EXTENSION);
    }

    ReplyDelete
  107. Great script - here is the fix to correct the file upload validation error that always says file uploaded succesfully - even when there is no file. Basically $_FILES always returns true so you have to go by the file size. I added this at the end (after the very last $change variable update)

    //If no file,

    if (isset($_POST['Submit']) && (isset($_FILES["file"]["size"]) && ($_FILES["file"]["size"] <= 0)) ){
    $change='No file';
    }

    cheers

    Jeff

    ReplyDelete
  108. Thanks a lot dude... very nice code..

    cheers

    sawan mahajan

    ReplyDelete
  109. Very useful code !!
    Thanks
    Deep

    ReplyDelete
  110. hi there can you write a script where the user can upload an image and change name of the image as well..

    ReplyDelete
  111. That's great idea. I'm working on next version live upload and cropping image.

    ReplyDelete
  112. Hey, you people who complain for no js in the downloaded source files. Where the hell do you see js in this tutorial??? It is pure PHP!

    ReplyDelete
  113. To stop larger files than the MAX_SIZE still being uploaded I have put die; into this part of the script.

    if ($size > MAX_SIZE*1024)
    {
    echo "You have exceeded the size limit";
    $errors=1;
    die;
    }

    ReplyDelete
  114. its popoing out undefined function, though i have v.5.2.5

    ReplyDelete
  115. Hi,great scrip but i've the problem with the images bigger than 1 MB, somebody can help me? Thanks

    ReplyDelete
  116. Bigger than 1 MB increase MAX_SIZE value

    define ("MAX_SIZE","400");

    ReplyDelete
  117. I don't think this code would work with windows XP. It should be UNIX. I have webserver with windows xp. What do I have to change/edit the code?

    ReplyDelete
  118. Hi Srinivas,

    The script is quite nice but does have a few bugs. The main one being the error handling of max file size, file type and No file. The files are all being uploaded before the error message displays.

    I tried Kyle's suggestion by placing "die;" after the if statements but this only gives me a blank screen.

    Any help on this would be greatly appreciated.

    Thanks again..

    ReplyDelete
  119. Thanks, just what I needed for a new project.

    ReplyDelete
  120. How could you set this up with your contact form, say if you were uploading a file. Also how would you add a vote script to the picture? Thanks so much

    ReplyDelete
  121. hi... it worked well on my local host, but wen i transfered same script to my live servers it didn't upload the file and it still gave no error. any idea?

    ReplyDelete
  122. Wow...

    This script save my day...

    Thanks dear...

    ReplyDelete
  123. thank you was usefull for me!

    ReplyDelete
  124. Hi,
    Thank you for the good tutorial,
    I have one question, what happen if the user didn't upload any image what will happen?

    ReplyDelete
  125. @ Mike

    ...
    $newwidthX=500;
    $newheightX=($height/$width)*$newwidthX;
    if($newheightX > 350) {
    $newheight=350;
    $newwidth=($newwidthX/$newheightX)*$newheight;
    } else {
    $newheight = $newheightX;
    $newwidth = $newwidthX; }
    ...

    Your code makes the uploaded image 500px wide even if the original file was narrower.

    How can this be edited so it does not increase the image's width if the original is less than 500px wide?

    Thanks, Jeff

    ReplyDelete
  126. hello guys, i am trying to use this script but i want it to be able to upload 7 files... 6 of them i want to have name 01.jpg, 02, 03.... 06.jpg and the other one i want to be named profile.jpg.. how can i do this, like to auto-rename it and in case the person who upload them wants to replace one of them how can i do this? like how can i make them able to erase a specific file out of the 7 they already uploaded and how can i let the script know eactly which one is missing and rename it just like that (lets say they erased file 05.jpg.. i want the script to identify 05.jpg is missing and thats the file name it should use for the new file....) or if its too complicated i would like to just replace an specific existing file with a new one... ughhh this is so complicated i dont even know how to explain it... so frustrating!

    ReplyDelete
  127. Wow, this works! Thank you so much! :)

    ReplyDelete
  128. A BIG THANKS to Srinivas! Great script and a huge help!

    ReplyDelete
  129. Nice and short
    gud work

    ReplyDelete
  130. thanks dude great script really loving it :)

    ReplyDelete
  131. works great ! thanks man !!!!! cody

    ReplyDelete
  132. O único que funcionou de todos os que procurei.

    ReplyDelete
  133. Thanks for this, work really well. Just one question, how t=do you keep one of the images, $tmp, the original size as it was upoloaded? I've tried a few things but can't get it to work.

    Thanks

    ReplyDelete
  134. excelent tutorial, is the easy way to make some thumbnails. I have a nice but complicated script to make 3 thumbs square and 1 proportional with the original size. with your example I will make shorter.
    thx again.

    ReplyDelete
  135. Hi. is possible when upload the image:

    eg: photo1.jpg and the another one photo@2x.jpg

    put the @2x after the name?

    Thanks

    ReplyDelete
  136. Hey great script.

    But i think you missed

    $uploadedfile = $_FILES['file']['tmp_name'];

    when Image extension is gif

    Please correct it.

    Vasim Padhiyar

    ReplyDelete
  137. Hi. is possible when upload the image:

    ex: photo1.jpg and the another one photo@2x.jpg

    put the @2x after the name?

    Thanks

    ReplyDelete
  138. It becames very useful for me.
    Thanks a lot.

    ReplyDelete
  139. nice tutorial, thanks :)

    ~kangmasjuqi

    ReplyDelete
  140. Thanks great works

    ReplyDelete
  141. Very simple and nice, i had a upload script already and i looked up a lot on how to resize images, at first i thought cropping and resizing are the same thing but then i learned its not, i first cropped images randomly which would have cropped any portion of the image...then i realized, all i wanted to do is make it look smaller so resizing is what i wanted..
    So i came on this :D and loved it, learned a lot from it..

    ReplyDelete
  142. I havent read through all the comments so i dont know if this was answered... png files show a black background and dont preserve their transparency. Any way to fix this? Great script here.

    ReplyDelete
  143. What I am wondering about only ONE person commented on here, which surprises me. Anyway, the "js/___.js" files for: displaymsg.js and ajaxdelete.js are not included, what effect or impact do they have on this script?

    ReplyDelete
  144. hmm thanks for the explanation.. very useful :)

    ReplyDelete
  145. You can also check this blog, which explains the same thing in a different way
    http://blog.wisecells.com/resize_upload_images_php

    ReplyDelete
  146. Cooooooool! brawo!

    ReplyDelete
  147. hi... thanks for the code

    i have one query

    how can i fix the height and width of uploaded image file when they are uploading in a folder

    ReplyDelete
  148. any body give me this complete script

    ReplyDelete
  149. Thank you. Worked for me first time. Saved me a lot of work. Thanks.

    ReplyDelete
  150. <? // Where the file is going to be placed
    $target_path = "upload/";

    /* Add the original filename to our target path.
    Result is "uploads/filename.extension" */
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
    $target_path = "upload/";

    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ". basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
    } else{
    echo "There was an error uploading the file, please try again!";
    }


    Warning: move_uploaded_file(upload/cap_bg.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in C:\inetpub\vhosts\domain.com\subdomains\f\httpdocs\up\upload_pic_ac.php on line 11

    ReplyDelete
  151. Very Nice!!!
    Many thanks for such a nice clean easy to use script!!
    That is why open source is the best!!!!

    ReplyDelete
  152. what is to add when i use multifile pic upload?

    ReplyDelete
  153. I get an error using imagecreatefrom_____ and imagecreatetruecolor. Any ideas what this could be from? Any help will be greatly appreciated

    ReplyDelete
  154. I need to validate the image size and if it doesn't have square dimensions I need to present the user with a dialog informing them "The image must have the same width and height".


    How can i check that if image have square dimensions or not?

    ReplyDelete
  155. Thank you, bro!

    ReplyDelete
  156. How to keep same name for both files?


    Any suggestions please.

    ReplyDelete
  157. Your code nice. I face a problems that I insert 60 image and ok but when I insert 61 Image then not insert. Image not insert,but when I insert name then insert.Image+name two field data not insert. Without image and single field insert.

    ReplyDelete
  158. i need code in php for uploading and updating multiple images in php when add more() function in java scripting is applied

    ReplyDelete
  159. Nice Tutorial
    I changed File Names as
    $imgname = $_FILES['image']['name']."_".$newwidth;
    with this Got filename as "filename.jpg_150"

    How to get filename as "filename_150.jpg" ?

    ReplyDelete
  160. Hi,

    This is really a awesome script i found for image re size. It works fine.Thanks a lot. Keep going.

    ReplyDelete
  161. Can you tell about how to catch the filename and filename1 into database?
    when i choose an image it doesn't catch filename and filename1 yet, although i click Upload button.
    but i want to let the filename and filename1 appear while i have choose the image file.....
    Can You Tell Me Please,,,, Please......
    Thank You Before...... :)

    ReplyDelete
  162. i have something to ask all of you....anyone can help me please.......

    this is code i have changed:
    if(isset($_POST['Submit'])) {

    $file1 = $_POST['file1'];
    $file2 = $_POST['file2'];

    $insert="insert into image(name, des) VALUES('$file1', '$file2')";
    $result=mysql_query($insert);

    if($result){
    echo "Successfull";
    }

    else {
    echo "error";
    }

    // mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
    $change=' Image Uploaded Successfully!';

    }


    input type="text" name="file1" value=""
    input type="text" name="file2" value=""


    and the problem is:
    when i click "browse button" an image file, it just not catch the filename and filename1.
    but even i click "upload button" it show the filename and filename1..

    can you show me how to catch filename and filename1 while i click "browse button"

    ReplyDelete
  163. thank you so much, this code save my time.best wishes.

    ReplyDelete
  164. Thanks DUDe.

    This code helps me lot...

    Thanks again...

    SK

    ReplyDelete
  165. For the png transparency problem, I used:


    $tmp=imagecreatetruecolor($newwidth,$newheight);
    imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127));
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
    imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

    $filename = "images/". $_FILES['file']['name'];

    imagepng($tmp,$filename);

    NOTE I USED: imagepng($tmp,$filename);
    The example above is always using imagejpeg, which will give a problem after adding the transparency calls.

    ReplyDelete
  166. I want to upload images from a URL. (from another sever)
    what are the changes i have to do...

    thank you!

    ReplyDelete
  167. Hi ALl,
    i want to upload multiple images of TIFF at one selection and convert them into JPG while uploading. please help me with an idea and code.

    Thanks in advance.

    ReplyDelete
  168. Cheers man, I sat down to write this myself to resize 2 images on the fly but a quick Google for the file extension function and I came accross this post so now you have saved me the time :) much appreciated.

    ReplyDelete
  169. hello,

    i am using the file as it is in download script link above with no changes, except image folder.

    why when i upload a 5 mb image there shows "image uploaded 'Image Uploaded Successfully! ' and in the folder there is nothing, just blank.

    why this happens?

    thanks! :)

    ReplyDelete
  170. hi,

    is there any version of the script with bugs fixed and everything?

    ReplyDelete
  171. Srinivas, i read your blog from 8,9 months and i've learned a lot of things from you. Now i've decided to thank you for all, and i'm sure you've helped a lot of people like me. Thanks again for your great job!

    ReplyDelete
  172. Hi, prior to PHP5.2 this script worked but i recently upgraded to 5.3.xx and i start getting 403 error below:
    "Access forbidden! You don't have permission to access the requested object. It is either read-protected or not readable by the server. If you think this is a server error, please contact the webmaster. Error 403 localhost 6/2/2012 8:59:05 AM Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1"
    Can you tell me what happened?
    Thanks in advance. Sameul

    ReplyDelete
  173. Great script sir!
    but i have a problem with this script that when i set image width like 500kb then it all times upload 500kb while when i use a small size of image like 200kb so it's not upload 200kb while it's upload 500kb.

    Any one help me to solve this issues!!!

    Thanks
    :)

    ReplyDelete
  174. Thx a lot!!!!!!
    its very useful for me.

    ReplyDelete
  175. Thx a lot!!!!!!
    its very useful for me.

    ReplyDelete
  176. Just what I needed, Thanks!

    ReplyDelete
  177. I love your script. Excellent.

    Just one question - if I want to limit the upload size to 1mb do I leave ($size > MAX_SIZE*1024) as it is.

    I don't want images larger than 1mb being uploaded.

    Thanks. And again - great script!

    ReplyDelete
  178. Thanks dude nice one :)

    ReplyDelete