Tuesday, February 25, 2020

REST API DUA METHOD CURL dan FILE_GET_CONTENT


Untuk Kali Ini Kita Bermain dengan API , tentu dengan PHP DAN MYSQL. nah disini saya akan menjelaskan 2 method , satu dengan curl satu lagi dengan get_content. berikut kodenya :


          1. sample curl get data.

            $ch = curl_init(); //inisial curl

            curl_setopt($ch, CURLOPT_URL, 'https://example.com/json.php'); // get url
        
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); //kirim data
        
            $content = curl_exec ($ch);  //eksekusi
        
            curl_close ($ch);  //close
        
            echo json_decode($content,true);

            
          2. sample data curl post data

            define("URL","http://example.com");
              $fields = array(
              'token'=>$token,
              'key'=>$key,
              'subject'=>$subject
             );
             $d = json_encode($fields);
            $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, URL);
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
             curl_setopt($ch, CURLOPT_POSTFIELDS, $d);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
               'Content-Type: application/json',
               'Content-Length: ' . strlen($d))
                );
              $result = curl_exec($ch);
             curl_close($ch);

         3. sample data get_content , untuk contoh kasus login dengan php mysql dan java


           header("Access-Control-Allow-Origin: *");
           header("Access-Control-Allow-Credentials: true");
           header("Access-Control-Allow-Methods: POST, GET, OPTIONS"); 
         //menghindari CORS origin

           include "config.php"; // koneksi

           $post = json_decode(file_get_contents('php://input'),true); //get data dari luar php 


           if(isset($post['nik']))
          { 
            $login = mysqli_num_rows(mysqli_query($con, "SELECT * FROM tbl_user WHERE
            username='".$post['username']."' AND password='".md5($post['password'])."'"));

         if($login > 0) {
              $data = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM tbl_user WHERE
            username='".$post['username']."' AND password='".md5($post['password'])."'"));

               $result =  json_encode(array('status'=>'OK','msg'=>$data));
              echo $result;   //result

              } else {

             $result =  json_encode(array('status'=>'OK','msg'=>'User Not Exist'));
              echo $result; //result 

             }
         }else{

         $result =  json_encode(array('status'=>'OK','msg'=>'Cannot Load Data'));
         echo $result; //result 

}    





No comments:

Post a Comment

Set Cookie dan Remove Cookie dengan php vanilla.js

< html lang = "en" > < head >     < meta charset = "UTF-8" >     < meta name = "viewport...