php - 将 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);
解决方案
我知道这听起来像是一种非常奇怪的方法来执行请求并取回数据。注意:这个技巧只适用于 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 来处理任何事情,只是总是摆脱了这些技巧。
推荐阅读
- java - Spring Batch:如何识别导致性能下降的java方法和SQL查询?
- python - 是否可以将 event.key 设置为变量?
- css - 未渲染来自 sass 的背景图像
- struts2 - 如何自动停止base64解码
- wso2is - WSO2IS - 仅通过手机号码和 SMS OTP 验证用户,无需用户名和密码
- nginx - 将 SSL 证书绑定到端口号 -- Nginx
- python - PHP 回调等价物
- python - Python:如何仅显示按国家/地区划分的运动员人数最多的运动?
- javascript - 如何在 Intl.NumberFormat 中格式化货币符号?
- arrays - 结构中具有动态大小的 C 语言数组