2013-05-23 2 views
0

PHP에서 cURL을 사용하여 POST 요청을하려고합니다. POST 요청 (코드 index.php)을 만들려면 코드가 있어야하며 올바른 것으로 믿습니다.cURL POST 요청에서 값 읽기

다음 부분은 POST 요청에서 데이터를 추출해야하는 API 레이어 (api.php)이며 여기서 문제가되는 부분입니다. 코드에서 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(); 
?> 

답변

0

그냥 보조 노트 : 당신의 API가 편안하지 않습니다. 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에 필드를 추가하는 방법을 확실히 하지입니다.

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

내가 로컬 호스트를 생각 : : 8888은 웹 서버이었다 api.php에서

, 다음과 같은 지정? localhost : 3306이 기본 포트에 있으면 MySQL 서버가됩니다.

나머지는 테이블/DB 구조를 알지 못하면 디버그하기가 어렵습니다.

+0

지금 당장 getCompanyId를 변수'$ func'에 전달하려고합니다. echo $ func;을 사용할 때 아무 것도 출력하지 않습니다 –

+0

@Ashish : CURL 요청이 잘못되었습니다! 그처럼 간단합니다. 'var_dump ($ _REQUEST)'할 수 있습니까? 거기에 q가 없다는 것을 내기하십시오. postfields의 배열 버전이 작동하지 않으면 문자열을 전달하십시오. –

+0

당신이 옳았습니다. 'q'와 'random_fields'를 제거하면 문제가 해결되었습니다. –