如何检索 URL 端点内的 cURL 数据

How to Retrieve cURL Data within the URL Endpoint

我正在尝试创建一个 cURL api,假设下面是我的 curl 请求代码,其中 http://localhost/api/endpoint.php 是我的端点。 endpoint.php 文件中的代码实际会发生什么?如何在 endpoint.php 页面中实际获取通过 cURL 请求发送的数据,例如 CURLOPT_USERPWD 数据?谢谢

$ch = curl_init();
$url = 'http://localhost/api/endpoint.php';

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERPWD, 'alex:password123');

$headers = array(
        'Accept: application/json',
        'Content-Type: application/x-www-form-urlencoded',
        'Accept-Language: en_US'        
);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$vars['grant_type'] = 'client_credentials';

$req = http_build_query($vars);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);

$response = curl_exec($ch);

您可以通过 $_SERVER superglobal 访问这些数据。

端点:

<?php

$user     = $_SERVER['PHP_AUTH_USER']; // alex
$password = $_SERVER['PHP_AUTH_PW'];   // password123

在您的文件 endpoint.php 中,您可以使用

打印您发布的值
print_r($_POST);

在你的 curl 打印响应之后

print_r($response);