Ajay
Ajay

Reputation: 9

json_decode in PHP to set a cookie

I want to decode Json returned from the WebService, And it should set a cookie, that i want to use to call next WebService API. I am not sure how to set a cookie, and decode this json.

I tried decoding it, but get the error. I need to extract sessionId. You can use the WebService.. I have put this on Internet.

Here is my code sample

 <?php //extract data from the post
       extract($_POST); //set POST variables
       $url = 'http://202.83.243.119/ems/loginByEID.json';
       $fields = array(
                   'eid'=>urlencode("7ea888b6-36e9-49db-84f3-856043841bef")
               );
      //url-ify the data for the POST
       foreach($fields as $key=>$value) {
       $fields_string .=
       $key.'='.$value.'&'; }
       rtrim($fields_string,'&');

       //open connection $ch = curl_init();

       //set the url, number of POST vars,
       POST data
       curl_setopt($ch,CURLOPT_URL,$url);
       curl_setopt($ch,CURLOPT_POST,count($fields));
       curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

       //execute post $result =
       curl_exec($ch);

       //close connection curl_close($ch);  
       //decoding Json $obj =
       json_decode($result);

       print $obj->{'stat'};  

       ?>

Upvotes: 0

Views: 1624

Answers (1)

janmoesen
janmoesen

Reputation: 8020

  1. Use setcookie() to set a cookie.
  2. Avoid extract() like the plague; it can be used to introduce any client-specified variables into your code.
  3. Use $fields_string = http_build_query($_GET) to build a query string instead of your hodge-podge above.
  4. Format your code properly. For example, you put the $obj = inside the previous comment line.

Upvotes: 4

Related Questions