How to select image from folder, when image has random name and extension?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilya Kraft
    New Member
    • Jan 2011
    • 134

    How to select image from folder, when image has random name and extension?

    Hello,

    I need to select image from a member folder to set it as their profile image. The problem is that I don't know how to do this, because that image has no fixed name or extension, so every time there is a different name for it. I need to use PHP for this, something like:

    Code:
    //This is not real code, just logic
    Select image from members/$member_id/image
    Here are scripts that I use to upload and store image in member folder.

    Upload Form
    Code:
    <form enctype="multipart/form-data" method="post" action="image_upload_script.php">
        Choose your file here:
        <input name="uploaded_file" type="file"/><br /><br />
        <input type="submit" value="Upload It"/>
        </form>
    image_upload_sc ript.php
    Code:
    <?php
    if (!$_SESSION['idx']) { 
        $msgToUser = '<br /><br /><font color="#FF0000">Only site members can do that</font><p><a href="register.php">Join Here</a></p>';
        include_once 'msgToUser.php'; 
        exit(); 
    } else if ($logOptions_id != $_SESSION['id']) {
    	$msgToUser = '<br /><br /><font color="#FF0000">Only site members can do that</font><p><a href="register.php">Join Here</a></p>';
        include_once 'msgToUser.php'; 
        exit(); 
    }
    $id = $logOptions_id;
    // Access the $_FILES global variable for this specific file being uploaded
    // and create local PHP variables from the $_FILES array of information
    $fileName = $_FILES["uploaded_file"]["name"]; // The file name
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot
    $fileExt = end($kaboom); // Now target the last array element to get the file extension
    // START PHP Image Upload Error Handling --------------------------------------------------
    if (!$fileTmpLoc) { // if file not chosen
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
    } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
        echo "ERROR: Your file was larger than 5 Megabytes in size.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    } else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
         // This condition is only if you wish to allow uploading of specific file types    
         echo "ERROR: Your image was not .gif, .jpg, or .png.";
         unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
         exit();
    } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
        echo "ERROR: An error occured while processing the file. Try again.";
        exit();
    }
    // END PHP Image Upload Error Handling ----------------------------------------------------
    // Place it into your "uploads" folder mow using the move_uploaded_file() function
    $moveResult = move_uploaded_file($fileTmpLoc, "members/$id/$fileName");
    // Check to make sure the move result is true before continuing
    if ($moveResult != true) {
        echo "ERROR: File not uploaded. Try again.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    }
    unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    When you upload the image, you should update the user record with the path of the image.

    Comment

    • ilya Kraft
      New Member
      • Jan 2011
      • 134

      #3
      Hi Rabbit,

      Do you mean that, I should create a field like "profile_im age" which contains path to the image?

      So say I have a field "profile_im age" Field set to "VARCHAR" and with path to default image as Length/Values "members/default.jpg".

      So then I would just use something like:
      Code:
      $new_image = members/$id/$filename
      
      $profile_image_sql = mysql_query("INSERT INTO myMembers (profile_image) VALUES('$new_image')")
              or die (mysql_error());
      This is what I think would be right, not sure though. Could you please tell me if this will work and also I think that this method will automatically replace old image with new when user uploads another file, am I right? If I am right, could you also point where exactly should I place this lines of code so it actually works.

      Thank You

      Comment

      • Markus
        Recognized Expert Expert
        • Jun 2007
        • 6092

        #4
        You would use UPDATE rather than INSERT. But that's the general idea, yes.

        Comment

        • ilya Kraft
          New Member
          • Jan 2011
          • 134

          #5
          Thnx Markus, one thing I'm concerned about. Is it alright if I define path to default image in Length/Values ? I mean will it change when I use UPDATE ? Also where should I place the code? I'm not sure where the good place is.

          Thank You

          Comment

          • Markus
            Recognized Expert Expert
            • Jun 2007
            • 6092

            #6
            It will change when you run an UPDATE query, yes.

            The UPDATE should be run when you're happy that the file has indeed been uploaded, otherwise you could end up with a path in your database to a non-existent file!

            Also, you do not need to unlink the temporary file paths - they're cleaned up by the system.

            Comment

            • ilya Kraft
              New Member
              • Jan 2011
              • 134

              #7
              Hi,

              Alright I think I've got it ))) Just in case, Is it a good idea to put UPDATE after line 40 in image_upload_sc ript.php ?

              Thank You again
              Last edited by ilya Kraft; Jun 24 '11, 06:43 PM. Reason: typo

              Comment

              • Markus
                Recognized Expert Expert
                • Jun 2007
                • 6092

                #8
                Yes - but make sure you've checked the return value of $moveresult before.

                Comment

                • ilya Kraft
                  New Member
                  • Jan 2011
                  • 134

                  #9
                  Hi,

                  I tried it out, but came over a problem. When I create a field "profile_im age" I set it as a "VARCHAR" and for Lenght/Values I enter path to deafult image e.g. members/0/image.jpg. But when I click Save an error saying: This is not a number. pops out. Is it because I use VARCHAR ?

                  UPDATE: Fixed it, forgot that I need to define path as a default and then enter character number in Length/Values

                  Comment

                  • Markus
                    Recognized Expert Expert
                    • Jun 2007
                    • 6092

                    #10
                    No. When you tell it you want the VARCHAR datatype, you need to also give it a (maximum) size, in characters, that can be stored. So, a field of type VARCHAR(200) will be able to store up to 200 characters. See the documentation for more info: http://dev.mysql.com/doc/refman/5.0/en/char.html

                    Comment

                    • ilya Kraft
                      New Member
                      • Jan 2011
                      • 134

                      #11
                      Wooh, I have it working now ))) Thank You very much, Now I'm concerned (again :) is it secure agains SQL injections? I have same code as in my first post here + I added this lines at the very end of image_upload_sc ript.php

                      new variables are from other code parts

                      Code:
                      $img_sql = mysql_query("UPDATE myMembers SET profile_img='$resized_file' WHERE id='$id' LIMIT 1");
                      Is it secure enough?

                      Comment

                      • ilya Kraft
                        New Member
                        • Jan 2011
                        • 134

                        #12
                        Alright,

                        It works cool ))), but there is a problem. When user uploads new image the old one still remains in their folder. Is there a way to delete old one, so user data takes less space?

                        Comment

                        Working...