Jump to content

Image Upload problem


ted_chou12

Recommended Posts

can anyone help me have a look at this script:

<html>
<head>
<title>web.blazonry : PHP : Upload and Resize an Image</title>

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST")
{

$imgfile_name = $_POST['imgfile'];

   /* SUBMITTED INFORMATION - use what you need
    * temporary filename (pointer): $imgfile
    * original filename           : $imgfile_name
    * size of uploaded file       : $imgfile_size
    * mime-type of uploaded file  : $imgfile_type
    */

    /*== upload directory where the file will be stored
         relative to where script is run ==*/
   
   $uploaddir = ".";
   

   /*== get file extension (fn at bottom of script) ==*/
   /*== checks to see if image file, if not do not allow upload ==*/
   $pext = getFileExtension($imgfile_name);
   $pext = strtolower($pext);
   if (($pext != "jpg" or "jpeg" or "bmp" or "png"))
   {
       print "<h1>ERROR</h1>Image Extension Unknown.<br>";
       print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>";
       print "The file you uploaded had the following extension: $pext</p>\n";

       /*== delete uploaded file ==*/
       unlink($imgfile);
       exit();
   }


   //-- RE-SIZING UPLOADED IMAGE

   /*== only resize if the image is larger than 250 x 200 ==*/
   $imgsize = GetImageSize($imgfile);

   /*== check size  0=width, 1=height ==*/
   if (($imgsize[0] > 250) || ($imgsize[1] > 200))
   {
       /*== temp image file -- use "tempnam()" to generate the temp
            file name. This is done so if multiple people access the
           script at once they won't ruin each other's temp file ==*/
       $tmpimg = tempnam("/tmp", "MKUP");

       /*== RESIZE PROCESS
            1. decompress jpeg image to pnm file (a raw image type)
            2. scale pnm image
            3. compress pnm file to jpeg image
       ==*/
       
       /*== Step 1: djpeg decompresses jpeg to pnm ==*/
       system("djpeg $imgfile >$tmpimg");
       

       /*== Steps 2&3: scale image using pnmscale and then
            pipe into cjpeg to output jpeg file ==*/
       system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile");

       /*== remove temp image ==*/
       unlink($tmpimg);

   }

   /*== setup final file location and name ==*/
   /*== change spaces to underscores in filename  ==*/
   $final_filename = str_replace(" ", "_", $imgfile_name);
   $newfile = $uploaddir . "/$final_filename";
   
   /*== do extra security check to prevent malicious abuse==*/
   if (is_uploaded_file($imgfile))
   {

      /*== move file to proper directory ==*/
      if (!copy($imgfile,"$newfile"))
      {
         /*== if an error occurs the file could not
              be written, read or possibly does not exist ==*/
         print "Error Uploading File.";
         exit();
      }
    }

   /*== delete the temporary uploaded file ==*/
   unlink($imgfile);

   
   print("<img src=\"$final_filename\">");

   /*== DO WHATEVER ELSE YOU WANT
        SUCH AS INSERT DATA INTO A DATABASE  ==*/

}
?>


</head>
<body bgcolor="#FFFFFF">

   <h2>Upload and Resize an Image</h2>

   <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="MAX_FILE_SIZE" value="50000">

   <p>Upload Image: <input type="file" name="imgfile"><br>
   <font size="1">Click browse to upload a local file</font><br>
   <br>
   <input type="submit" value="Upload Image">
   </form>

</body>
</html>

<?php
   /*== FUNCTIONS ==*/

   function getFileExtension($str) {

       $i = strrpos($str,".");
       if (!$i) { return ""; }

       $l = strlen($str) - $i;
       $ext = substr($str,$i+1,$l);

       return $ext;

   }
?>

why everytime when I try to upload jpg files it says file extension error?
Link to comment
Share on other sites

in this case, you want $_FILES['imgfile'], not $_POST['imgfile']. you use post to get regular input fields, and $_FILES for files.

a couple of other things.

[code]
<?php
$imgfile = $_FILES['imgfile'];

echo $imgfile['name']; // original filename - NOT $imgfile_name as you have it
echo $imgfile['tmp_name']; // the actual filepath/name of the uploaded file on the server
echo $imgfile['type']; // the MIME type. always good to use this instead/as well as of the file extension
echo $imgfile['error']; // any error messages. 0 = successful upload.
?>
[/code]

