Results 1 to 8 of 8

Thread: Issue with picture upload

  1. #1
    Join Date
    Mar 2010

    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:

    // 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
    error('the upload form is neaded'$uploadForm);

    // check for PHP's built-in uploading errors
    ($_FILES[$fieldname]['error'] == 0)
    error($errors[$_FILES[$fieldname]['error']], $uploadForm);
    // check that the file we are working on really was the subject of an HTTP upload
    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.
    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;
    file_exists($uploadFilename $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))

    // 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)
    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\"");
    '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\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".
    // 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
    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 09:26 AM.
    The first rule of Tautology Club is the first rule of Tautology Club.

  3. #3
    Join Date
    Mar 2010
    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
    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 04:56 PM.
    The first rule of Tautology Club is the first rule of Tautology Club.

  5. #5
    Join Date
    Mar 2010
    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
    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

    // subdirectory relative to cwd

    // parent directory relative to cwd

    // parent of parent

    // up then back down again!

    // 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 05:16 PM.
    The first rule of Tautology Club is the first rule of Tautology Club.

  7. #7
    Join Date
    Mar 2010
    Thanks Mindzai

  8. #8
    Join Date
    Mar 2010
    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';
    file_exists($uploadFilename $uploadsDirectory.'add1'.$ext))

    move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
    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



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.47896 seconds
  • Memory Usage 2,974KB
  • Queries Executed 15 (?)
More Information
Template Usage (34):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (5)bbcode_php
  • (2)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (8)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (8)postbit
  • (8)postbit_onlinestatus
  • (8)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates