从cURL POST请求中读取值

时间:2013-05-23 01:57:04

标签: php curl

我正在尝试使用PHP中的cURL发出POST请求。我有代码来发出POST请求(来自 index.php ),我相信它是正确的。

下一部分是API层( api.php ),它需要从POST请求中提取数据,这就是我遇到问题的地方。在代码中,我试图读取我使用index.php传递的参数q的值。

这是两个文件的代码。

的index.php

<?php
    $handle = curl_init();
    curl_setopt_array(
        $handle,
        array(
            CURLOPT_URL => 'http://localhost:8888/restAPI/api.php',
            'q' => 'getCompanyId',
            'post_fields' => 'q=getCompanyId',
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => array(
                'q' => 'getCompanyId'
            ),
            CURLOPT_RETURNTRANSFER => true
        )
    );
    $response = curl_exec($handle);
    curl_close($handle);
?>

api.php

<?php
    require_once("Rest.inc.php");

    class API extends REST {

        public function processApi() {

            $func = $_REQUEST['q'];

            if((int)method_exists($this,$func) > 0){
                $this->$func();
            }
            else{
                $this->response('',404); 
            // If the method not exist with in this class, response would be "Page not found".
            }
        }
        public function getCompanyId(){
            $dbhost = 'localhost:8888';
            $conn = mysql_connect($dbhost, 'root', 'root');

            if (! $conn) {
                die('Could not connect - ' . mysql_error());
            }

            $sql = 'SELECT companyId FROM Companies';
            mysql_select_db('IRSocialBackend');
            $executeSql = mysql_query($sql);

            while($data = mysql_fetch_array($executeSql)){
                echo $data['companyId'];
            }

        }
    }
    //echo "here";
    $api = new API;
    $api -> processApi();
?>

1 个答案:

答案 0 :(得分:0)

请注意:您的API不是RESTFUL。 REST不是“发出HTTP请求”的问题。阅读它!

第一个错误:

       array(
        CURLOPT_URL => 'http://localhost:8888/restAPI/api.php',
        'q' => 'getCompanyId',
        'post_fields' => 'q=getCompanyId',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => array(
            'q' => 'getCompanyId'
        ),
        CURLOPT_RETURNTRANSFER => true
    )

随机“q”和“post_fields”肯定如何向curlopt添加字段。

api.php 中,您可以指定以下内容:

$dbhost = 'localhost:8888';
        $conn = mysql_connect($dbhost, 'root', 'root');

我认为localhost:8888是你的网络服务器? localhost:3306将是你的MySQL服务器,如果它在默认端口上。

如果不知道您的表/数据库结构,其余部分很难调试。

相关问题