복붙노트

PHP를 사용하여 JSON POST 읽기

카테고리 없음

PHP를 사용하여 JSON POST 읽기

나는이 질문을 게시하기 전에 주위를 둘러 보았습니다. 그래서 다른 게시판에 있다면 사과드립니다.이 질문은 올바르게 서식을 지정하지 않으면 사과로 처리됩니다.

게시 된 값을 가져와 JSON 인코딩 된 배열을 반환해야하는 정말 간단한 웹 서비스가 있습니다. 그 모든 내용은 application / json의 content-type으로 양식 데이터를 게시해야 할 때까지 모두 잘 돌아갔다. 그 이후로 나는 웹 서비스로부터 어떠한 값도 리턴 할 수 없으며, 분명히 포스트 값을 필터링하는 방법과 관련이 있습니다.

기본적으로 내 로컬 설치 프로그램에서 다음을 수행하는 테스트 페이지를 만들었습니다.

$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);                                                                  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($curl, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data))                                                                       
);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

웹 서비스에서이 기능을 제거했습니다.

<?php

header('Content-type: application/json');

/* connect to the db */
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('webservice',$link) or die('Cannot select the DB');

if(isset($_POST['action']) && $_POST['action'] == 'login') {
    $statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail');
    $posts[] = array('status'=>$statusCode);
    header('Content-type: application/json');
    echo json_encode($posts);

    /* disconnect from the db */
}
@mysql_close($link);

?>

기본적으로 나는 $ _POST 값이 설정되지 않았기 때문에 그것이 $ _POST 대신에 넣어야하는 것을 찾을 수 없다는 것을 알고 있습니다. 나는 노력했다. json_decode ($ _ POST), file_get_contents ( "php : // input") 및 기타 여러 가지 방법을 사용했지만 어둠 속에서 촬영을하고있었습니다.

어떤 도움이라도 대단히 감사하겠습니다.

고마워, 스티브

덕분에 도움을 주신 Michael, 확실한 진보를 보였습니다. 게시물을 반향 할 때 적어도 지금은 repsonse가 있습니다 .... 그것이 null 일지라도

업데이트 된 CURL -

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
  curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

데이터가 게시되는 페이지에서 php를 업데이트했습니다.

$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array

print_r(json_encode($input));

적어도 내가 말했듯이 지금은 빈 페이지를 반환하기 전에 응답을 보았습니다.

해결법

  1. ==============================

    1.

    $ _POST가 비어 있습니다. 웹 서버가 json 형식으로 데이터를보고 싶다면 원시 입력을 읽고 JSON 디코딩으로 파싱해야합니다.

    당신은 그런 것을 필요로합니다 :

    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    

    또한 JSON 통신을 테스트하는 코드가 잘못되었습니다 ...

    CURLOPT_POSTFIELDS는 매개 변수를 application / x-www-form-urlencoded로 인코딩하도록 curl에 지시합니다. 여기에 JSON 문자열이 필요합니다.

    최신 정보

    테스트 페이지의 PHP 코드는 다음과 같아야합니다.

    $data_string = json_encode($data);
    
    $ch = curl_init('http://webservice.local/');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
    );
    
    $result = curl_exec($ch);
    $result = json_decode($result);
    var_dump($result);
    

    또한 웹 서비스 페이지에서 header ( 'Content-type : application / json'); 행 중 하나를 제거해야합니다. 한 번만 호출해야합니다.

  2. ==============================

    2.

    안녕하세요 이것은 json 형식으로 회신하는 일부 무료 IP 데이터베이스 서비스에서 IP 정보를 얻기 위해 말풍선을 사용하는 광산의 오래된 프로젝트에서 발췌 한 것입니다. 나는 그것이 당신을 도울 것 같아요.

    $ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
    
    getUserLocation($ip_srv);
    

    기능:

    function getUserLocation($services) {
    
            $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
    
            for ($i = 0; $i < count($services); $i++) {
    
                // Configuring curl options
                $options = array (
                    CURLOPT_RETURNTRANSFER => true, // return web page
                    //CURLOPT_HEADER => false, // don't return headers
                    CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                    CURLOPT_FOLLOWLOCATION => true, // follow redirects
                    CURLOPT_ENCODING => "", // handle compressed
                    CURLOPT_USERAGENT => "test", // who am i
                    CURLOPT_AUTOREFERER => true, // set referer on redirect
                    CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                    CURLOPT_TIMEOUT => 5, // timeout on response
                    CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
                ); 
    
                // Initializing curl
                $ch = curl_init($services[$i]);
                curl_setopt_array ( $ch, $options );
    
                $content = curl_exec ( $ch );
                $err = curl_errno ( $ch );
                $errmsg = curl_error ( $ch );
                $header = curl_getinfo ( $ch );
                $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
    
                curl_close ( $ch );
    
                //echo 'service: ' . $services[$i] . '</br>';
                //echo 'err: '.$err.'</br>';
                //echo 'errmsg: '.$errmsg.'</br>';
                //echo 'httpCode: '.$httpCode.'</br>';
                //print_r($header);
                //print_r(json_decode($content, true));
    
                if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
    
                    return json_decode($content, true);
    
                } 
    
            }
        }
    
  3. ==============================

    3.

    당신은 당신의 json을 매개 변수에 넣고 헤더에 json만을 넣는 대신 그것을 보낼 수 있습니다 :

    $post_string= 'json_param=' . json_encode($data);
    
    //open connection
    $ch = curl_init();
    
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
    curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call
    
    //execute post
    $result = curl_exec($curl);
    
    //see the results
    $json=json_decode($result,true);
    curl_close($curl);
    print_r($json);
    

    서비스 측면에서 json 문자열을 매개 변수로 가져올 수 있습니다.

    $json_string = $_POST['json_param'];
    $obj = json_decode($json_string);
    

    변환 된 데이터를 오브젝트로 사용할 수 있습니다.

  4. from https://stackoverflow.com/questions/19004783/reading-json-post-using-php by cc-by-sa and MIT lisence