/    Sign up×
Community /Pin to ProfileBookmark

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:

[code=php]
<?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(1 => ‘php.ini max file size exceeded’,
2 => ‘html form max file size exceeded’,
3 => ‘file upload was only partial’,
4 => ‘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”>’.”nn”.
‘<html lang=”en”>’.”n”.
‘ <head>’.”n”.
‘ <meta http-equiv=”content-type” content=”text/html; charset=iso-8859-1″>’.”nn”.
‘ <link rel=”stylesheet” type=”text/css” href=”stylesheet.css”>’.”nn”.
‘ <title>Upload error</title>’.”nn”.
‘ </head>’.”nn”.
‘ <body>’.”nn”.
‘ <div id=”Upload”>’.”nn”.
‘ <h1>Upload failure</h1>’.”nn”.
‘ <p>An error has occured: ‘.”nn”.
‘ <span class=”red”>’ . $error . ‘…</span>’.”nn”.
‘ The upload form is reloading</p>’.”nn”.
‘ </div>’.”nn”.
‘</html>’;
exit;
} // end error handler

?>
[/code]

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:

[U][I]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?[/I][/U]

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.

[I][U]Is there some way to change whole name to something of my own choice instead of just adding text to the name??[/U][/I]

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.

to post a comment
PHP

7 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiMar 28.2010 — 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:
    [LIST]
  • [*]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.

  • [/LIST]


  • 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 [FONT="Courier New"]/home/you/public_html/images/foo.jpg[/FONT], 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:


  • [code=php]$base = '/home/you/public_html/images/';
    $ext = pathinfo($_FILES['foo']['name'], PATHINFO_EXTENSION);
    $newFilename = $base . 'foo' . $ext;
    [/code]
    Copy linkTweet thisAlerts:
    @OllieBarnettMar 29.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.
    Copy linkTweet thisAlerts:
    @MindzaiMar 29.2010 — Unlink will not work unless the script is in the same folder as the file you want to delete.[/QUOTE]

    That's not correct. Unlink can delete a file anywhere as long as the webserver has the necessary permissions.

    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.[/quote]

    This is a good point (and you are correct, move_uploaded_file will overwrite).
    Copy linkTweet thisAlerts:
    @OllieBarnettMar 29.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!
    Copy linkTweet thisAlerts:
    @MindzaiMar 29.2010 — You just have to supply a path as a string, either relative to the current working directory, or absolute. For example:

    [code=php]
    // 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
    [/code]


    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:

    [code=php]
    $base = dirname(__FILE__);
    $path = $base . '/foo/bar.txt';
    [/code]


    This way you maintain the portability and location-agnosticism that you get with relative paths but avoid the downsides.
    Copy linkTweet thisAlerts:
    @OllieBarnettMar 29.2010 — Thanks Mindzai
    Copy linkTweet thisAlerts:
    @aim4perfectionauthorApr 04.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?

    [code=php]
    $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);[/code]



    Thanks again for any further help!
    ×

    Success!

    Help @aim4perfection spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.19,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...