cURL请求在终端中工作,但是在PHP中运行请求时我得到错误

时间:2016-07-09 14:18:37

标签: php curl

我使用namechk.com API检查社交媒体名称是否可用(Twitter)。当我在终端中发出cURL请求时它工作正常,但是当在PHP中运行时我得到错误。

终端中的以下查询正常工作:

curl -i -H "AUTHORIZATION: Bearer xxxxxxxxxx" -H "Accept: application/vnd.api.v1+json" -d "site=twitter&username=namechk" "https://api.namechk.com/services/check.json"

遵循namechk.com上的文档,以下内容应该有效(未经修改,直接从文档中获取):

<?php

$http_options = array(
    'http' => array(
        'method' => 'POST',
        'content' => json_encode(array('site' => 'twitter', 'username' => 'namechk')),
        'header' => array("AUTHORIZATION: Bearer xxxxxxx".PHP_EOL,    "Accept: application/vnd.api.v1+json".PHP_EOL, "Content-Type: application/json".PHP_EOL)
));

$context = stream_context_create($http_options);
$contents = file_get_contents("https://api.namechk.com/services/check.json", false, $context);
$results = json_decode($contents, true);

......除非我收到错误:

Warning: file_get_contents(https://api.namechk.com/services/check.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

我使用cURL for PHP编写一个返回空的函数:

public function checkSite($username, $service) {
    $ch = curl_init('https://api.namechk.com/services/check.json');

    $headers = array(
        "AUTHORIZATION: Bearer {$this->token}",
        "Accept: application/vnd.api.v1+json",
        "Content-Type: application/json"
    );

    curl_setopt_array($ch , array(
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => array(
            'site' => $service,
            'username' => $username
        ),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => false,
        CURLOPT_FOLLOWLOCATION => true
    ));

    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
}

1 个答案:

答案 0 :(得分:0)

固定。

问题是在headers数组中,API文档的每个元素都附加了PHP_EOL。删除它,它的工作原理。