PHP Array在文件上传时触发错误消息 [英] PHP Array to trigger error message on file upload

查看:56
本文介绍了PHP Array在文件上传时触发错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪在线上载的有关上载图像的教程.我是新手,需要您的帮助以帮助我更好地理解编码人员的思想.

您会看到,有一个数组,其中包含分配给可能的上载错误的键和值.我想知道这些错误将如何触发,因为我在代码的其他地方都没有找到关系.

我要努力理解的是:这些键1,2,3,...是描述PHP上传错误的标准值,还是仅仅是数字?

第二个问题,是否有另一种方法可以在不使用PHP函数且避免回显的情况下根据这种情况打印错误消息?

代码如下:

<?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

?>

解决方案

有一种情况,只是掩盖了代码的逻辑.

以这个为例:

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

$_FILES[$fieldname]['error']将求值,在这种情况下为整数. == 0是布尔逻辑检查; $_FILES[$fieldname]['error']的结果等于零吗?

如果可以,我们继续.

如果不是,那么我们下拉至下一行.

error(args)是对函数error的调用,在代码的后面定义.此函数接受3个参数,发生错误时我们将传入其中的2个.

让我们分解一下: error($errors[$_FILES[$fieldname]['error']], $uploadForm),我们确定是对error()函数的调用. $errors[$_FILES[$fieldname]['error']]是传递给该函数的第一个参数. $uploadForm是传递的第二个参数.

让我们分解第一个:

如果我要问你$errors[1]等于什么,你会说什么?好吧,[1]是数组errors的索引,在这种情况下,我要索要第一个索引号或键值,即哪个关键点是'php.ini max file size exceeded'.

因此,知道了这一点,我们现在对$errors[$_FILES[$fieldname]['error']]的含义有了新的认识.如果您回想起我之前说过的话,$_FILES[$fieldname]['error']将求值为某个整数值,并且由于该值位于[]内部,因此无论该值是什么,都将成为我们的索引或errors的键值数组.

总的来说,我们有以下代码块:

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

在运行时,我们检查$_FILES[$fieldname]['error']是否等于零.如果是这样,继续前进,就没有错误.如果不等于零,请运行第二行,该行调用error()函数,并传入具有某些索引(与引发的错误有关)和$uploadForm值的errors数组.

在没有完全看到代码的情况下,或者在不了解项目的全部上下文的情况下,很难说是天气还是不需要回声.我可以确切地告诉您该脚本在做什么,如果有帮助的话?如果没有错误,它将把用户重定向到上传成功页面.如果存在错误,即调用了error()函数,则此脚本将生成一个全新的页面,其中包含错误的详细信息.当然,还有其他方法可以做到,但这是快速简便的事情.

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

?>

解决方案

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.

这篇关于PHP Array在文件上传时触发错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