Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

Retrieve data from CURL "-d" using PHP

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.

question from:https://stackoverflow.com/questions/65901813/retrieve-data-from-curl-d-using-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...