This question is not about how to use CURL in PHP. But how to retrieve data that send using CURL with “-d” option.
This command:
curl -H 'Content-Type: text/plain; charset=utf-8' -d 'Hello, World!' -X POST http://localhost:8080
will produce empty array in $_POST variable.
Does anyone know? Thank you.
Advertisement
Answer
I think this is a header conflict. You trying to send text/plain
but is not form
.
Let’s try to create a php
file:
<?php var_dump($_SERVER); var_dump($_POST); var_dump(file_get_contents('php://input')); ?>
run built-in server php -S localhost:8000 path_to_file.php
curl -d 'Hello, World!' -X POST http://localhost:8000 # ... # ["CONTENT_TYPE"]=> # string(33) "application/x-www-form-urlencoded" < --- FORM # ["HTTP_CONTENT_TYPE"]=> # string(33) "application/x-www-form-urlencoded" # ... # array(1) { < ---- DATA HERE # ["Hello,_World!"]=> # string(0) "" # } # string(13) "Hello, World!" < ---- AND INPUT HERE curl -H 'Content-Type: text/plain; charset=utf-8' -d 'Hello, World!' -X POST http://localhost:8000 # ... # ["CONTENT_TYPE"]=> # string(25) "text/plain; charset=utf-8" < ------ TEXT # ["HTTP_CONTENT_TYPE"]=> # string(25) "text/plain; charset=utf-8" # ... # array(0) { < ---- EMPTY # } # string(13) "Hello, World!" < ---- BUT INPUT HERE
Let’s try to send multipart/form-data
:
curl -F key1=val1 -F key2=val2 -X POST http://localhost:8000 # ... FORM ....... # ["CONTENT_TYPE"]=> # string(70) "multipart/form-data; boundary=------------------------2abad5506f8862a5" # ["HTTP_CONTENT_TYPE"]=> # string(70) "multipart/form-data; boundary=------------------------2abad5506f8862a5" # ["REQUEST_TIME_FLOAT"]=> # ... # array(2) { < ------ DATA HERE # ["key1"]=> # string(4) "val1" # ["key2"]=> # string(4) "val2" # } # string(0) "" <- BUT INPUT EMPTY
Let’s try with json
:
curl --header "Content-Type: application/json" --request POST --data '{"hey":"joe"}' http://localhost:8000 # array(0) { < ----- EMPTY # } # string(13) "{"hey":"joe"}" < ----- INPUT HERE
So I think in your case the main reason for this behavior is request headers