【问题标题】:PHP post Rest APIPHP 发布 Rest API
【发布时间】:2015-06-17 18:48:00
【问题描述】:

我整天都在搜索从 php 页面调用我的 api 发生了什么,但找不到有效的解决方案。 很简单,我有一个需要 2 个参数的 rest api,它返回一条 json 消息。 例如,从邮递员那里调用 api,它工作正常。 从我的 php 页面调用,它会阻塞我的网络服务器,直到超时。

我的块是(在 SO 上找到的块之一):

        $url = HOST . '/users/verifyemail';
        $userID = $_GET['userID'];
        $key = $_GET['key'];            

        $postdata = http_build_query(
            array(
                'userID' => $userID,
                'apiKey' => $key
            )
        );              

        try
        {

            $opts = array('http' =>
                array(
                    'method'  => 'POST',
                    'header'  => 'Content-Type: application/x-www-form-urlencoded',
                    'content' => $postdata
                )
            );
            $context  = stream_context_create($opts);

            $response = file_get_contents($url, false, $context);
            if ($response) {
                echo "OK";
            } else {
                echo "NOK !";
            }
        } catch (Exception $ex) {
            echo $ex;
        }  

甚至不调用 catch。

在我的网络服务器中,我有这个:

[Wed Jun 17 20:39:18 2015] ::1:52312 [200]: /emailValidation.php?userID=16&key=1212
[Wed Jun 17 20:39:18 2015] ::1:52313 [200]: /users/verifyemail

因为一切都很好......

My PHPInfo

有什么想法吗?

谢谢!

【问题讨论】:

  • 你的常量 HOST 是什么,$url 的“输出”是什么
  • 是的。甚至放置我的 index.php/.完全没有错误。
  • 你是在命令行中使用 php 构建,而不是使用 apache 或类似的东西

标签: php rest post restful-url


【解决方案1】:

请尝试 php-curl:

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => "$url",
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        userID => "$userID",
        apiKey => "$key",
    )

));

$response = curl_exec($curl);
curl_close($curl);

【讨论】:

  • $response 总是错误的,我的网络服务器给了我 [2015 年 6 月 17 日星期三 21:00:26] ::1:53447 无效请求(意外 EOF)
  • 好的,你在运行 Apache2 吗?
  • MacBook-Air:etc user$ httpd -v 服务器版本:Apache/2.4.10 (Unix) 服务器构建时间:2015 年 5 月 19 日 16:46:25
  • 好的,我明白了。你是如何安装 php 的,你在运行 php5 吗?您必须安装 php5-curl 才能发出 curl 请求。
  • 您能否制作一个示例 php 文件并将其添加到其中:<?php phpinfo(); ?>。然后用你的浏览器转到那个页面,看看你是否能找到一个单独的框,标题是“curl”。将屏幕截图编辑到我的帖子中。
【解决方案2】:

事实上,Kasper Franz 是对的。 即使将 PHP 作为第三方安装在我的 mac 中,它也使用内置实例,问题出在单线程上。

更改配置解决了问题。

也感谢 AirPet 的及时帮助 ;-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2016-02-10
    • 2018-08-23
    • 2015-04-27
    • 2019-03-05
    • 2016-09-01
    相关资源
    最近更新 更多