Bender
Bender

Reputation: 581

Can't send file as form data using cURL

I am trying to send a cURL request via the command line. Below is my request

curl -i http://localhost/test/index.php 
-X POST 
-F "name=file.png" 
-F "content=@/var/www/html/test/file.png"

The problem I'm having is that the file isn't getting sent with the request. The name is getting sent fine but not the file. Can anyone see if I am doing anything obviously wrong?

I've check the permission on the file as I thought that might be the problem but they are fine

The backend is written using the PHP Slim framework and I'm doing the following $app->request->post('content');

Upvotes: 13

Views: 1724

Answers (3)

Vinod Tigadi
Vinod Tigadi

Reputation: 859

@Bender, use the symbol @ but make the changes to your PHP Code, such that you make use of $_FILES variable. That will help. Make sure that you provide the Full Absolute path for the cURL. Else you will get the error.

Please refer the same kind of SO Question here: File Upload to Slim Framework using curl in php

Hope this helps.

Upvotes: 0

Sri Nair
Sri Nair

Reputation: 31

There is a bug in php version 5.2.6 and lower. Verify your php version and test in latest. This might be the problem.

Upvotes: 0

Phillip
Phillip

Reputation: 13668

If you want to be able to access the file's contents using $app->request->post('content');, your curl request must use a < instead of an @ for the content field,

curl -i http://localhost/test/index.php -X POST -F "name=file.png" \
  -F "content=</var/www/html/test/file.png"

From curl's manpage:

To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

By using @, you marked the field as a file. Technically, this adds a Content-Disposition header to the field (RFC 2388, if you're interested). PHP detects that and automatically stores the field inside $_FILES instead of $_POST, as Raphaël Malié remarked in a comment, which is why you can't access the contents using $app->request->post.

You should consider to switch to using $_FILES in your backend, though, if you want to support uploading using browsers' <input type=file> elements and forms. Those always set a Content-Disposition header.

Upvotes: 9

Related Questions