SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jan 2012
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Php/MySql image upload. Help needed!

    Hi,
    I'm a php virgin so maybe my problem here is pretty obvious!

    I made a site for a friends pet shop, just somewhere he can put pictures, list stock etc.

    I now need to make him an admin part so he can upload his own photos, update his stock list etc.

    I have been doing this tutorilhttp://onlamp.com/pub/a/onlamp/2002/...b2.html?page=1

    Here is the code

    index.php

    Code:
    <!DOCTYPE HTML PUBLIC 
      "-//W3C//DTD HTML 4.0 Transitional//EN"
      "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
       <title>Browse Upload Files</title>
    </head>
    <body bgcolor="white">
    
    <?php
      include 'db.inc';
      
      $query = "SELECT id, shortName, mimeName FROM files";
    
      if (!($connection = @ mysql_pconnect($hostName, 
                                        $username,
                                        $password)))
         showerror();
    
      if (!mysql_select_db("files", $connection))
         showerror();
            
      if (!($result = @ mysql_query ($query, $connection)))
         showerror();
    ?>
        <h1>Image database</h1> 
    
        <h3>Click <a href="insert.php">here</a> to 
    upload an image.</h3>
    <?php 
    
      if ($row = @ mysql_fetch_array($result))
      {
    ?>
    
        <table>
        <col span="1" align="right">
        <tr>
           <th>Short description</th>
           <th>File type</th>
           <th>Image</th>
    
        </tr>
    <?php
       do 
       {
    ?>
        <tr>
           <td><?php echo "{$row["shortName"]}";?></td>         
           <td><?php echo "{$row["mimeName"]}";?></td>
           <td><?php echo "<img src=\"view.php?file={$row["id"]}\">";?></td>
        </tr>
    <?php
       } while ($row = @ mysql_fetch_array($result));
    ?>
        </table>
    <?php
      } // if mysql_fetch_array()
      else
         echo "<h3>There are no images to display</h3>\n";
    ?>
    </body>
    </html>
    db.inc

    Code:
    <?php
    
    // These are the DBMS credentials
    $hostName = "localhost";
    $username = "name";
    $password = "password";
    
    // Show an error and stop the script
    function showerror()
    {
       if (mysql_error())
          die("Error " . mysql_errno() . " : " . mysql_error());
       else
          die("Could not connect to the DBMS");
    }
    
    // Secure the user data by escaping characters 
    // and shortening the input string
    function clean($input, $maxlength)
    {
      $input = substr($input, 0, $maxlength);
      $input = EscapeShellCmd($input);
      return ($input);
    }
    
    ?>
    insert.php

    Code:
    <?php
      include 'db.inc';
    
      if (empty($short) || empty($userfile))
      {
    ?>
        <!DOCTYPE HTML PUBLIC 
                   "-//W3C//DTD HTML 4.0 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
          <title>Upload an Image File</title>
        </head>
        <body bgcolor="white">
        <form method="post" action="insert.php" enctype="multipart/form-data">
        <h1>Upload an Image File</h1> 
        <h3>Please fill in the details below to upload your file. 
        Fields shown in <font color="red">red</font> are mandatory.</h3>
        <table>
        <col span="1" align="right">
    
        <tr>
           <td><font color="red">Short description:</font></td>
           <td><input type="text" name="short" size=50></td>
        </tr>
    
        <tr>    
           <td><font color="red">File:</font></td>
           <td><input name="userfile" type="file"></td>
        </tr>
    
        <tr>
              <td><input type="submit" value="Submit"></td>
        </tr>
        </table>
        <input type="hidden" name="MAX_FILE_SIZE" value="3000000">
        </form>
        <h3>Click <a href="index.php">here</a> to browse the images instead.</h3>
        </body>
        </html>
    <?php    
      }
      else 
      {
         $short = clean($short, 50);
         $userfile = clean($userfile, 50);
    
         if (!($connection = @ mysql_pconnect($hostName, 
                                             $username, 
                                             $password)))
            showerror();
    
         if (!mysql_select_db("files", $connection))
            showerror();
    
         // Was a file uploaded?
         if (is_uploaded_file($userfile))
         {
           
           switch ($userfile_type)
           {
              case "image/gif";       
                 $mimeName = "GIF Image";
                 break;
              case "image/jpeg";          
                 $mimeName = "JPEG Image";
                 break;
              case "image/png";       
                 $mimeName = "PNG Image";
                 break;
              case "image/x-MS-bmp";       
                 $mimeName = "Windows Bitmap";
                 break;
              default: 
                 $mimeName = "Unknown image type";
           }
       
           // Open the uploaded file
           $file = fopen($userfile, "r");
        
           // Read in the uploaded file
           $fileContents = fread($file, filesize($userfile)); 
    
           // Escape special characters in the file
           $fileContents = AddSlashes($fileContents);
         }  
         else
           $fileContents = NULL;
    
         $insertQuery = "INSERT INTO files VALUES (NULL, \"{$short}\",
             \"{$userfile_type}\", \"{$mimeName}\", \"{$fileContents}\")";
    
         if ((@ mysql_query ($insertQuery, $connection)) 
             && @ mysql_affected_rows() == 1)
           header("Location: receipt.php?status=T&file="
             . mysql_insert_id($connection));
         else
           header("Location: receipt.php?status=F&file=" 
             . mysql_insert_id($connection));  
      } // if else empty()
    ?>
    view.php

    Code:
    <?php
      include 'db.inc';
    
      $file = clean($file, 4);
    
      if (empty($file))
         exit;
    
      if (!($connection = @ mysql_pconnect($hostName,
                                           $username,
                                           $password)))
         showerror();
    
      if (!mysql_select_db("files", $connection))
         showerror();
    
      $query = "SELECT mimeType, fileContents FROM files 
                WHERE id = $file";
    
      if (!($result = @ mysql_query ($query,$connection)))
         showerror();  
    
      $data = @ mysql_fetch_array($result);
    
      if (!empty($data["fileContents"]))
      {
        // Output the MIME header
         header("Content-Type: {$data["mimeType"]}");
        // Output the image
         echo $data["fileContents"];
       }
    ?>
    receipt.php

    Code:
     <!DOCTYPE HTML PUBLIC 
                   "-//W3C//DTD HTML 4.0 Transitional//EN"
                   "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
          <title>File Insert Receipt</title>
        </head>
        <body bgcolor="white">
    
    <body bgcolor="white">
    <?php
      include 'db.inc';
      
      $status = clean($status, 1);
      $file = clean($file, 5);
    
      // did the insert operation succeed?
      switch ($status)
      {
      case "T":
         // Yes, insert operation succeeded. 
         // Show details of the new file.
    
         $query = "SELECT shortName, mimeName FROM files WHERE id = $file";
    
         if (!($connection = @ mysql_pconnect($hostName, 
                                           $username,
                                           $password)))
            showerror();
    
         if (!mysql_select_db("files", $connection))
            showerror();
            
         // Run the query on the DBMS
         if (!($result = @ mysql_query ($query, $connection)))
            showerror();
    
         if ($row = @ mysql_fetch_array($result))
         {
    ?>
        <h1>File Insert Receipt</h1> 
        <h3>The following file was successfully uploaded:
        <table>
        <col span="1" align="right">
        <tr>
           <td><font color="red">Short description:</font></td>
           <td><?php echo "{$row["shortName"]}";?></td>
        </tr>
    
        <tr>
           <td><font color="red">File type:</font></td>
           <td><?php echo "{$row["mimeName"]}";?></td>
        </tr>
    
        <tr>
           <td><font color="red">File:</font></td>
           <td><?php echo "<img src=\"view.php?file={$file}\">";?></td>
        </tr>
        </table>
    <?php
         } // if mysql_fetch_array()
    
         break;
    
      case "F":
         // No, insert operation failed
         // Show an error message
         echo "The file insert operation failed.";
         echo "<br>Contact the system administrator.";
    
         break;
    
      default:
         // User did not provide a status parameter
         echo "You arrived unexpectedly at this page.";          
      } // end of switch
    ?>
    <h3>Click <a href="insert.php">here</a> to upload another image.</h3>
    <h3>Click <a href="index.php">here</a> to browse the uploaded images.</h3>
    </body>
    </html>
    The image never gets uploaded to the database for some reason!

    Can anyone give me advice on this?
    Thanks
    Glen....
    Last edited by TechnoBear; Aug 20, 2012 at 06:30. Reason: User name & password details removed

  2. #2
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    The image never gets uploaded to the database for some reason!

    Can anyone give me advice on this?
    Turn on error reporting, and also display_errors : this will help you as you develop and show you clearer messages and notices about any errors.

    http://php.net/manual/en/function.error-reporting.php

    In your upload form handler add this line temporarily at the top of the script.

    PHP Code:
    var_dump$_FILES ); 
    In that resulting array if 'error' shows anything other than 0 then the script encountered a problem which can be deciphered here:

    http://php.net/manual/en/features.fi...oad.errors.php

    File uploading is one of the most error-prone operations, and is fraught with security problems so you need to bone up on exactly how it works.

    http://www.php.net/manual/en/features.file-upload.php

    Taking code from a book is of course a great place to start, but you will have to read the corresponding manual pages to really understand what is going on - I am sure your book tells you that.

    I urge you to read that last manual link's associated pages and user comments word for word, take some notes if you can too. Set aside at least a day for this, and have a play with the code.

  3. #3
    SitePoint Member
    Join Date
    Jan 2012
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Cups View Post
    Turn on error reporting, and also display_errors : this will help you as you develop and show you clearer messages and notices about any errors.

    http://php.net/manual/en/function.error-reporting.php

    In your upload form handler add this line temporarily at the top of the script.

    PHP Code:
    var_dump$_FILES ); 
    In that resulting array if 'error' shows anything other than 0 then the script encountered a problem which can be deciphered here:

    http://php.net/manual/en/features.fi...oad.errors.php

    File uploading is one of the most error-prone operations, and is fraught with security problems so you need to bone up on exactly how it works.

    http://www.php.net/manual/en/features.file-upload.php

    Taking code from a book is of course a great place to start, but you will have to read the corresponding manual pages to really understand what is going on - I am sure your book tells you that.

    I urge you to read that last manual link's associated pages and user comments word for word, take some notes if you can too. Set aside at least a day for this, and have a play with the code.
    I was getting
    PHP Code:
    'error' => 
    meaning the file size exceedes the max file size in php.ini according to your link. i reduced the file size and I then got
    PHP Code:
    'error' => 
    but when I try to view the images in the db it still wasnt added!

    Any ideas why?

    Thanks

  4. #4
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I suspect your code was developed for the lower PHP version having register globals ON. Otherwise from where these variables are converted directly $short and $userfile?
    PHP Code:
    if (empty($short) || empty($userfile)) 
    Because I don't see any variable variable conversion either above the use of those variables. So:
    1. What is your PHP version in your computer?
    2. What is your book/manual suggesting the PHP version for testing?
    3. Do you know about register_globals setting/configuration in php.ini file?

    So please consider about all these.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  5. #5
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Add a line of debug, and take a good look into how PHP is assembling the SQL statement (a string) on your behalf:

    PHP Code:
    $insertQuery "INSERT INTO files VALUES (NULL, \"{$short}\",
             \"
    {$userfile_type}\", \"{$mimeName}\", \"{$fileContents}\")";

    // temp line of debug
    echo $insertQuery 
    If it looks OK, paste the output of that echo directly into your database -- using whatever you use to manage your db, then note any errors.

    Then you might figure out: "is this a PHP or SQL problem?"


Bookmarks

Posting Permissions

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