开发者

How does this Switch statement know which case to execute? (PHP/MySQL)

Here is a code form a PHP+MySQL book I am reading and I am having trouble understanding this code. This code is about checking a file uploaded into a database. (Please excuse any spelling errors if any, I was typing it in)

Q1: How does it know which case to echo? In the whole code, there is no mention of each case.

Q2: Why 开发者_运维百科do they skip case 5?! Or does it not matter which numbers you use(so I can have case 1, case 18, case 2?)

For this statement, can you say if($_FILES['userfile']['error']=1) instead of >0? Are they the same thing?

    if($_FILES['userfile']['error']>0)
{
    echo 'Problem: ';
switch($_FILES['userfile']['error'])
{
    case 1: echo 'File exceeded upload_max_filesize';
            break;
    case 2: echo 'File exceeded max_file_size';
            break;
    case 3: echo 'File only partially uploaded';
            break;
    case 4: echo 'No file uploaded';
            break;
    case 6: echo 'Cannot upload file: no temp directory specified';
            break;
    case 7: echo 'Upload failed: Cannot write to disk';
            break;
}
exit;
}


This should help:

UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

The gist of it is that when you are handling an uploaded file, you check the error value ($_FILES['userfile']['error']) to see the status of the file. The switch statement just breaks it down by checking the possible error codes that could be present. These are basically "hardwired".


All of the error cases for file uploads are predefined in PHP. You can see their meanings here: http://php.net/manual/en/features.file-upload.errors.php


$_FILES['userfile']['error'] is just a number. The switch statement goes to the case that matches the number. So it's like a big list of if(...){goto ...;} statements. I'm guessing case 5 either never happens or doesn't matter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