尝试在PHP中的文件不上传的语句 [英] try catch statement in PHP where the file does not upload
问题描述
如果上传不成功,我该怎么把这个例子变成一个try catch语句?
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ _FILES [ '文件'] [ '名']);
if(!$ move){
die('File did not upload');
} else {
//打开上传的文件提取
echoUpload Complete!;
}
这可能不是一个很好的例子,但任何帮助将是
你可以这样做。
try {
//抛出异常,如果不能移动文件
if(!move_uploaded_file(...)){
throw new Exception('Could不移动文件');
}
//对文件做更多的事情也可能会引发异常
// ...
//如果有这里
echoUpload Complete!;
} catch(Exception $ e){
die('File not not upload:'。$ e-> getMessage());
}
上面的例子是没有意义的,但你应该得到想法。请注意,您可以从任何地方(例如在使用try {}调用的函数/方法中)抛出异常,并将向上传播。
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.
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.
这篇关于尝试在PHP中的文件不上传的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!