简体   繁体   中英

PHP: curl script fails

The task seemed simple. The login (email) used for authentication must be passed in the login request parameter. In the request body (Body), the user password is passed as a string encoded in UTF-8.

Example request:

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

If the request is successful, the response will contain a JSON object

Tried to do like this:

$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);

No result. Nothing is displayed. Please help.

In my understanding what you need can be simply (please amend the headers to further suit your needs if necessary):

$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);

Solved the problem. Ken Lee and everyone else thanks for the help.

$ch = curl_init();

$post = 'mypassword';

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM