Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    Banned
    Join Date
    Mar 2007
    Posts
    1,523
    Thanks
    116
    Thanked 0 Times in 0 Posts

    Question File upload, create a thumbnail too an place into thumbnail folder

    My current code uploads images to the gallery folder, I would like to also get the image uploaded and create a thumbnail from it too but place in the thumbnails folder and update datebase too

    thanks

    PHP Code:
    $FileName uniqid() .'-' .$_FILES['file']['name'];  
    if (((
    $_FILES["file"]["type"] == "image/gif")
    || (
    $_FILES["file"]["type"] == "image/jpeg")
    || (
    $_FILES["file"]["type"] == "image/pjpeg"))
    && (
    $_FILES["file"]["size"] < 20000))
      {
      if (
    $_FILES["file"]["error"] > 0)
        {
        echo 
    "Return Code: " $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo 
    "Upload: " $FileName "<br />";
        echo 
    "Type: " $_FILES["file"]["type"] . "<br />";
        echo 
    "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo 
    "Temp file: " $_FILES["file"]["tmp_name"] . "<br />";

        
        if (
    file_exists("gallery/" $FileName))
          {
          echo 
    $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          
    move_uploaded_file($_FILES["file"]["tmp_name"],
          
    "gallery/" $FileName);
          
          
    // Define $myusername and $mypassword
    $UserID=$_POST['UserID'];
    $PictureName=$_POST['PictureName'];
    $PictureDate=$_POST['PictureDate'];
    $TargetID=$_POST['TargetID'];

    // To protect MySQL injection (more detail about MySQL injection)
    $UserID stripslashes($UserID);
    $PictureName stripslashes($PictureName);
    $PictureDate stripslashes($PictureDate);
    $TargetID stripslashes($TargetID);
    $UserID mysql_real_escape_string($UserID);
    $PictureName mysql_real_escape_string($PictureName);
    $PictureDate mysql_real_escape_string($PictureDate);
    $TargetID mysql_real_escape_string($TargetID);

          
          
    $sql "INSERT INTO rstargetpictures (UserID, FileName, PictureName, PictureDate, TargetID)
    VALUES ('$UserID', '$FileName', '$PictureName', '$PictureDate', '$TargetID')"
    ;
    $msg "New booking added";
    $result mysql_query($sql) or die('Error: ' mysql_error() . '<br>SQL: ' $sql);
          
          echo 
    "Stored in: " "gallery/" $FileName;
          }
        }
      }
    else
      {
      echo 
    "Invalid file";
      } 
    Last edited by Inigoesdr; 11-11-2011 at 05:33 PM.

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,472
    Thanks
    8
    Thanked 1,085 Times in 1,076 Posts
    Here you go ... see script below.

    Make a subdirectory called /gallery/thumbs/
    That is where the thumbnail gets saved.
    The filename will be the same as the fullsize, but in the /thumbs/ directory.

    I added a function to make+save the thumbs, and set the size to 100 (you can change that).
    I'm not the author of this function ... I just use it all the time because it works so good.
    That resize function is a nice one to save in your "snippets" folder for use on other scripts.


    PHP Code:
    <?php

    $FileName 
    uniqid() .'-' .$_FILES['file']['name'];  
    if (((
    $_FILES["file"]["type"] == "image/gif")
    || (
    $_FILES["file"]["type"] == "image/jpeg")
    || (
    $_FILES["file"]["type"] == "image/pjpeg"))
    && (
    $_FILES["file"]["size"] < 20000))
      {
      if (
    $_FILES["file"]["error"] > 0)
        {
        echo 
    "Return Code: " $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo 
    "Upload: " $FileName "<br />";
        echo 
    "Type: " $_FILES["file"]["type"] . "<br />";
        echo 
    "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo 
    "Temp file: " $_FILES["file"]["tmp_name"] . "<br />";

        
        if (
    file_exists("gallery/" $FileName))
          {
          echo 
    $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          
    move_uploaded_file($_FILES["file"]["tmp_name"],
          
    "gallery/" $FileName);

        
    // Resize the original file to a thumbnail
        // Maximum width of 100.
        // Saved with the same filename, but in the "thumbs" directory.
          
    resize("gallery/".$FileName100"thumbs/".$FileName);
          
          
    // Define $myusername and $mypassword
    $UserID=$_POST['UserID'];
    $PictureName=$_POST['PictureName'];
    $PictureDate=$_POST['PictureDate'];
    $TargetID=$_POST['TargetID'];

    // To protect MySQL injection (more detail about MySQL injection)
    $UserID stripslashes($UserID);
    $PictureName stripslashes($PictureName);
    $PictureDate stripslashes($PictureDate);
    $TargetID stripslashes($TargetID);
    $UserID mysql_real_escape_string($UserID);
    $PictureName mysql_real_escape_string($PictureName);
    $PictureDate mysql_real_escape_string($PictureDate);
    $TargetID mysql_real_escape_string($TargetID);

          
          
    $sql "INSERT INTO rstargetpictures (UserID, FileName, PictureName, PictureDate, TargetID)
    VALUES ('$UserID', '$FileName', '$PictureName', '$PictureDate', '$TargetID')"
    ;
    $msg "New booking added";
    $result mysql_query($sql) or die('Error: ' mysql_error() . '<br>SQL: ' $sql);
          
          echo 
    "Stored in: " "gallery/" $FileName;
          }
        }
      }
    else
      {
      echo 
    "Invalid file";
      }  

    function 
    resize($img$thumb_width$newfilename){
      
    $max_width=$thumb_width;

        
    //Check if GD extension is loaded
        
    if (!extension_loaded('gd') && !extension_loaded('gd2')){
            
    trigger_error("GD is not loaded"E_USER_WARNING);
            return 
    false;
        }

        
    //Get Image size info
        
    list($width_orig$height_orig$image_type) = getimagesize($img);
       
        switch (
    $image_type){
            case 
    1$im imagecreatefromgif($img); break;
            case 
    2$im imagecreatefromjpeg($img);  break;
            case 
    3$im imagecreatefrompng($img); break;
            default:  
    trigger_error('Unsupported filetype!'E_USER_WARNING);  break;
        }
       
        
    /*** calculate the aspect ratio ***/
        
    $aspect_ratio = (float) $height_orig $width_orig;

        
    /*** calulate the thumbnail width based on the height ***/
        
    $thumb_height round($thumb_width $aspect_ratio);
       

        while(
    $thumb_height>$max_width){
            
    $thumb_width-=10;
            
    $thumb_height round($thumb_width $aspect_ratio);
        }
       
        
    $newImg imagecreatetruecolor($thumb_width$thumb_height);
       
        
    /* Check if this image is PNG or GIF, then set if Transparent*/ 
        
    if(($image_type == 1) OR ($image_type==3))
        {
            
    imagealphablending($newImgfalse);
            
    imagesavealpha($newImg,true);
            
    $transparent imagecolorallocatealpha($newImg255255255127);
            
    imagefilledrectangle($newImg00$thumb_width$thumb_height$transparent);
        }
        
    imagecopyresampled($newImg$im0000$thumb_width$thumb_height$width_orig$height_orig);
       
        
    //Generate the file, and rename it to $newfilename
        
    switch ($image_type){
            case 
    1imagegif($newImg,$newfilename); break;
            case 
    2imagejpeg($newImg,$newfilename);  break;
            case 
    3imagepng($newImg,$newfilename); break;
            default:  
    trigger_error('Failed resize image!'E_USER_WARNING);  break;
        }
     
        return 
    $newfilename;
    }
    ?>


    EDIT:
    Also note ... looking at these lines of the script ...

    move_uploaded_file($_FILES["file"]["tmp_name"],
    "gallery/" . $FileName);

    // Resize the original file to a thumbnail
    // Maximum width of 100.
    // Saved with the same filename, but in the "thumbs" directory.
    resize("gallery/".$FileName, 100, "thumbs/".$FileName);


    You might have a situation where your script does the move and tries to resize
    without finishing the move instruction.

    If that "timing issue" occurs, simply put the move command in an "if" statement.
    The script must complete the move to determine "true" or "false", thus finishing the move.

    Like this:

    if(move_uploaded_file($_FILES["file"]["tmp_name"],
    "gallery/" . $FileName)){
    // let it finish the move
    }

    // Resize the original file to a thumbnail
    // Maximum width of 100.
    // Saved with the same filename, but in the "thumbs" directory.
    resize("gallery/".$FileName, 100, "thumbs/".$FileName);





    .
    Last edited by mlseim; 11-11-2011 at 06:36 PM.

  • #3
    Banned
    Join Date
    Mar 2007
    Posts
    1,523
    Thanks
    116
    Thanked 0 Times in 0 Posts

    Question

    Thanks,

    I now get Invalid file displayed?!

    here is my code

    PHP Code:
    <?php
    session_start
    ();
    mysql_connect("xxx""xxx""xxx") or die(mysql_error());
    mysql_select_db("xxx") or die(mysql_error());
    $FileName uniqid() .'-' .$_FILES['file']['name'];  
    if (((
    $_FILES["file"]["type"] == "image/gif")
    || (
    $_FILES["file"]["type"] == "image/jpeg")
    || (
    $_FILES["file"]["type"] == "image/pjpeg"))
    && (
    $_FILES["file"]["size"] < 20000))
      {
      if (
    $_FILES["file"]["error"] > 0)
        {
        echo 
    "Return Code: " $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo 
    "Upload: " $FileName "<br />";
        
        if (
    file_exists("gallery/" $FileName))
          {
          echo 
    $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          
    move_uploaded_file($_FILES["file"]["tmp_name"],
          
    "gallery/" $FileName);

        
    // Resize the original file to a thumbnail
        // Maximum width of 100.
        // Saved with the same filename, but in the "thumbs" directory.
          
    resize("gallery/".$FileName100"thumbs/".$FileName);
          
          
    // Define $myusername and $mypassword
    $UserID=$_POST['UserID'];
    $PictureName=$_POST['PictureName'];
    $PictureDate=$_POST['PictureDate'];
    $TargetID=$_POST['TargetID'];

    // To protect MySQL injection (more detail about MySQL injection)
    $UserID stripslashes($UserID);
    $PictureName stripslashes($PictureName);
    $PictureDate stripslashes($PictureDate);
    $TargetID stripslashes($TargetID);
    $UserID mysql_real_escape_string($UserID);
    $PictureName mysql_real_escape_string($PictureName);
    $PictureDate mysql_real_escape_string($PictureDate);
    $TargetID mysql_real_escape_string($TargetID);

          
          
    $sql "INSERT INTO rstargetpictures (UserID, FileName, PictureName, PictureDate, TargetID)
    VALUES ('$UserID', '$FileName', '$PictureName', '$PictureDate', '$TargetID')"
    ;
    $msg "New booking added";
    $result mysql_query($sql) or die('Error: ' mysql_error() . '<br>SQL: ' $sql);
          
          echo 
    "Stored in: " "gallery/" $FileName;
          }
        }
      }
    else
      {
      echo 
    "Invalid file";
      }  

    function 
    resize($img$thumb_width$newfilename){
      
    $max_width=$thumb_width;

        
    //Check if GD extension is loaded
        
    if (!extension_loaded('gd') && !extension_loaded('gd2')){
            
    trigger_error("GD is not loaded"E_USER_WARNING);
            return 
    false;
        }

        
    //Get Image size info
        
    list($width_orig$height_orig$image_type) = getimagesize($img);
       
        switch (
    $image_type){
            case 
    1$im imagecreatefromgif($img); break;
            case 
    2$im imagecreatefromjpeg($img);  break;
            case 
    3$im imagecreatefrompng($img); break;
            default:  
    trigger_error('Unsupported filetype!'E_USER_WARNING);  break;
        }
       
        
    /*** calculate the aspect ratio ***/
        
    $aspect_ratio = (float) $height_orig $width_orig;

        
    /*** calulate the thumbnail width based on the height ***/
        
    $thumb_height round($thumb_width $aspect_ratio);
       

        while(
    $thumb_height>$max_width){
            
    $thumb_width-=10;
            
    $thumb_height round($thumb_width $aspect_ratio);
        }
       
        
    $newImg imagecreatetruecolor($thumb_width$thumb_height);
       
        
    /* Check if this image is PNG or GIF, then set if Transparent*/ 
        
    if(($image_type == 1) OR ($image_type==3))
        {
            
    imagealphablending($newImgfalse);
            
    imagesavealpha($newImg,true);
            
    $transparent imagecolorallocatealpha($newImg255255255127);
            
    imagefilledrectangle($newImg00$thumb_width$thumb_height$transparent);
        }
        
    imagecopyresampled($newImg$im0000$thumb_width$thumb_height$width_orig$height_orig);
       
        
    //Generate the file, and rename it to $newfilename
        
    switch ($image_type){
            case 
    1imagegif($newImg,$newfilename); break;
            case 
    2imagejpeg($newImg,$newfilename);  break;
            case 
    3imagepng($newImg,$newfilename); break;
            default:  
    trigger_error('Failed resize image!'E_USER_WARNING);  break;
        }
     
        return 
    $newfilename;
    }
    ?>
    Last edited by jarv; 11-11-2011 at 10:33 PM.

  • #4
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,472
    Thanks
    8
    Thanked 1,085 Times in 1,076 Posts
    Did you create a directory called "thumbs"?

    Oh, and I use a shared webhost online ...
    You're using your own server? Are the / the wrong way ? /\/\/\ ??

  • #5
    Banned
    Join Date
    Mar 2007
    Posts
    1,523
    Thanks
    116
    Thanked 0 Times in 0 Posts
    no no, it works but only with certain .jpg files?!

  • #6
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,313
    Thanks
    58
    Thanked 525 Times in 512 Posts
    Blog Entries
    5
    As suggested to you earlier, have you tried debugging yet?
    See my new CodingForums Blog: http://www.codingforums.com/blogs/tangoforce/

    Many useful explanations and tips including: Cannot modify headers - already sent, The IE if (isset($_POST['submit'])) bug explained, unexpected T_CONSTANT_ENCAPSED_STRING, debugging tips and much more!

  • #7
    Banned
    Join Date
    Mar 2007
    Posts
    1,523
    Thanks
    116
    Thanked 0 Times in 0 Posts
    hmm, how to debug that though?!

  • #8
    Senior Coder
    Join Date
    Jul 2009
    Location
    South Yorkshire, England
    Posts
    2,318
    Thanks
    6
    Thanked 304 Times in 303 Posts
    echo.

  • #9
    Banned
    Join Date
    Mar 2007
    Posts
    1,523
    Thanks
    116
    Thanked 0 Times in 0 Posts
    yeah, echo what though?! it's a JPG file... surely it should upload?!

  • #10
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,313
    Thanks
    58
    Thanked 525 Times in 512 Posts
    Blog Entries
    5
    Quote Originally Posted by jarv View Post
    yeah, echo what though?! it's a JPG file... surely it should upload?!
    Without a doubt the file HAS uploaded - the browser will do that automatically. The problem happens with the move_uploaded_file() function. If you don't get your filepaths correct then as soon as the script terminates, the files are deleted from the temp directory automatically by php.

    Jarv, if you want to be a programmer, you MUST learn to debug your code. This is one of the very fundamentals of programming in any language. You can't just find bits of code and put them together and then get everyone else to fix them (well you can but eventually you will get let down).

    You must learn to debug. Your post above where you say "hmm, how to debug that though?!" is the first sign of progress and its a good one. In all the months you've been here you're finally asking how to debug and thats good - very good.

    Firstly you need to do this somewhere in your code to determine what the $_FILES array contains (such as temp names etc):

    var_dump($_FILES);

    That should give you the basics of what you need to know. The rest is pretty much the same thing- printing out variables to be sure that they contain the correct values that you think they should. Thats basically all that debugging is - printing values to check things are as they should.

    When it comes to files, sometimes you need to run additional code - using if(file_exists()) and if (is_dir()) etc and then print out your yes/no values accordingly. You do it like this:

    PHP Code:
        if (file_exists("gallery/" $FileName))
          {
          echo 
    $_FILES["file"]["name"] . " already exists. ";
          } 
    That code came from YOUR code. THAT is how you debug but sometimes you have to debug every single line of code until you find the fault. Yes that can be hard work but it can save you the amount of time that you waste waiting for us to help you. You could fix it in an hour or two or wait 8-9 hours for us to help you. What is best?

    You can also log things to a database for scripts that can't output anything and there are ways of doing that using var_export($Var, true); instead of var_dump().

    I promise you jarv, once you've learnt the basics of debugging it gets a LOT easier
    Last edited by tangoforce; 11-12-2011 at 01:38 AM.
    See my new CodingForums Blog: http://www.codingforums.com/blogs/tangoforce/

    Many useful explanations and tips including: Cannot modify headers - already sent, The IE if (isset($_POST['submit'])) bug explained, unexpected T_CONSTANT_ENCAPSED_STRING, debugging tips and much more!

  • #11
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,472
    Thanks
    8
    Thanked 1,085 Times in 1,076 Posts
    Maybe you have differences in the extensions?

    jpeg
    jpg
    JPG
    Jpg
    Jpeg

    those are all different, case-sensitive.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •