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();
?>
지금 당장 getCompanyId를 변수'$ func'에 전달하려고합니다. echo $ func;을 사용할 때 아무 것도 출력하지 않습니다 –
@Ashish : CURL 요청이 잘못되었습니다! 그처럼 간단합니다. 'var_dump ($ _REQUEST)'할 수 있습니까? 거기에 q가 없다는 것을 내기하십시오. postfields의 배열 버전이 작동하지 않으면 문자열을 전달하십시오. –
당신이 옳았습니다. 'q'와 'random_fields'를 제거하면 문제가 해결되었습니다. –