SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2001
    Location
    UK
    Posts
    190
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Upload Image + Filename

    Hi,

    I'm trying to upload an image to a folder, and then insert the image path into a database. I have a working script to upload the image, but i'm not sure how to connect it to the second part.

    PHP Code:
     <?php
    if ($HTTP_POST_VARS['submit']) {
    print_r($HTTP_POST_FILES);
    if (!
    is_uploaded_file($HTTP_POST_FILES['file']['tmp_name'])) {
        
    $error "You did not upload a file!";
        
    unlink($HTTP_POST_FILES['file']['tmp_name']);
        
    // assign error message, remove uploaded file, redisplay form.
    } else {
        
    //a file was uploaded
        
    $maxfilesize=10240;
        if (
    $HTTP_POST_FILES['file']['size'] > $maxfilesize) {
         
    $error "file is too large";
         
    unlink($HTTP_POST_FILES['file']['tmp_name']);
         
    // assign error message, remove uploaded file, redisplay form.
        
    } else {
         if (
    $HTTP_POST_FILES['file']['type'] != "image/gif" AND $HTTP_POST_FILES['file']['type'] != "image/pjpeg") { 
            
    $error "This file type is not allowed";
            
    unlink($HTTP_POST_FILES['file']['tmp_name']);
            
    // assign error message, remove uploaded file, redisplay form.
         
    } else {
         
    //File has passed all validation, copy it to the final destination and remove the temporary file:
         
    copy($HTTP_POST_FILES['file']['tmp_name'],"/directorypath/".$HTTP_POST_FILES['file']['name']);
         
    unlink($HTTP_POST_FILES['file']['tmp_name']);
         print 
    "File has been successfully uploaded!";
         exit;
         }
        } 
    }
    }
    ?>
     
    <html>
    <head></head>
    <body>
    <form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
    <?=$error?>
    <br><br>
    Choose a file to upload:<br>
    <input type="file" name="file"><br>
    <input type="submit" name="submit" value="submit">
    </form>
    This uploads the image.

    PHP Code:
     <?
    // Connect to the database server
    $dbcnx = @mysql_connect("localhost""username""password");
    if (!
    $dbcnx) {
    echo( 
    "<p>Unable to connect to the " .
    "database server at this time.</p>" );
    exit();
    }
    // Select the database
    if (! @mysql_select_db("name") ) {
    echo( 
    "<p>Unable to locate the " .
    "database at this time.</p>" );
    exit();
    }
    // add it to the database.
    if ($submit == "SUBMIT") {
    $sql "INSERT INTO table SET Image='$file', ID='$ID'";
     
    if (@
    mysql_query($sql)) {
    echo(
    "<p><B><font face='Verdana, Arial, Helvetica, sans-serif' size='2' color='#000000'>Thanks, the record has been added.</p></B></font>");
    } else {
    echo(
    "<p>Error adding submitted record: " .
    mysql_error() . "</p>");
    }
    }
    ?>
    This is what I would use to insert the path into the database. I can't get it to work though?

    Thanks a lot,

    Rob

  2. #2

    Join Date
    Oct 2003
    Location
    €uroLand
    Posts
    1,340
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What error are you exactly experiencing? If it is just a database issue that this happens most likely due to the incorrect INSERT sytax.

    In your case it should be
    PHP Code:
    'INSERT INTO table (Image, ID) VALUES ("'.$file.'", "'.$ID.'")' 

  3. #3
    SitePoint Zealot David C's Avatar
    Join Date
    Nov 2003
    Location
    New York!
    Posts
    105
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Also, it's good practice not to use quotes around numeric values.

  4. #4
    PHP manual bot bronze trophy Gaheris's Avatar
    Join Date
    Oct 2003
    Location
    Germany
    Posts
    2,195
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I rewrote it a bit, tell me if it helps you.
    PHP Code:
    <?php
    // Settings
    define('MAX_FILE_SIZE'8192); // 8 MB
    define('UPLOAD_PATH',   '/directorypath/');
    $allowed_types = array('image/gif''image/pjpeg''image/jpeg');

    // Upload handling
    if (isset($_POST['submit'])) {
        switch (
    $_FILES['file']['error']) {
            case 
    UPLOAD_ERR_NO_FILE:
                
    $error 'You did not upload a file!';
                break;
            case 
    UPLOAD_ERR_OK:
                if (
    $_FILES['file']['size'] > MAX_FILE_SIZE) {
                    
    $error 'File is too large!';
                    break;
                }
                if (!
    in_array($_FILES['file']['type'], $allowed_types) {
                    
    $error 'This file types is not allowed!';
                    break;
                }
                if (!
    move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_PATH $_FILES['file']['name'])) {
                    
    $error 'Could not move file, upload failed!';
                    break;
                }
                
    // Add file entry
                
    mysql_connect('localhost''username''password') or die(mysql_error());
                
    mysql_select_db('name') or die(mysql_error());
                
    $sql "INSERT INTO table (Image) VALUES ('".$_FILES['file']['name']."')";
                
    mysql_error($sql) or die(mysql_error());
                break;
        }
        
    $message = isset($error) ? '<span style="color:red">'.$error.'</span>'
                                 
    '<span style="font-weight:bold">Upload successfull</span>';
    }
    ?>

    <html>
      <head>
        <title>Upload file</title>
      </head>
      <body>
        <form action="" method="post" enctype="multipart/form-data">
          <?php if (isset($message)) echo $message?>
          <br><br>
          Choose a file to upload:<br>
          <input type="file" name="file"><br>
          <input type="submit" name="submit" value="submit">
        </form>
      </body>
    </html>

  5. #5
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    vta,ca,usa
    Posts
    180
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by drzoid
    What error are you exactly experiencing? If it is just a database issue that this happens most likely due to the incorrect INSERT sytax.

    In your case it should be
    PHP Code:
    'INSERT INTO table (Image, ID) VALUES ("'.$file.'", "'.$ID.'")' 
    I think it's ironic that the link you posted shows the exact INSERT syntax Robb used, e.g.
    Code:
    INSERT INTO sometable SET somefield = 'my data here', someotherfield = NOW();
    That's perfectly acceptable although not seen much in mainstream MySQL usage. You normally see this sort of syntax used in UPDATE statements.

    I think the main problem is twofold; having a seperate script for the MySQL INSERT, and not using $_FILES['file']['name'] as Gaheris has shown in the example.

  6. #6
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    vta,ca,usa
    Posts
    180
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Very slightly changed from the original:
    PHP Code:
    <?php
    // Settings
    define('MAX_FILE_SIZE'8388608); // 8 MB
    define('UPLOAD_PATH',   '/directorypath/');
    $allowed_types = array('image/gif''image/pjpeg''image/jpeg');

    // Upload handling
    if (isset($_POST['submit'])) {
        switch (
    $_FILES['file']['error']) {
            case 
    UPLOAD_ERR_NO_FILE:
                
    $error 'You did not upload a file!';
                break;
            case 
    UPLOAD_ERR_OK:
                if (
    $_FILES['file']['size'] > MAX_FILE_SIZE) {
                    
    $error 'File is too large!';
                    break;
                }
                if (!
    in_array($_FILES['file']['type'], $allowed_types)) {
                    
    $error 'This file types is not allowed!';
                    break;
                }
                if (!
    move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_PATH $_FILES['file']['name'])) {
                    
    $error 'Could not move file, upload failed!';
                    break;
                }
                
    // Add file entry
                
    mysql_connect('localhost''username''password') or die(mysql_error());
                
    mysql_select_db('name') or die(mysql_error());
                
    $sql "INSERT INTO table (Image) VALUES ('".$_FILES['file']['name']."')";
                
    mysql_query($sql) or die(mysql_error());
                break;
        }
        
    $message = isset($error) ? '<span style="color:red">'.$error.'</span>'
                                 
    '<span style="font-weight:bold">Upload successfull</span>';
    }
    ?>

    <html>
      <head>
        <title>Upload file</title>
      </head>
      <body>
        <form action="" method="post" enctype="multipart/form-data">
          <?php if (isset($message)) echo $message?>
          <br><br>
          Choose a file to upload:<br>
          <input type="file" name="file"><br>
          <input type="submit" name="submit" value="submit">
        </form>
      </body>
    </html>

    Changed two things; parse error on
    PHP Code:
    if (!in_array($_FILES['file']['type'], $allowed_types) { 
    ...and...

    '8192' is 8KB not 8MB...

    Also changed mysql_error($sql) to mysql_query($sql).

  7. #7
    PHP manual bot bronze trophy Gaheris's Avatar
    Join Date
    Oct 2003
    Location
    Germany
    Posts
    2,195
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Very slightly changed from the original:
    Thanks for the corrections bdl.

    '8192' is 8KB not 8MB...

  8. #8
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    vta,ca,usa
    Posts
    180
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Gaheris
    Thanks for the corrections bdl.


    Anytime, that's what we're here for.

    Script works nicely though, I'm going to use it myself. Thanks!

  9. #9

    Join Date
    Oct 2003
    Location
    €uroLand
    Posts
    1,340
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by bdl
    I think it's ironic that the link you posted shows the exact INSERT syntax Robb used, e.g.
    Code:
    INSERT INTO sometable SET somefield = 'my data here', someotherfield = NOW();
    That's perfectly acceptable although not seen much in mainstream MySQL usage. You normally see this sort of syntax used in UPDATE statements.
    oops, I was not aware of this syntax style and since Robb didnt specify the actual error I supposed it was a database related one .... my fault

  10. #10
    SitePoint Zealot
    Join Date
    Nov 2001
    Location
    UK
    Posts
    190
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot for the responses guys.

    I managed to fix it shortly after posting. I think it was a much simplier problem than I first thought.

    If anyone's interested, this is what looks to be working. There's also a form which I wont bother to include. Please let me know if there's anything I should change, I'm still learning

    PHP Code:
    <?php 
    // file upload - In PHP 4.1.0 or later, $_FILES should be used instead of $HTTP_POST_FILES. 
    if ($file_uploaded == "upload") {
    if (
    is_uploaded_file($_FILES['userfile']['tmp_name'])) 

    //upload 
    $file_realname $_FILES['userfile']['name']; 
    //PUT IN FOLDER 
    copy($_FILES['userfile']['tmp_name'], "/pathname/$file_realname"); 

    else 

    echo 
    "<b><font color=red>No file uploaded.</font></b><BR>No file available or file too big to upload."

    // Connect to the database server
    $dbcnx = @mysql_connect("localhost""blah""blah");
    if (!
    $dbcnx) {
    echo( 
    "<p>Unable to connect to the " .
    "database server at this time.</p>" );
    exit();
    }
    // Select the database
    if (! @mysql_select_db("blah") ) {
    echo( 
    "<p>Unable to locate the " .
    "database at this time.</p>" );
    exit();
    }
    $sql "INSERT INTO photos SET Image='$file_realname', Caption='$caption', ID='$ID'";
     
    if (@
    mysql_query($sql)) {
    echo(
    "<p><B><td><font face='Verdana, Arial, Helvetica, sans-serif' size='2' color='#000000'>Thanks, the photo has been added.</p></B></font>");
    } else {
    echo(
    "<p>Error adding record: " .
    mysql_error() . "</p>");
    }
     
    }
    ?>
    Cheers,

    Robb

  11. #11
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    vta,ca,usa
    Posts
    180
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    On a related note, I was killing myself last night trying to get an adaptation of the script Gaheris posted to work on a remote server (works great on mine at home). The script seemed to work fine with one big exception; the file would'nt upload. All indications showed otherwise. I tinkered with it, double and triple checked the directory permissions, etc. FINALLY as I looked around in the PHP manual I found the reason: error handling in $_FILES wasn't added until 4.2 - the server is 4.1. Uh duh. So $_FILES superglobal is there, but $_FILES['file']['error'] and the constants used in the logic isn't.

    Just though you all would like to know that before you to spend half an hour trying to work this out.

    And, yes, I realize the hosts' server is out of date; they don't seem to care (interland.com). Not my hosting account, not much I can do about it.

  12. #12
    SitePoint Member
    Join Date
    Nov 2004
    Location
    Dagenham
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Robb, Could you please post the code for your form please as im am looking to do sonthing like this but have a caption go into the db too. I can see fromy our code that you have this.

    Cheers

    Lee

  13. #13
    SitePoint Enthusiast SlayMan's Avatar
    Join Date
    Oct 2004
    Location
    Germany/ Hamburg
    Posts
    89
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i do have a slight addition:
    PHP Code:
    if ($file_uploaded == "upload"
    this works fine i know, BUT! if you turn on error_reporting (by including this on top of your source):
    PHP Code:
    error_reporting(E_ALL); 
    u will see there is a lot of notices: undefined variable etc.
    U can get around by prechecking the variable before using it:
    Check:
    PHP Code:
    if (isset($variable)) {
    //all your var- based operations

    this means for your example:
    PHP Code:
    if ((isset($file_uploaded)) && ($file_uploaded == "upload")) 
    You see pretty easy, i know this is more work, but it's good style and u won't get notices from PHP.
    SlayMan,
    Your friendly neighbourhood trainee and webmaster
    go, see for yourself @ http://www.alpupp.de

  14. #14
    SitePoint Member
    Join Date
    Nov 2004
    Location
    Dagenham
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for all this code, im using it to upload images and captions for my gallery. What i need it to do also is insert the width and height of the image that was uploaded to my database. When i click Upload it does everything fine but for some reason for every image it inserts width and height as 127 and i don't know why. Could someone please help me, here is the code.
    PHP Code:
    <?php 
    // Settings 
    define('MAX_FILE_SIZE'8388608); // 8 MB 
    define('UPLOAD_PATH',   'images/'); 
    $allowed_types = array('image/gif''image/pjpeg''image/jpeg'); 


    // Upload handling 
    if (isset($_POST['submit'])) { 
        switch (
    $_FILES['file']['error']) { 
            case 
    UPLOAD_ERR_NO_FILE
                
    $error 'You did not upload a file!'
                break; 
            case 
    UPLOAD_ERR_OK
                if (
    $_FILES['file']['size'] > MAX_FILE_SIZE) { 
                    
    $error 'File is too large!'
                    break; 
                } 
                if (!
    in_array($_FILES['file']['type'], $allowed_types)) { 
                    
    $error 'This file types is not allowed!'
                    break; 
                } 
                if (!
    move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_PATH $_FILES['file']['name'])) { 
                    
    $error 'Could not move file, upload failed!'
                    break; 
                } 
                list(
    $width$height) = getimagesize('images/'.$_FILES['file']['name']); 
                echo 
    "Height = $height &amp; Width = $width";

                
    // Add file entry 
                
    mysql_connect('localhost''root''xxxx') or die(mysql_error()); 
                
    mysql_select_db('test') or die(mysql_error()); 
                
    $sql "INSERT INTO babygallery (Image, caption, height, width) VALUES ('".$_FILES['file']['name']."', '" . ($caption) . "', '" . ($height) . "', '" . ($width) . "' )"
                
    mysql_query($sql) or die(mysql_error()); 
                break; 
        } 
        
    $message = isset($error) ? '<span style="color:red">'.$error.'</span>' 
                                 
    '<span style="font-weight:bold">Upload successfull</span>'

    ?> 

    <html> 
      <head> 
        <title>Upload file</title> 
      </head> 
      <body> 
        
      <form action="" method="post" enctype="multipart/form-data"> 
          <?php if (isset($message)) echo $message?> 
          <br><br> 
          Choose a file to upload:<br> 
          <input type="file" name="file"><br>
          <br>     
          <textarea name="caption" cols="50"><?php echo $caption ?></textarea>
          <br>    
        <input type="submit" name="submit" value="Upload"> 
        </form> 
        
      </body> 
    </html>
    Last edited by lbeetles; Nov 2, 2004 at 10:24.


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
  •