[b]edit:[/b] also, its generally better to use [url=http://www.php.net/move_uploaded_file]move_uploaded_file[/url] instead of copy in this case.
[b]edit2[/b]: also:
[code]
<?php
if (($pext != "jpg" or "jpeg" or "bmp" or "png"))

?>
[/code]
should be
[code]
<?php
if (($pext != "jpg" && $pext != "jpeg" && $pext != "bmp" && $pext != "png"))

?>
[/code]



take those points into account in your code, and you should get it fixed.
Link to comment
Share on other sites

<html>
<head>
<title>web.blazonry : PHP : Upload and Resize an Image</title>
[code]
<?php

if ($_SERVER['REQUEST_METHOD'] == "POST")
{

$imgfile = $_FILES['imgfile'];

echo $imgfile['name']; // original filename - NOT $imgfile_name as you have it
echo $imgfile['tmp_name']; // the actual filepath/name of the uploaded file on the server
echo $imgfile['type']; // the MIME type. always good to use this instead/as well as of the file extension
echo $imgfile['error']; // any error messages. 0 = successful upload.

    /* SUBMITTED INFORMATION - use what you need
    * temporary filename (pointer): $imgfile
    * original filename          : $imgfile_name
    * size of uploaded file      : $imgfile_size
    * mime-type of uploaded file  : $imgfile_type
    */

    /*== upload directory where the file will be stored
          relative to where script is run ==*/
   
    $uploaddir = ".";
   

    /*== get file extension (fn at bottom of script) ==*/
    /*== checks to see if image file, if not do not allow upload ==*/
    $pext = getFileExtension($imgfile_name);
    $pext = strtolower($pext);
    if (($pext != "jpg" && $pext != "jpeg" && $pext != "bmp" && $pext != "png"))
    {
        print "<h1>ERROR</h1>Image Extension Unknown.<br>";
        print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>";
        print "The file you uploaded had the following extension: $pext</p>\n";

        /*== delete uploaded file ==*/
        unlink($imgfile);
        exit();
    }


    //-- RE-SIZING UPLOADED IMAGE

    /*== only resize if the image is larger than 250 x 200 ==*/
    $imgsize = GetImageSize($imgfile);

    /*== check size  0=width, 1=height ==*/
    if (($imgsize[0] > 250) || ($imgsize[1] > 200))
    {
        /*== temp image file -- use "tempnam()" to generate the temp
            file name. This is done so if multiple people access the
            script at once they won't ruin each other's temp file ==*/
        $tmpimg = tempnam("/tmp", "MKUP");

        /*== RESIZE PROCESS
            1. decompress jpeg image to pnm file (a raw image type)
            2. scale pnm image
            3. compress pnm file to jpeg image
        ==*/
       
        /*== Step 1: djpeg decompresses jpeg to pnm ==*/
        system("djpeg $imgfile >$tmpimg");
       

        /*== Steps 2&3: scale image using pnmscale and then
            pipe into cjpeg to output jpeg file ==*/
        system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile");

        /*== remove temp image ==*/
        unlink($tmpimg);

    }

    /*== setup final file location and name ==*/
    /*== change spaces to underscores in filename  ==*/
    $final_filename = str_replace(" ", "_", $imgfile_name);
    $newfile = $uploaddir . "/$final_filename";
   
    /*== do extra security check to prevent malicious abuse==*/
    if (is_uploaded_file($imgfile))
    {

      /*== move file to proper directory ==*/
      if (!move_uploaded_file($imgfile,"$newfile"))
      {
          /*== if an error occurs the file could not
              be written, read or possibly does not exist ==*/
          print "Error Uploading File.";
          exit();
      }
    }

    /*== delete the temporary uploaded file ==*/
    unlink($imgfile);

   
    print("<img src=\"$final_filename\">");

    /*== DO WHATEVER ELSE YOU WANT
        SUCH AS INSERT DATA INTO A DATABASE  ==*/

}
?>


</head>
<body bgcolor="#FFFFFF">

    <h2>Upload and Resize an Image</h2>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="50000">

    <p>Upload Image: <input type="file" name="imgfile"><br>
    <font size="1">Click browse to upload a local file</font><br>
    <br>
    <input type="submit" value="Upload Image">
    </form>

</body>
</html>

<?php
    /*== FUNCTIONS ==*/

    function getFileExtension($str) {

        $i = strrpos($str,".");
        if (!$i) { return ""; }

        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);

        return $ext;

    }
?>
[/code]
Link to comment
Share on other sites

no. the code i posted was to give you an example - ie, to use $imgfile['name'], not $imgfile_name. the general idea of the code would work, but a few mistakes like that will stop it in its tracks. either way, the fact you posted my example code (the 'echo's) and looking  at the output shows that the file is being uploaded correctly.

one change for example:
[code]
<?php
    $pext = getFileExtension($imgfile['name']);

?>
[/code]

you need to make those changes throughout the code in the relevent places. substitude your references to imgfile (imgfile_name, etc) with the ones i gave in my example and you should be a little closer to getting it working.
cheers
Mark
Link to comment
Share on other sites

i dont normally do this, but:

