Jump to content

Uploading & Thumbnailing Images


MoFish

Recommended Posts

hello everyone.

i've hunted high and low for a solution, and have come accross this website hoping that someone could help me shine some light on my problem. I am trying to create a upload script which will upload the originial image to a directory on my server aswell as a thumbnail with the dimensions of 150px x 150px.

I have tryed coding it, but have run accross alot of problems. Sometimes the script actually works, and uploads the image fine. othertimes, it doesnt upload anything at all to the server, which im not sure why.

would anyone mind reading over my code, to see if its okay? and see if any errors jump out at them? im not the greatest at php, so please go easy on me if its a bit sloppy, im curently in the learning cycle.

thanks alot, mofish.

[code]

<?php

// if the session is not set then they aint logged in
// so lets display a message to them telling them to login first

if (!isset($_SESSION['member'])) {
    echo "<div class='error-style'>Error: Please Login</div>";

// if it is set, then they are actually logged in
// so lets proceed

} else {
        
//if upload is set then perform the following actions

if (isset($_POST['upload'])){

// Get the details of file the user is uploading
// some of these are prebuild php functions, such as size etc
// they are very usefull.
$filename = $_FILES['imagefile']['name'];
$temporary_name = $_FILES['imagefile']['tmp_name'];
$mimetype = $_FILES['imagefile']['type'];
$filesize = $_FILES['imagefile']['size'];
$member = $_SESSION['member'];
$selectedcategory = $_POST['selectedcategory'];

// based on the type of file, we are going to check what type of file it is
// the $ mime variable above was used for type, so we will use this to check
// a prebuild php function imagecreatefrom will be used to create the images.

switch($mimetype) {

// if its a jpg file, then use the image create from jpeg function
// i used upper and loweclass jpg checks, because both are common.

    case "image/jpg":
    case "image/jpeg":
    case "image/JPG":
    case "image/JPEG":
        $i = imagecreatefromjpeg($temporary_name);
        break;
        
// if its a gif file, then use the image create from gif function
// i used upper and loweclass gif checks, because both are common.
    
    case "image/gif":
    case "image/GIF":
        $i = imagecreatefromgif($temporary_name);
        break;
    
// if its a png file, then use the image create from png function
// i used upper and loweclass png checks, because both are common.

    case "image/png":
    case "image/PNG":
        $i = imagecreatefrompng($temporary_name);
        break;
}

// remove the temporary uploaded file, we dont need this now.

unlink($temporary_name);

// lets move a copy of the original to the gallery folder
// this will be full size

imagejpeg($i,"gallery/" . $filename ,80);

// now we are going to thumb nail this image we just uploaded
// we can specify the dimensions to use below.

$dest_x = 130;
$dest_y = 130;

// now we need to check if the original is bigger than the thumbnail dimensions
// it should be, but someone may have uploaded small image.

if (imagesx($i) > $dest_x or imagesy($i) > $dest_y) {
  
    // we now need to check if the width of the original image is bigger
    // then the height. to do this i found a solution on phpguide.com
    
    if (imagesx($i) >= imagesy($i)) {
        $thumb_x = $dest_x;
        $thumb_y = imagesy($i)*($dest_x/imagesx($i));
    } else {
        $thumb_x = imagesx($i)*($dest_y/imagesy($i));
        $thumb_y = $dest_y;
    }
    
//if the image is already small then we can just use that for the thumbnail

} else {

    // use the original dimensions uploaded from the user
    // since its already small we can do this happily.
    
    $thumb_x = imagesx($i);
    $thumb_y = imagesy($i);

}

// lets create the image now we have done the scale checking.
// the below code will generate the thumbnail using our checking above.

$thumb = imagecreatetruecolor($thumb_x,$thumb_y);

// copy the original image data to it using resampling

imagecopyresampled($thumb, $i ,0, 0, 0, 0, $thumb_x, $thumb_y, imagesx($i), imagesy($i));

// save the thumbnail to the gallery directory.
// I added the tn_ before the image so we can identfy which is a thumbnail

imagejpeg($thumb, "gallery/tn_" . $filename, 80);

// next lets set the query for adding this information to our gallery database
// this will be used to retreive the information for thw gallery later

$query = "insert into `gallery` (`image`, `author`, `category`) values ('$filename', '$member', '$selectedcategory')";

// if the query is performed successfully then lets tell the user it worked fine.

if (mysql_query($query)){
    echo "Successfully added <b>" . $filename . " </b>to the Gallery.\n";

// if we had a problem uploading, lets tell the user, and display a message

} else {

    echo "<div class='error-style'>Error Adding Image</div>";

}

// if the user upload wasnt set, then lets display the form,
// because they obviously want to upload something.

}else{

// display form allowing user to upload

?>
<div class="navigation-heading">Upload Image</div>
    <div class="link-heading">
    <form action="index.php?page=upload" method="POST" enctype="multipart/form-data">
        
        <div><b>1</b>) - Please Choose A Category To Upload The Image<br/><br/></div>
            
            <?
            $result = mysql_query("SELECT * FROM `category`");
            $category = $myrow["category"];
            
            echo '<select name="selectedcategory">';
            while ($myrow = mysql_fetch_array($result)) {
            $opt = $myrow['category'];
            echo "<option>$opt</option> ";
            }
            echo '</select>';
            ?>
            <input name="Category" type="button" onclick="location.href="index.php?page=addcategory"" value="Add Category" />
        
        <div><p><b>2</b>) - Please Select The Image To Upload</p></div>
        
        <input type="hidden" name="MAX_FILE_SIZE" value="10485760" class="loginbox">
            <input type="file" name="imagefile" class="loginbox">
        <input type="submit" name="upload" value="Upload Image" class="loginbox"></p>
        
        <div><p><b>3</b>) - Please Be Patient While Your Image Uploads</p></div>
    </form>
    <div style="background-color:#D7FCFF; border:1px dotted black">Supported File Formats:
        <ul>
             <li>JPG</li>
             <li>JPEG</li>
            <li>GIF</li>
              <li>PNG </li>
        </ul>
    </div>
    </div>
