Upload and Resize an Image with PHP
Wall Script
Wall Script
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
web notification

305 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. 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
  16. PNG transparency issue.

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

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

    Tnx you, realy nice and easy script.

    ReplyDelete
  18. where image create ?

    i am not able to find created image

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

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

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

    ReplyDelete
  22. 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
  23. 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
  24. @Scotty

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

    ($size > MAX_SIZE*1024)

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

    ReplyDelete
  26. 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
  27. excellent man, works good. thanks for the example

    ReplyDelete
  28. 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
  29. hi. what about if i would like upload 2 or more photos? what to do? i`m new in php:/ help pls..
    regards

    ReplyDelete
  30. very good stuff buddy !

    ReplyDelete
  31. 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
  32. 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
  33. 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
  34. nice, i want to make an image resize but like (50x50, 20x20,...).
    thanks..

    ReplyDelete
  35. 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
  36. 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
  37. 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
  38. 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
  39. Thanks man! I'm from Brazil!
    I love the web too!!!

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

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

    Vasim Padhiyar

    http://scriptforphp.blogspot.com

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

    ReplyDelete
  42. 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
  43. @levani

    Add Timestamp or Username to image file name.

    eg: logo.png

    to

    eg : levanilogo.png or 1270723550logo.png

    ReplyDelete
  44. 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
  45. @ 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
  46. there are missing some js files ?!
    Or clear script code !

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

    ReplyDelete
  48. 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
  49. Very nice script working fine on server but how to run this on local host?

    Can anyone help me?

    ReplyDelete
  50. 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
  51. This is an awesome script. It's works very well and help me to finish my work faster.
    Thank you

    ReplyDelete
  52. @ 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
  53. Great Script! Thanks a bunch!

    ReplyDelete
  54. Great script! Thx for sharing it!

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

    ReplyDelete
  56. 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
  57. 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
  58. 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
  59. @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
  60. 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
  61. thanks... works great... very simple...

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

    Regards,
    Basit

    ReplyDelete
  62. 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
  63. 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
  64. 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
  65. 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
  66. 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
  67. 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
  68. 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
  69. """"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
  70. 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
  71. Can you convert it to ajax? Thanks!

    ReplyDelete
  72. 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
  73. 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
  74. check your php.ini for size restirctions

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

    ReplyDelete
  76. 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
  77. hi is any way to change the size of the uploaded image other then 60 x 40
    thank you

    ReplyDelete
  78. 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
  79. Can't you use $_FILE['file']['type'] for image file type check instead of dealing with extension?

    ReplyDelete
  80. 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
  81. @Stjepan: the Mime-type can be easily modified by a user, so they aren't safe to use..

    ReplyDelete
  82. 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
  83. how to use this code in zend framwork

    plz give me solution step by step and with download script

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

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

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

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

    ReplyDelete
  87. 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
  88. 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
  89. 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
  90. hi .. i am newbie here ....do anyone know to store image path in database?

    thanks guys ...

    ReplyDelete
  91. 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
  92. Thanks man nice script

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

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

    ReplyDelete
  95. 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
  96. 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
  97. hi all


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

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

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

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

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

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

    ReplyDelete
  103. try this:

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

    ReplyDelete
  104. 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
  105. Thanks a lot dude... very nice code..

    cheers

    sawan mahajan

    ReplyDelete
  106. Very useful code !!
    Thanks
    Deep

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

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

    ReplyDelete
  109. 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
  110. 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
  111. its popoing out undefined function, though i have v.5.2.5

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

    ReplyDelete
  113. Bigger than 1 MB increase MAX_SIZE value

    define ("MAX_SIZE","400");

    ReplyDelete
  114. 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
  115. 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
  116. Thanks, just what I needed for a new project.

    ReplyDelete
  117. 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
  118. 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
  119. Wow...

    This script save my day...

    Thanks dear...

    ReplyDelete
  120. thank you was usefull for me!

    ReplyDelete
  121. 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
  122. @ 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
  123. 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
  124. Wow, this works! Thank you so much! :)

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

    ReplyDelete
  126. Nice and short
    gud work

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

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

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

    ReplyDelete
  130. 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
  131. 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
  132. Hi. is possible when upload the image:

    eg: photo1.jpg and the another one [email protected]

    put the @2x after the name?

    Thanks

    ReplyDelete
  133. Hey great script.

    But i think you missed

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

    when Image extension is gif

    Please correct it.

    Vasim Padhiyar

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

    ex: photo1.jpg and the another one [email protected]

    put the @2x after the name?

    Thanks

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

    ReplyDelete
  136. nice tutorial, thanks :)

    ~kangmasjuqi

    ReplyDelete
  137. Thanks great works

    ReplyDelete
  138. 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
  139. 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
  140. 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
  141. hmm thanks for the explanation.. very useful :)

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

    ReplyDelete
  143. 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
  144. any body give me this complete script

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

    ReplyDelete
  146. <? // 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
  147. Very Nice!!!
    Many thanks for such a nice clean easy to use script!!
    That is why open source is the best!!!!

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

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

    ReplyDelete
  150. 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
  151. How to keep same name for both files?


    Any suggestions please.

    ReplyDelete
  152. 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
  153. i need code in php for uploading and updating multiple images in php when add more() function in java scripting is applied

    ReplyDelete
  154. 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
  155. Hi,

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

    ReplyDelete
  156. 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
  157. 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
  158. thank you so much, this code save my time.best wishes.

    ReplyDelete
  159. Thanks DUDe.

    This code helps me lot...

    Thanks again...

    SK

    ReplyDelete
  160. 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
  161. I want to upload images from a URL. (from another sever)
    what are the changes i have to do...

    thank you!

    ReplyDelete
  162. 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
  163. 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
  164. 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
  165. hi,

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

    ReplyDelete
  166. 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
  167. 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
  168. 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
  169. Thx a lot!!!!!!
    its very useful for me.

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

    ReplyDelete
  171. Just what I needed, Thanks!

    ReplyDelete
  172. 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
  173. Thanks dude nice one :)

    ReplyDelete

mailxengine Youtueb channel
Make in India
X