[code]
<html>
<head>
<title>web.blazonry : PHP : Upload and Resize an Image</title>

<?php

if ($_SERVER['REQUEST_METHOD'] == "POST")
{

$imgfile = $_FILES['imgfile'];

    /* SUBMITTED INFORMATION - use what you need
     * temporary filename (pointer): $imgfile
     * original filename           : $imgfile_name
     * size of uploaded file       : $imgfile_size
     * mime-type of uploaded file  : $imgfile_type
     */

     /*== upload directory where the file will be stored
          relative to where script is run ==*/
   
    $uploaddir = ".";
   

    /*== get file extension (fn at bottom of script) ==*/
    /*== checks to see if image file, if not do not allow upload ==*/
    $pext = getFileExtension($imgfile['name']);
    $pext = strtolower($pext);
    if (($pext != "jpg" && $pext != "jpeg" && $pext != "bmp" && $pext != "png"))
    {
        print "<h1>ERROR</h1>Image Extension Unknown.<br>";
        print "<p>Please upload only a JPEG image with the extension .jpg or .jpeg ONLY<br><br>";
        print "The file you uploaded had the following extension: $pext</p>\n";

        /*== delete uploaded file ==*/
        unlink($imgfile['tmp_name']);
        exit();
    }


    //-- RE-SIZING UPLOADED IMAGE

    /*== only resize if the image is larger than 250 x 200 ==*/
    $imgsize = GetImageSize($imgfile['tmp_file']);

    /*== check size  0=width, 1=height ==*/
    if (($imgsize[0] > 250) || ($imgsize[1] > 200))
    {
        /*== temp image file -- use "tempnam()" to generate the temp
             file name. This is done so if multiple people access the
            script at once they won't ruin each other's temp file ==*/
        $tmpimg = tempnam("/tmp", "MKUP");

        /*== RESIZE PROCESS
             1. decompress jpeg image to pnm file (a raw image type)
             2. scale pnm image
             3. compress pnm file to jpeg image
        ==*/
       
        /*== Step 1: djpeg decompresses jpeg to pnm ==*/
        system("djpeg {$imgfile['tmp_name']} >$tmpimg");
       

        /*== Steps 2&3: scale image using pnmscale and then
             pipe into cjpeg to output jpeg file ==*/
        system("pnmscale -xy 250 200 $tmpimg | cjpeg -smoo 10 -qual 50 >$imgfile");

        /*== remove temp image ==*/
        unlink($tmpimg['tmp_name']);

    }

    /*== setup final file location and name ==*/
    /*== change spaces to underscores in filename  ==*/
    $final_filename = str_replace(" ", "_", $imgfile['name']);
    $newfile = $uploaddir . "/$final_filename";
   
    /*== do extra security check to prevent malicious abuse==*/
    if (is_uploaded_file($imgfile['tmp_name']))
    {

       /*== move file to proper directory ==*/
       if (!move_uploaded_file($imgfile['tmp_name'],"$newfile"))
       {
          /*== if an error occurs the file could not
               be written, read or possibly does not exist ==*/
          print "Error Uploading File.";
          exit();
       }
     }

    /*== delete the temporary uploaded file ==*/
    unlink($imgfile['tmp_name']);

   
    print("<img src=\"$final_filename\">");

    /*== DO WHATEVER ELSE YOU WANT
         SUCH AS INSERT DATA INTO A DATABASE  ==*/

}
?>


</head>
<body bgcolor="#FFFFFF">

    <h2>Upload and Resize an Image</h2>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="50000">

    <p>Upload Image: <input type="file" name="imgfile"><br>
    <font size="1">Click browse to upload a local file</font><br>
    <br>
    <input type="submit" value="Upload Image">
    </form>

</body>
</html>

<?php
    /*== FUNCTIONS ==*/

    function getFileExtension($str) {

        $i = strrpos($str,".");
        if (!$i) { return ""; }

        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);

        return $ext;

    }
?>
[/code]

there are a few things i dont understand in there, so havent fixed/changed it, but that should set you on your way. PLEASE PLEASE PLEASE dont just copy the code and hope it'll work. look at the changes i made, try and suss out why i made them and whats going on, and see how you go.

Cheers
Mark
Link to comment
Share on other sites

c'mon lad - do yourself a favour. read back over the replies. look at whats what and what goes where. you could do a lot worse than try getting your head around what you've already written and trying to understand it first, before moving on.
which begs the question - i mentioned NOT just copying and pasting it and just assuming it'll work, but instead doing what you need to do, getting to grips with it and understanding it, yet only a few mins later....

i posted that as i was in a good mood. now do yourself a favour and have a think about the new problem yourself, try it out, and post back if you have any specific problems. getting your code totally written/modified for you for free is pretty rare.

good luck
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.