SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2006
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Smile Replacing Uploaded Images

    Hi,

    The following script, when passed a product ID, displays the products details in a form so that the user can edit the details for that product. It also presents the user with three file upload boxes so they can upload three image: a thumbnail, a main image and an enlarged image.

    At the moment. If you press submit and select images to upload in the three file upload fields, the pictures are uploaded to the relevant directories. This is good. However, if the user then returns to the product to edit it a second time and does not submit any pictures, the path to the pictures in the database is wiped.

    Please could someone point me in the right direction to get this script to:

    - Check to see if there are pictures existing for this product (for thumb, main and large) and return text to the form to confirm this or not. (ie: populate the file path form box with the image name)

    - If no pictures are uploaded during an edit+submit, do NOT overwrite the existing image paths with 'nothing'. ie. Only update the image paths if SOMETHING is submitted

    - If a new image is uploaded for the product. Delete the old image.

    Ideally, I'd like the user to upload just one large image, which is then resized to a thumb and a main image, which are then saved to relevant locations in the File system. I have seen scripts for this but they just blow my mind as i am new to PHP.

    PHP Code:
    <html>

    <body>



    <?php



    include 'config.php';
    include 
    'opendb.php';

    $thumbUploadDir 'product_images/thumb/'
    $mediumUploadDir 'product_images/medium/';
    $largeUploadDir 'product_images/large/';
     


    if (
    $submit) {

      
    // here if no ID then adding else we're editing

      
    if ($id) {
    if(isset(
    $_POST['submit'])) { 

        
    $thumbName $_FILES['thumb']['name']; 
        
    $tmpName  $_FILES['thumb']['tmp_name']; 
        
    $thumbFileSize $_FILES['thumb']['size']; 
        
    $thumbFileType $_FILES['thumb']['type'];

        
    $thumbFilePath $thumbUploadDir $thumbName;  // the files will be saved in filePath 
      
    $result  move_uploaded_file($tmpName$thumbFilePath); 
     
        
    $mediumName $_FILES['medium']['name']; 
        
    $tmpName  $_FILES['medium']['tmp_name']; 
        
    $mediumFileSize $_FILES['medium']['size']; 
        
    $mediumFileType $_FILES['medium']['type']; 

      
    $mediumFilePath $mediumUploadDir $mediumName
     
    $result  move_uploaded_file($tmpName$mediumFilePath); 

        
    $largeName $_FILES['large']['name']; 
        
    $tmpName  $_FILES['large']['tmp_name']; 
        
    $largeFileSize $_FILES['large']['size']; 
        
    $largeFileType $_FILES['large']['type']; 
      
        
    $largeFilePath $largeUploadDir $largeName;  
        

     
    // move the files to the specified directory 
        // if the upload directory is not writable or 
        // something else went wrong $result will be false 
     
    $result  move_uploaded_file($tmpName$largeFilePath); 
      


      
    if(!
    get_magic_quotes_gpc()) 
        { 
            
    $thumbName  addslashes($thumbName); 
            
    $thumbFilePath  addslashes($thumbFilePath); 

            
    $mediumName  addslashes($mediumName); 
            
    $mediumFilePath  addslashes($mediumFilePath); 

            
    $largeName  addslashes($largeName); 
            
    $largeFilePath  addslashes($largeFilePath); 
        }   


    }

        
    $sql "UPDATE products SET title='$title',long_description='$long_description', img_name='$mediumName', img_size='$mediumFileSize', img_type='$mediumFileType', img_path='$mediumFilePath', TMimg_name='$thumbName', TMimg_size='$thumbFileSize', TMimg_type='$thumbFileType', TMimg_path='$thumbFilePath', LGimg_name='$largeName', LGimg_size='$largeFileSize', LGimg_type='$largeFileType', LGimg_path='$largeFilePath' WHERE id=$id";


      } 
    else {

        
    $sql "INSERT INTO products (title,long_description) VALUES ('$title','$long_description')";

      }

      
    // run SQL against the DB

      
    $result mysql_query($sql);

      echo 
    "Record updated/edited!<p>";

    } elseif (
    $delete) {

        
    // delete a record

        
    $sql "DELETE FROM employees WHERE id=$id";    

        
    $result mysql_query($sql);

        echo 
    "$sql Record deleted!<p>";

    } else {

      
    // this part happens if we don't press submit

      
    if (!$id) {

        
    // print the list if there is not editing

        
    $result mysql_query("SELECT id, title, long_description FROM products");

        while (
    $myrow mysql_fetch_array($result)) {

          
    printf("<a href=\"%s?id=%s\">%s %s</a> \n"$PHP_SELF$myrow["id"], $myrow["title"], $myrow["long_description"]);

          
    printf("<a href=\"%s?id=%s&delete=yes\">(DELETE)</a><br>"$PHP_SELF$myrow["id"]);

        }

      }



      
    ?>

      <P>

      <a href="<?php echo $PHP_SELF?>">ADD A RECORD</a>

      <P>

      <form method="post" enctype="multipart/form-data" action="<?php echo $PHP_SELF?>">

      <?php



      
    if ($id) {

        
    // editing so select a record

        
    $sql "SELECT * FROM products WHERE id=$id";

        
    $result mysql_query($sql);

        
    $myrow mysql_fetch_array($result);

        
    $id $myrow["id"];

        
    $title $myrow["title"];

        
    $long_description $myrow["long_description"];


        
    // print the id for editing


        
    ?>

        <input type=hidden name="id" value="<?php echo $id ?>">

        <?php

      
    }



      
    ?>



      ID:<input type="Text" name="id" value="<?php echo $id ?>"><br>

      Title:<input type="Text" name="title" value="<?php echo $title ?>"><br>

    Long Description: <br><TEXTAREA NAME="long_description", ROWS=20, COLS=60> <?php echo $long_description ?></TEXTAREA>
    <br>


     
    <input type="hidden" name="MAX_FILE_SIZE" value="20000000">

    Thumbnail Pic:<br><input name="thumb" type="file" class="box" id="thumb"> 158 x 98 pixels<br>
    Main Pic:<br><input name="medium" type="file" class="box" id="medium"> 455 x 257 pixels<br>
    Large Pic:<br><input name="large" type="file" class="box" id="large"> 740 x 418 pixels<br>

    <input type="Submit" name="submit" id="submit" value="SAVE">


      </form>



    <?php



    }



    ?>



    </body>

    </html>

  2. #2
    SitePoint Wizard silver trophy
    Join Date
    Mar 2006
    Posts
    6,132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    a crude way to only update the db if we have a valid filename to insert.
    PHP Code:
    $sql "UPDATE products SET title='$title',long_description='$long_description'";


    $result_thumb  move_uploaded_file($tmpName$thumbFilePath);
    if (!
    $result_thumb) {
        
    // we have an error, we didnt do any validation so we have no idea why...
    } else {
        
    // seems to be ok, so we can add this to db
        
    $sql .= ", TMimg_name='$thumbName', TMimg_size='$thumbFileSize', TMimg_type='$thumbFileType', TMimg_path='$thumbFilePath'";
    }


    // repeat for other images...


    // then
    $sql .= " WHERE id=$id";
    echo 
    $sql
    im just showing you the logic, you must structure the code in. dont forget to use addslashes(), or preferably mysql_real_escape_string() instead.


    how to give advisory message of which images already exist.
    PHP Code:
    $sql "SELECT TMimg_name, img_name, LGimg_name FROM products WHERE id = $id";
    $res mysql_query($sql);
    if (
    mysql_num_rows($res)) {
        
    $row mysql_fetch_assoc($res);
        
    $small_exists strlen($row['TMimg_name']);
        
    $med_exists strlen($row['img_name']);
        
    $large_exists strlen($row['LGimg_name']);
    }

    if (
    $small_exists) {
        echo 
    'small exists!';
    }
    // etc... 

    Off Topic:


    your code is very lacking in the validation department. fortunately it seems like maybe only an admin with non-malcious intents will use this, but ideally your code should still be resilient.

    you dont do any validation on the filename, or what type of file it is. you should be using basename() on the filename to eliminate any filepaths. you should be checking the file extension against a list of allowed files.

    consider what would happen if a user uploaded
    ../../bad.exe
    or similar variants. you get the point.

    also, i dont know where $id comes from, im guessing from the url. you should define this and make sure its a number. for example
    $id = intval($_GET['id']);

    those were the most glaring issues i saw.


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
  •