Search code examples
phpcurlyii2

send file with curl to yii2 controller


I want to send a file with curl by windows command line, to a yii2 controller. My script for command line is like this:

curl  -X POST -F "file=@G:\file.txt"  http://file.localhost/file-siakadbeta/upload

and my yii2 controller is like this:

 class FileSiakadbetaController extends Controller
 {
   public function actionUpload()
   {

    if ($_FILES && isset($_FILES['file'])) {
        $target_dir = "uploads/"; // Replace with your desired upload directory
        $target_file = $target_dir . basename($_FILES['file']['name']);
        
        // Check if the file already exists
        if (file_exists($target_file)) {
            return "File already exists.";
        } else {
            // Move the uploaded file to the target directory
            if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
                return "File uploaded successfully.";
            } else {
                return "File upload failed.";
            }
        }
    } else {
        return "No file uploaded.";
    }  
  }
}

The problem is, i get response

Bad Request (#400)

I have try to send the curl command to plain php code (not use yii2 framework) and the upload code is working.

Any help?


Solution

  • The Bad Request response is probably result of missing CSRF token in POST request.

    Yii2 by default expects all POST request to include valid CSRF token. You can disable this on per controller basis by setting its $enableCsrfValidation property to false. For example like this:

    class FileSiakadbetaController extends Controller
    {
        public $enableCsrfValidation = false;
    
        public function actionUpload()
        {
             // ... action body ...
        }
    }
    

    Or if you want to disable CSRF validation only for specific action, you can do it in beforeAction() callback.

    class FileSiakadbetaController extends Controller
    {
        public function beforeAction($action)
        {
            if ($action->id == 'upload') {
                $this->enableCsrfValidation = false;
            }
            return parent::beforeAction($action);
        }
    
        public function actionUpload()
        {
             // ... action body ...
        }
    }
    

    See more about CSRF protection in documentation.