<?
}
}
?>
[/code]
Link to comment
Share on other sites

I have glanced over your code, but have not read it in any depth. You mentioned that sometimes it works, and sometimes it doesn't. Have you tried uploading the same file over and over, or, have you tried this with a selection of different images? If you're using different images, what is it about those images that is different to the images that work? The answer to that may narrow down the problem area in your code.

Heres a tip for you too, it could prevent you from typing more than you have to in the future:
[code]/*Force $mimetype to all lowercase with strtolower() so you dont have to match against both upper and lowercase versions of the string.*/
switch(strtolower($mimetype)) {
    case "image/jpg":
    case "image/jpeg":
        $i = imagecreatefromjpeg($temporary_name);
        break;
    case "image/gif":
        $i = imagecreatefromgif($temporary_name);
        break;
    case "image/png":
        $i = imagecreatefrompng($temporary_name);
        break;
}[/code]
Link to comment
Share on other sites

hello, i have been using a range of images, some work some dont. I have tryed a selection of images, some big and some small. It just seems to be luck if they work or not, which i find pretty wierd! I get a number of warnings when an image fails to upload. :S

here is a paste bin of my full code, with line numbers and stuff, just so you can see where im at right now. [a href=\"http://mofish.pastebin.com/653810\" target=\"_blank\"]http://mofish.pastebin.com/653810[/a]

[code]
Warning: unlink() [function.unlink]: No such file or directory in /home/mo/public_html/pages/upload.php on line 48

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 53

Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 53

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 64

Warning: imagesx(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 64

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 64

Warning: imagesy(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 64

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 84

Warning: imagesx(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 84

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 85

Warning: imagesy(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 85

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/mo/public_html/pages/upload.php on line 92

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 96

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 96

Warning: imagesx(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 96

Notice: Undefined variable: i in /home/mo/public_html/pages/upload.php on line 96

Warning: imagesy(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 96

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 96

Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/mo/public_html/pages/upload.php on line 101
Successfully added crystalllll.jpg to the Gallery.
[/code]

when one is successfull it simply prints.

[code]
Successfully added crystalllll.jpg to the Gallery.
[/code]

you can check out my site, and try uploading for yourself. maybe you can identify whats going wrong because i cant :( [a href=\"http://mo.dotgeek.org/\" target=\"_blank\"]CLICK HERE[/a]

you will need to login to upload, you can use the following information or register.
username: [b]admin[/b]
password: [b]admin[/b]

thanks, mofish
Link to comment
Share on other sites

You're always assuming that the file uploaded ok. You really should check to see if there was an error uploading the file:
[code]<?php
  if ($_FILES['imagefile']['error'] != 0)
  switch($_FILES['imagefile']['error']){
  case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
     echo "The file you are trying to upload is too big.";
     break;
   case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
     echo "The file you are trying to upload is too big.";
     break;
   case 3: //uploaded file was only partially uploaded
     echo "The file you are trying upload was only partially uploaded.";
     break;
   case 4: //no file was uploaded
     echo "You must select an image for upload.";
     break;
   default: //a default error, just in case!  :)
     echo "There was a problem with your upload.";
     break;
} else { // do the rest of your code
?>[/code]

Ken
Link to comment
Share on other sites

[!--quoteo(post=363742:date=Apr 11 2006, 01:08 PM:name=kenrbnsn)--][div class=\'quotetop\']QUOTE(kenrbnsn @ Apr 11 2006, 01:08 PM) [snapback]363742[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Do it after this line:
[code]<?php if (isset($_POST['upload'])){ ?>[/code]

Ken
[/quote]


right, seems to be working, its been narrowed down to the image being too big in the ini file? I will try a few more checks on smaller images, and see whats going on here.

thanks for all the help so far.
Link to comment
Share on other sites

I really cant figure this out at all. I have managed to successfully upload an image, and my friend sitting in his house, has tryed the exact same image, and is getting the load of notice errors as posted above.

when it fails, its not actually uploading the image to the server at all. no image is there, its somehow skipping it and going onto the adding details to the database part.

[!--coloro:#000099--][span style=\"color:#000099\"][!--/coloro--]-->>[!--colorc--][/span][!--/colorc--][a href=\"http://mo.pastebin.com/654602\" target=\"_blank\"]here[/a] is my exact upload.php code as it stands, with the error checking as posted above. can anyone think of any ways i can adapt this, so it only adds to the database if its successfull? because right now, its adding if its successfull or not, which is causing some problems i guess.

would anyone mind registering, or logging into my site, username: admin, password: admin. and try adding some random images? it doesnt matter which catagory, i can sort it all out once its working. it seems to work on my pc and not on others? I dont get it at all.

[!--coloro:#000099--][span style=\"color:#000099\"][!--/coloro--]-->>[!--colorc--][/span][!--/colorc--][a href=\"http://mo.dotgeek.org/\" target=\"_blank\"]here is my website[/a]

can anyone see any problems in my code? been looking over the same code for about 4 days and its driving me mad, because it has no real error, its totally random as it seems.

Thanks Again, MoFish
Link to comment
Share on other sites

how could i add some validation to check the file has actually been sucessfully uploaded, before adding the information to the database? when it fails, its skipping the upload section, which is within the first few lines, so im guessing something here is going wrong.

upload.php

[code]
<?php

// if the session is not set then they aint logged in
// so lets display a message to them telling them to login first

if (!isset($_SESSION['member'])) {
    echo "<div class='error-style'>Error: Please Login</div>";

// if it is set, then they are actually logged in
// so lets proceed

} else {
        
//if upload is set then perform the following actions

if (isset($_POST['upload'])){

// Get the details of file the user is uploading
// some of these are prebuild php functions, such as size etc
// they are very usefull.
$filename = $_FILES['imagefile']['name'];
$temporary_name = $_FILES['imagefile']['tmp_name'];
$mimetype = $_FILES['imagefile']['type'];
$filesize = $_FILES['imagefile']['size'];
$member = $_SESSION['member'];
$selectedcategory = $_POST['selectedcategory'];

if ($_FILES['imagefile']['error'] != 0)
  switch($_FILES['imagefile']['error']){
  case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
     echo "The file you are trying to upload is too big.";
     break;
   case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
     echo "The file you are trying to upload is too big (max file size).";
     break;
   case 3: //uploaded file was only partially uploaded
     echo "The file you are trying upload was only partially uploaded.";
     break;
   case 4: //no file was uploaded
     echo "You must select an image for upload.";
     break;
   default: //a default error, just in case!  :)
     echo "There was a problem with your upload.";
     break;
} else { // do the rest of your code

// based on the type of file, we are going to check what type of file it is
// the $ mime variable above was used for type, so we will use this to check
// a prebuild php function imagecreatefrom will be used to create the images.

/*Force $mimetype to all lowercase with strtolower() so you dont have to match against both upper and lowercase versions of the string.*/
switch(strtolower($mimetype)) {
    case "image/jpg":
    case "image/jpeg":
        $i = imagecreatefromjpeg($temporary_name);
        break;
    case "image/gif":
        $i = imagecreatefromgif($temporary_name);
        break;
    case "image/png":
        $i = imagecreatefrompng($temporary_name);
        break;
}

// remove the temporary uploaded file, we dont need this now.

unlink($temporary_name);

// lets move a copy of the original to the gallery folder
// this will be full size

imagejpeg($i,"gallery/" . $filename ,80);

// now we are going to thumb nail this image we just uploaded
// we can specify the dimensions to use below.

$dest_x = 130;
$dest_y = 130;

// now we need to check if the original is bigger than the thumbnail dimensions
// it should be, but someone may have uploaded small image.

if (imagesx($i) > $dest_x or imagesy($i) > $dest_y) {
  
    // we now need to check if the width of the original image is bigger
    // then the height. to do this i found a solution on phpguide.com
    
    if (imagesx($i) >= imagesy($i)) {
        $thumb_x = $dest_x;
        $thumb_y = imagesy($i)*($dest_x/imagesx($i));
    } else {
        $thumb_x = imagesx($i)*($dest_y/imagesy($i));
        $thumb_y = $dest_y;
    }
    
//if the image is already small then we can just use that for the thumbnail

} else {

    // use the original dimensions uploaded from the user
    // since its already small we can do this happily.
    
    $thumb_x = imagesx($i);
    $thumb_y = imagesy($i);

}

// lets create the image now we have done the scale checking.
// the below code will generate the thumbnail using our checking above.

$thumb = imagecreatetruecolor($thumb_x,$thumb_y);

// copy the original image data to it using resampling

imagecopyresampled($thumb, $i ,0, 0, 0, 0, $thumb_x, $thumb_y, imagesx($i), imagesy($i));

// save the thumbnail to the gallery directory.
// I added the tn_ before the image so we can identfy which is a thumbnail

imagejpeg($thumb, "gallery/tn_" . $filename, 80);

// next lets set the query for adding this information to our gallery database
// this will be used to retreive the information for thw gallery later

$query = "insert into `gallery` (`image`, `author`, `category`) values ('$filename', '$member', '$selectedcategory')";

// if the query is performed successfully then lets tell the user it worked fine.

if (mysql_query($query)){
    echo "Successfully added <b>" . $filename . " </b>to the Gallery.\n";

// if we had a problem uploading, lets tell the user, and display a message
} else {

    echo "<div class='error-style'>Error Adding Image</div>";

}
}
// if the user upload wasnt set, then lets display the form,
// because they obviously want to upload something.

}else{

// display form allowing user to upload

?>
<div class="navigation-heading">Upload Image</div>
    <div class="link-heading">
    <form action="index.php?page=upload" method="POST" enctype="multipart/form-data">
        
        <div><b>1</b>) - Please Choose A Category To Upload The Image<br/><br/></div>
            
            <?
            $result = mysql_query("SELECT * FROM `category`");
            $category = $myrow["category"];
            
            echo '<select name="selectedcategory">';
            while ($myrow = mysql_fetch_array($result)) {
            $opt = $myrow['category'];
            echo "<option>$opt</option> ";
            }
            echo '</select>';
            ?>
            <input name="Category" type="button" onclick="location.href=&quot;index.php?page=addcategory&quot;" value="Add Category" />
        
        <div><p><b>2</b>) - Please Select The Image To Upload</p></div>
        
        <input type="hidden" name="MAX_FILE_SIZE" value="10485760" class="loginbox">
            <input type="file" name="imagefile" class="loginbox">
        <input type="submit" name="upload" value="Upload Image" class="loginbox"></p>
        
        <div><p><b>3</b>) - Please Be Patient While Your Image Uploads</p></div>
    </form>
    <div style="background-color:#D7FCFF; border:1px dotted black">Supported File Formats:
        <ul>
             <li>JPG</li>
             <li>JPEG</li>
            <li>GIF</li>
              <li>PNG </li>
        </ul>
    </div>
    </div>
<?
}
}
?>
[/code]

Link to comment
Share on other sites

This code I gave you and you incorporated tells you whether the upload worked:
[code]<?php
if ($_FILES['imagefile']['error'] != 0)
  switch($_FILES['imagefile']['error']){
  case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
     echo "The file you are trying to upload is too big.";
     break;
   case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
     echo "The file you are trying to upload is too big (max file size).";
     break;
   case 3: //uploaded file was only partially uploaded
     echo "The file you are trying upload was only partially uploaded.";
     break;
   case 4: //no file was uploaded
     echo "You must select an image for upload.";
     break;
   default: //a default error, just in case!  :)
     echo "There was a problem with your upload.";
     break;
} else ?>[/code]
If the error code is not zero, there was a problem uploading. Make sure you don't do anymore processing if that occurs.

Ken
Link to comment
Share on other sites

does this mean i dont have my closing brackets in the right place?


[code]

<?php

if (!isset($_SESSION['member'])) {
    echo "<div class='error-style'>Error: Please Login</div>";
} else {
    if (isset($_POST['upload'])){

        $filename = $_FILES['imagefile']['name'];
        $temporary_name = $_FILES['imagefile']['tmp_name'];
        $mimetype = $_FILES['imagefile']['type'];
        $filesize = $_FILES['imagefile']['size'];
        $member = $_SESSION['member'];
        $selectedcategory = $_POST['selectedcategory'];

        if ($_FILES['imagefile']['error'] != 0)
              switch($_FILES['imagefile']['error']){
              case 1:
                 echo "The file you are trying to upload is too big.";
             break;
               case 2:
                echo "The file you are trying to upload is too big (max file size).";
             break;
               case 3:
                 echo "The file you are trying upload was only partially uploaded.";
             break;
               case 4:
                 echo "You must select an image for upload.";
             break;
               default:
                 echo "There was a problem with your upload.";
             break;
         
        } else {

            switch(strtolower($mimetype)) {
                case "image/jpg":
                case "image/jpeg":
                    $i = imagecreatefromjpeg($temporary_name);
                   break;
                   case "image/gif":
                        $i = imagecreatefromgif($temporary_name);
                   break;
                case "image/png":
                    $i = imagecreatefrompng($temporary_name);
                   break;
        }

        unlink($temporary_name);

        imagejpeg($i,"gallery/" . $filename ,80);

        $dest_x = 130;
        $dest_y = 130;

        if (imagesx($i) > $dest_x or imagesy($i) > $dest_y) {
        
            if (imagesx($i) >= imagesy($i)) {
                $thumb_x = $dest_x;
                $thumb_y = imagesy($i)*($dest_x/imagesx($i));
               } else {
                $thumb_x = imagesx($i)*($dest_y/imagesy($i));
                $thumb_y = $dest_y;
            }
    
        } else {
    
            $thumb_x = imagesx($i);
            $thumb_y = imagesy($i);

        }
    
    
        $thumb = imagecreatetruecolor($thumb_x,$thumb_y);
        imagecopyresampled($thumb, $i ,0, 0, 0, 0, $thumb_x, $thumb_y, imagesx($i), imagesy($i));
        imagejpeg($thumb, "gallery/tn_" . $filename, 80);

        $query = "insert into `gallery` (`image`, `author`, `category`) values ('$filename', '$member', '$selectedcategory')";
            
            if (mysql_query($query)){
                echo "Successfully added <b>" . $filename . " </b>to the Gallery.\n";
            } else {
                echo "<div class='error-style'>Error Adding Image</div>";

            }
        }
}else{

?>
<div class="navigation-heading">Upload Image</div>
    <div class="link-heading">
    <form action="index.php?page=upload" method="POST" enctype="multipart/form-data">
        
        <div><b>1</b>) - Please Choose A Category To Upload The Image<br/><br/></div>
            
            <?
            $result = mysql_query("SELECT * FROM `category`");
            $category = $myrow["category"];
            
            echo '<select name="selectedcategory">';
            while ($myrow = mysql_fetch_array($result)) {
            $opt = $myrow['category'];
            echo "<option>$opt</option> ";
            }
            echo '</select>';
            ?>
        
        <input name="Category" type="button" onclick="location.href="index.php?page=addcategory"" value="Add Category" />
            <div><p><b>2</b>) - Please Select The Image To Upload</p></div>
        <input type="hidden" name="MAX_FILE_SIZE" value="10485760" class="loginbox">
            <input type="file" name="imagefile" class="loginbox">
        <input type="submit" name="upload" value="Upload Image" class="loginbox"></p>
            <div><p><b>3</b>) - Please Be Patient While Your Image Uploads</p></div>
        </form>
    <div style="background-color:#D7FCFF; border:1px dotted black">Supported File Formats:
        <ul>
             <li>JPG</li>
             <li>JPEG</li>
            <li>GIF</li>
              <li>PNG </li>
        </ul>
    </div>
    </div>
<?
}
}
?>

[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.