dpcnm2132
dpcnm2132
2014-12-14 01:33

Laravel 4未定义变量:file_destination问题

已采纳

Once I post the form with and image upload the first time it works. But when I do it again it gives me this error,

Undefined variable: file_destination

Here is all of my code that uses 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
        ));

Can someone please help me understand why I'm getting this error.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongmacuo1193 dongmacuo1193 7年前

    As @Ali Gajani wrote in the comments. $file_destination is undefined when the first if

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

    is false. So the whole code inside the if statement won't be executed. Especially the line where $file_destination gets declared.

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

    The solution is simple. Just declare $file_destination before the if statement so it will be defined no matter what.

    $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
    

    I chose null as default value. You could also use an empty string or something else. Only make sure your variables are defined.

    点赞 评论 复制链接分享

相关推荐