首页 > 解决方案 > 将 Curl 转换为 Php 不发送数据

问题描述

我在 mac 终端中使用这个 Curl 代码

curl 'http://www.test.com/courses/ping' -H 'authority: www.test.com' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: */*' -H 'origin: https://www.www.test.com'  -H 'x-requested-with: XMLHttpRequest'  -H 'sec-fetch-site: same-origin' -H 'sec-fetch-mode: cors'  -H 'accept-encoding: gzip,deflate, br' --data 'course=3231';

上面的代码可以正常工作但是当转换为 PHP 时它不再工作了

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.test.com/courses/ping');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "course=3231;");

$headers = array();
$headers[] = 'Authority: www.test.com';
$headers[] = 'Pragma: no-cache';
$headers[] = 'Cache-Control: no-cache';
$headers[] = 'Accept: */*';
$headers[] = 'Origin: https://www.www.test.com';
$headers[] = 'X-Requested-With: XMLHttpRequest';
$headers[] = 'Sec-Fetch-Site: same-origin';
$headers[] = 'Sec-Fetch-Mode: cors';
$headers[] = 'Accept-Encoding: gzip,deflate, br';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
 }
curl_close($ch);

标签: phpcurl

解决方案


我知道这听起来像是一种非常奇怪的方法来执行请求并取回数据。注意:这个技巧只适用于 GET json api。

你应该可以使用这个:

<?php

$data = file_get_contents("https://example.com/file?data=something"); // run a request and get back the data

$json = json_decode($data, true); // convert the raw json data to an array to use it in php 

?>

对于 POST 请求,请查看有关 CURL 的这篇文章,也许您可​​以在这里找到您的错误:https ://www.codexworld.com/post-receive-json-data-using-php-curl/

或者:您可以使用 exec 并直接在服务器上执行 curl 命令。例子:

<?php

$data = exec("curl 'http://www.test.com/courses/ping' -H 'authority: www.test.com' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: */*' -H 'origin: https://www.www.test.com'  -H 'x-requested-with: XMLHttpRequest'  -H 'sec-fetch-site: same-origin' -H 'sec-fetch-mode: cors'  -H 'accept-encoding: gzip,deflate, br' --data 'course=3231'");

?>

我希望这对您有所帮助,我使用 php 超过 5 年,并且是 BitBiz 的首席 php 开发人员,并且从来不需要在 php 中使用 CURL 来处理任何事情,只是总是摆脱了这些技巧。


推荐阅读