首页 > 解决方案 > PHP:curl 脚本失败

问题描述

任务看起来很简单。用于身份验证的登录名(电子邮件)必须在登录请求参数中传递。在请求正文(Body)中,用户密码以UTF-8编码的字符串形式传递。

示例请求:

POST /auth/authenticate-by-pass?login=testlogin@testDomain.net HTTP/1.1
Host: somehost.ru
Body: somepassword
Cache-Control: no-cache

如果请求成功,响应将包含一个 JSON 对象

试图这样做:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://somehost.ru/auth/authenticate-by-pass?login=mylogin@mydomain.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST,           true );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "mypassword" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain', 'Host: somehost.ru')); 
            
$result=curl_exec($ch);  
$php_obj = json_decode($result, true);

print_r($php_obj);

没有结果。什么都没有显示。请帮忙。

标签: phpcurlphp-curl

解决方案


据我了解,您需要的可以很简单(如有必要,请修改标题以进一步满足您的需要):

$ch = curl_init();

$post = [
    'password' => 'xxxxxx'
];

curl_setopt($ch, CURLOPT_URL, 'http://somehost.ru/auth/authenticate-by-pass?login=mylogin@mydomain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);


$headers = array();
$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);
}

$php_obj = json_decode($result, true);
print_r($php_obj);

curl_close($ch);

推荐阅读