1

I'm following a tutorial found online on uploading images. Need your help for me to understand the coders mind a little better as I'm a newbie.

You see, there is an array with keys and values assigned to possible upload errors. I'm wondering how those errors will trigger as I don't find a relationship elsewhere in the code.

Where I'm struggling to understand is: are these keys 1,2,3,... standard values depicting PHP upload errors or they are just mere numbers?

Second question, is there another method to print the error messages according to this scenario without using a PHP function and avoiding echoing?

Code as follows:

<?php  

// filename: upload.processor.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 files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';

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

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

// name of the fieldname used for the file in 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 form
isset($_POST['submit'])
    or error('the upload form is neaded', $uploadForm);

// check for standard uploading errors
($_FILES[$fieldname]['error'] == 0)
    or error($errors[$_FILES[$fieldname]['error']], $uploadForm);

// check that the file we are working on really was 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 upload is 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 taken... if it is keep trying until we find a vacant one
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
    $now++;
}

// now let's move the file to its final and allocate it with the new filename
@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 the success page.
header('Location: ' . $uploadSuccess);

// make an error handler which will be used if the 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

?>

1 Answer 1

1

There is a realtion, just burried in the logic of the code.

Take this for exaple:

($_FILES[$fieldname]['error'] == 0)
    or error($errors[$_FILES[$fieldname]['error']], $uploadForm);

$_FILES[$fieldname]['error'] is going to evaluate to something, in this case an integer. == 0 is a boolean logic check; does the result of $_FILES[$fieldname]['error'] equal zero?

If it does, we move on.

If it does NOT, we drop down to the next line.

error(args) is a call to the function, error, defined later in the code. This function takes 3 arguments, 2 of which we are passing in when an error occurs.

Let's break this down: error($errors[$_FILES[$fieldname]['error']], $uploadForm), we have determined is a call to the error() function. $errors[$_FILES[$fieldname]['error']] is the first argument that is passed to that function. $uploadForm is the second argument that is passed.

Let's break the first one down:

If I was to ask you what $errors[1] equals, what would you say? Well the [1] is the index of the array errors, in this case I am asking for the first index number, or key value, which of corse is, 'php.ini max file size exceeded'.

So knowing this, we now have a new perspective on what $errors[$_FILES[$fieldname]['error']] means. If you recall from what I stated earlier, $_FILES[$fieldname]['error'] is going to evaluate to some integer value, and since that is inside of [], then what ever that value is, becomes our index, or key value for the errors array.

In summary, we have this block of code:

($_FILES[$fieldname]['error'] == 0)
    or error($errors[$_FILES[$fieldname]['error']], $uploadForm);

At run time, we check to see if $_FILES[$fieldname]['error'] is equal to zero. If it is, move on, there was no error. If it is not equal to zero, run the second line, which calls the error() function, and passes in the errors array with some index (that pertains to the error that was thrown) and the value of $uploadForm.

Without seeing the code in its entirely, or knowing the full context of your project, it is hard to say weather or not an echo is required. I can tell you exactly what this script is doing however, if that helps? If there were no errors, it redirects the user to the upload success page. If there were errors, ie the error() function was called, this script generates a completely new, page, containing the details of the error. Sure there are other ways of doing it, but this is quick and easy.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for this. I guess I'm starting to digest better. Can I also post a one another question? If I want to remove the echo (replace with something to like a variable) inside the function but to print the error messages as is how do you suggest that I change the function? May be you can add and edit to your excellent explanation. Thanks again
Well, technically speaking the way the function is now is "correct", and in my opinion, is a very good way of handling things. It sends the user a correctly formatted HTML page, and tells the user's browser to automatically refresh in 5 seconds, in order to try the reload again. Also, currently this HTML block that is being echoed contains a link to a CSS file. I will offer this simpler solution, with a disclaimer however, it is 2013 and this is not the most "correct" way of doing things. It still uses an echo statement, but without the HTML block. Simply echo $error; Leave the header call.
You might take a look at this post, and its solution stackoverflow.com/questions/18429174/… it appears to be a similar script to the one you are using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.