拉拉维尔 4 未定义的变量:file_destination问题


Laravel 4 Undefined variable: file_destination issue

一旦我第一次发布表单并上传图像,它就可以工作。但是当我再次这样做时,它给了我这个错误,

Undefined variable: file_destination

以下是我所有使用 file_destination 的代码:

if(isset($_FILES['img'])) {
            $file = $_FILES['img'];
            // File properties
            $file_name = $file['name'];
            $file_tmp = $file['tmp_name'];
            $file_size = $file['size'];
            $file_error = $file['error'];
            // Work out the file extension
            $file_ext = explode('.', $file_name);
            $file_ext = strtolower(end($file_ext));
            $allowed = array('png', 'jgp', 'jpeg', 'gif');
            if(in_array($file_ext, $allowed)) {
                if($file_error === 0) {
                    if($file_size <= 180000000) {
                        $file_name_new = uniqid('', true) . '.'  . $file_ext;
                        $file_destination = 'img/content-imgs/' . $file_name_new;
                        if (move_uploaded_file($file_tmp, $file_destination)) {
                            echo '<img src="' .$file_destination. '">';
                        }
                    }
                }
            }
        }   
        $title  = Input::get('title');
        $slug   = Input::get('slug');
        $body   = Markdown::parse(Input::get('body'));
        $draft  = Input::get('draft');
        $created_at = date("Y-m-d H:i:s");
        $updated_at = date("Y-m-d H:i:s");
        $post = DB::table('posts')
            ->insert(array(
                'title' => $title,
                'slug' => $slug,
                'body' => $body,
                'img' => $file_destination,
                'draft' => $draft,
                'created_at' => $created_at,
                'updated_at' => $updated_at
        ));

有人可以帮助我理解为什么我会收到此错误。

正如@Ali Gajani在评论中写道。 $file_destination当第一个 if

if(isset($_FILES['img'])) {

是假的。因此,if 语句中的整个代码不会被执行。尤其是声明$file_destination的那条线。

$file_destination = 'img/content-imgs/' . $file_name_new;

解决方案很简单。只需在 if 语句之前声明 $file_destination,这样无论如何都会定义它。

$file_destination = null;
if(isset($_FILES['img'])){
    // ...
    $file_destination = 'img/content-imgs/' . $file_name_new;
    // ...
}
// now $file_destination either is null or contains the path

我选择null作为默认值。您也可以使用空字符串或其他内容。只确保定义了变量。