Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

exception - try catch statement in PHP where the file does not upload

I understand what try-catch statements do, but from reading the documentation on php.net, I would not be able to implement one into my own code. I need a real example to help me understand.

How can I turn this example into a try-catch statement, if the upload was not successful?

$move = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$_FILES['file']['name']);

if (!$move) {
    die ('File didn't upload');
} else {            
    //opens the uploaded file for extraction
    echo 'Upload Complete!';
}

This may not be a good example to work with, but any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do it like this.

try {
    //throw exception if can't move the file
    if (!move_uploaded_file( ... )) {
        throw new Exception('Could not move file');
    }

    //do some more things with the file which may also throw an exception
    //...

    //ok if got here
    echo "Upload Complete!";
} catch (Exception $e) {
    die ('File did not upload: ' . $e->getMessage());
}

It is a bit pointless for the above example, but you should get the idea. Note that you can throw the exception(s) from anywhere (e.g. within a function/method that you call from withing the try{}) and they will propagate upwards.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...