尝试在PHP中的文件不上传的语句 [英] try catch statement in PHP where the file does not upload

查看:112
本文介绍了尝试在PHP中的文件不上传的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白了try-catch语句的作用,但是从php.net上阅读文档,我无法在我自己的代码中实现一个。我需要一个真实的例子来帮助我理解。



如果上传不成功,我该怎么把这个例子变成一个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屋!

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