Get json values in cURL return

2

I have three distinct servers: server A, server B, and server C. Where A registers users and stores personal information. I'm trying to log in from servers B and C into A using cURL.

I need to return the values of A to authenticate user and try to do this with an array and json_encode but I can not redeem these values to store in php strings on servers B or C.

PHP cURL

<?php
header ('Content-type: text/html; charset=UTF-8');
if(!isset($_SESSION)) session_start(); 
if(isset($_POST['name'])){
   $name = $_POST['name'];
}
if($name == "Fulano"){
    $postData = array(
     'name' => $name
);
// Initialize cURL
$ch = curl_init();

// Setup options for a cURL transfer
curl_setopt_array(
    $ch, array(
    CURLOPT_URL => 'http://servidor requisitado/login_ext.php',
    CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)',
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_COOKIEJAR => 'tmp/cookie.txt',
    CURLOPT_COOKIEFILE => 'tmp/cookie.txt',
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData,
    CURLOPT_RETURNTRANSFER, true
));

// Return web page
//return curl_exec($ch);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if($server_output != ''){

   $string = json_decode($server_output, true);
    //???????????
   }

}else{
   echo "ERR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
}

PHP login_ext.php

<?php
header ('Content-type: text/html; charset=UTF-8');

if(isset($_POST['name'])){
   $name = $_POST['name'];
   //Verificação no Banco de dados!
   $nameRequest = $fetch['name'];// Ex: Fulano!
   $sobrenomeRequest = $fetch['sobrenome'];

   if($name == $nameRequest){

      $json = array("nome"=>$name, "sobrenome"=>$sobrenomeRequest);

      echo json_encode($json);
   }
}else{
   echo "Err";
}

I have tried to do a foreach but with no results!

What is the syntax for retrieving and using these values?

    
asked by anonymous 24.05.2015 / 15:34

2 answers

2

One way to redeem these values is:

$string = json_decode($server_output);
$nome = $string->nome;
$sobrenome = $string->sobrenome;

echo $nome . " " . $sobrenome . "\n"; // Fulano Ciclano

View demonstração

    
24.05.2015 / 16:40
1

If I have correctly understood your question this way go against what you need:

// Pega o json decodificado
$jsonDecodificado = json_decode($server_output, true);

foreach($jsonDecodificado as $key => $value){
         $nome = $value;
         echo $nome.'<br />';
}

Check if a key exists in the array:

if (array_key_exists("nome",$jsonDecodificado))
  {
  //faz uma validação;
  }

I'm traversing the resulting json decoding array, done that I can print it, compare it, make assignments.

    
24.05.2015 / 16:31