www.webdeveloper.com
Results 1 to 8 of 8

Thread: Issue with picture upload

  1. #1
    Join Date
    Mar 2010
    Location
    Sweden
    Posts
    5

    Question Issue with picture upload

    Hello everyone, I'm all new to the PHP language and I have encountered some issues while editing an PHP upload script I'd like to use on a site.

    The purpose is to upload a picture, have it renamed and then placed in it's correct sub-folder. Because the picture is supposed to be changed regularly I also would like it to delete old pictures with the specific name in the targeted sub-folder before uploading new ones.

    This is the upload script that's requested when i press "upload" on my site:

    PHP Code:
    <?php
    $myFile 
    "outlet/1/outlet1.jpg";
    unlink($myFile);
    ?>
    <?php

    // first let's set some variables

    // make a note of the current working directory, relative to root.
    $directory_self str_replace(basename($_SERVER['PHP_SELF']), ''$_SERVER['PHP_SELF']);

    // make a note of the directory that will recieve the uploaded file
    $uploadsDirectory $_SERVER['DOCUMENT_ROOT'] . $directory_self 'outlet/1/';

    // make a note of the location of the upload form in case we need it
    $uploadForm 'http://' $_SERVER['HTTP_HOST'] . $directory_self 'uploadformfirst.php';

    // make a note of the location of the success page
    $uploadSuccess 'http://' $_SERVER['HTTP_HOST'] . $directory_self 'upload.success.php';

    // fieldname used within the file <input> of the HTML form
    $fieldname 'file';

    // Now let's deal with the upload

    // possible PHP upload errors
    $errors = array(=> 'php.ini max file size exceeded',
                    
    => 'html form max file size exceeded',
                    
    => 'file upload was only partial',
                    
    => 'no file was attached');

    // check the upload form was actually submitted else print the form
    isset($_POST['submit'])
        or 
    error('the upload form is neaded'$uploadForm);

    // check for PHP's built-in uploading errors
    ($_FILES[$fieldname]['error'] == 0)
        or 
    error($errors[$_FILES[$fieldname]['error']], $uploadForm);
        
    // check that the file we are working on really was the subject of an HTTP upload
    @is_uploaded_file($_FILES[$fieldname]['tmp_name'])
        or 
    error('not an HTTP upload'$uploadForm);
        
    // validation... since this is an image upload script we should run a check  
    // to make sure the uploaded file is in fact an image. Here is a simple check:
    // getimagesize() returns false if the file tested is not an image.
    @getimagesize($_FILES[$fieldname]['tmp_name'])
        or 
    error('only image uploads are allowed'$uploadForm);
        
    // make a unique filename for the uploaded file and check it is not already
    // taken... if it is already taken keep trying until we find a vacant one
    $now outlet;
    while(
    file_exists($uploadFilename $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
    {
        
    $now++;
    }

    // now let's move the file to its final location and allocate the new filename to it
    @move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
        or 
    error('receiving directory insuffiecient permission'$uploadForm);
        
    // If you got this far, everything has worked and the file has been successfully saved.
    // We are now going to redirect the client to a success page.
    header('Location: ' $uploadSuccess);

    // The following function is an error handler which is used
    // to output an HTML error page if the file upload fails
    function error($error$location$seconds 5)
    {
        
    header("Refresh: $seconds; URL=\"$location\"");
        echo 
    '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
        
    '"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
        
    '<html lang="en">'."\n".
        
    '    <head>'."\n".
        
    '        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
        
    '        <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
        
    '    <title>Upload error</title>'."\n\n".
        
    '    </head>'."\n\n".
        
    '    <body>'."\n\n".
        
    '    <div id="Upload">'."\n\n".
        
    '        <h1>Upload failure</h1>'."\n\n".
        
    '        <p>An error has occured: '."\n\n".
        
    '        <span class="red">' $error '...</span>'."\n\n".
        
    '         The upload form is reloading</p>'."\n\n".
        
    '     </div>'."\n\n".
        
    '</html>';
        exit;
    // end error handler

    ?>
    Now to my issues, first of all I'm trying to delete any previous picture with the "unlink" command without any success so I wounder:

    what am I doing wrong? Is it even OK to add the unlink command before the upload code like I have done or is there any other way?

    Second question, the change name part of my script is actually just adding a word to the chosen file name, this makes a problem when the file is to be read by the page because i have to know the name to use the "img src=" attribute, as it is now I have to rename the picture myself before uploading and that feel really amateur like.

    Is there some way to change whole name to something of my own choice instead of just adding text to the name??

    Would really appreciate any help I could get this drives me crazy over here

    _____

    I hope i have given you enough info, this is my first post so please tell me if there is something I have missed, and I have searched the forum for answers but haven't found anything that solved my problems.

  2. #2
    Join Date
    Nov 2008
    Posts
    2,477
    I'll assume you're using Linux & Apache.

    1. Make sure the user which Apache runs as (usually www-data or nobody) has write permission on the image file. This means that either:
    • Apache needs to own the file (which it will if you uploaded it via PHP) and the file has owner write permissions,
    • The file owner is in the same group as the Apache user and the file has group write permissions, or
    • The file is owned by any user from any group, but it has global write permissions.


    2. The second argument to the move_uploaded_file function is the full path (including filename) of the uploaded file. You can set this to anything you like (as long as it resolved to a directory in which the Apache user can write). For example, if you want to upload the file to /home/you/public_html/images/foo.jpg, just pass that in as a second parameter to the move_uploaded_file function. In practice you will probably want to ensure you use the correct file extension etc, in which case I use the pathinfo function to get the extension. For example:

    PHP Code:
    $base '/home/you/public_html/images/';
    $ext pathinfo($_FILES['foo']['name'], PATHINFO_EXTENSION);
    $newFilename $base 'foo' $ext
    Last edited by Mindzai; 03-28-2010 at 10:26 AM.

  3. #3
    Join Date
    Mar 2010
    Posts
    15
    Did you get this problem sorted? Unlink will not work unless the script is in the same folder as the file you want to delete. As far as I know if you upload the file, say to your images directory and have renamed it - the new file will overwrite the old one so deleting is strictly not necessary.

    Why not store the file name in a database and then your script can pull that image from there without you having to know the name of the image.

  4. #4
    Join Date
    Nov 2008
    Posts
    2,477
    Quote Originally Posted by OllieBarnett View Post
    Unlink will not work unless the script is in the same folder as the file you want to delete.
    That's not correct. Unlink can delete a file anywhere as long as the webserver has the necessary permissions.

    Quote Originally Posted by OllieBarnett View Post
    As far as I know if you upload the file, say to your images directory and have renamed it - the new file will overwrite the old one so deleting is strictly not necessary.
    This is a good point (and you are correct, move_uploaded_file will overwrite).
    Last edited by Mindzai; 03-29-2010 at 05:56 PM.

  5. #5
    Join Date
    Mar 2010
    Posts
    15
    Thanks for that Mindzai, i have actually never used unlink until i tried it today and had thought that the script had to be in the same directory. How do you delete a file in a different directory? I should maybe post this as a separate question! Any pointers in the right direction would be appreciated!

  6. #6
    Join Date
    Nov 2008
    Posts
    2,477
    You just have to supply a path as a string, either relative to the current working directory, or absolute. For example:

    PHP Code:
    // absolute path from root
    unlink('/foo/bar/baz.txt');

    // subdirectory relative to cwd
    unlink('some/dir/file.txt');

    // parent directory relative to cwd
    unlink('../foo.txt');

    // parent of parent
    unlink('../../foo.txt');

    // up then back down again!
    unlink('../../foo/bar/baz.txt');

    // etc 
    There are some gotchas with relative paths and include/require, so to be safe I tend to build an absolute path using the current script's location as a base, eg:

    PHP Code:
    $base dirname(__FILE__);
    $path $base '/foo/bar.txt'
    This way you maintain the portability and location-agnosticism that you get with relative paths but avoid the downsides.
    Last edited by Mindzai; 03-29-2010 at 06:16 PM.

  7. #7
    Join Date
    Mar 2010
    Posts
    15
    Thanks Mindzai

  8. #8
    Join Date
    Mar 2010
    Location
    Sweden
    Posts
    5
    hey guys, big thanks for all the help you given this far, unfortunately I can't get it to work just yet

    The name changes as I want it to but the issue is now that when I upload a second picture nothing happens ( receive a blank page after a major loading time by FF)

    I changed my code to the following fixing the name but is there anything I've written that makes the overwriting fail?

    PHP Code:
    $ext '.jpg';
    while(
    file_exists($uploadFilename $uploadsDirectory.'add1'.$ext))
    {
    }

    @
    move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
        or 
    error('receiving directory insuffiecient permission'$uploadForm);
        
    header('Location: ' $uploadSuccess); 

    Thanks again for any further help!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles