$data = array(
"num" => $_GET["num"]
);
$url = "https://otroservidor.com/pruebas/curl/test.php";
$ch = curl_init($url);
$datosJSON = json_encode($data);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $datosJSON);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Para llamarlo:http://localhost/pruebas/curl/sendAndGet/?num=124
En test.php del otro servidor:
header("Content-Type:application/json");
$data = json_decode(file_get_contents('php://input'), true);
foreach ($data as $clave=>$valor) {
echo "<h2>La tabla de multiplicar de ".$valor." es:</h2>";
for ($i=1;$i<=10;$i++) {
echo $valor." * ".$i." = ".$valor*($i)."<br>";
}
}
Otro ejemplo:
// add User
$url = "https://otroservidor.com/pruebas/curl/add_user.php ";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$parametros = '{
"nombre": "Pepito",
"apellidos": "Pérez García",
"edad": "27",
"ciudad": "Madrid",
"email": "pepitoperez@gmail.com"
}';
curl_setopt( $ch, CURLOPT_POSTFIELDS, $parametros);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
en add_user.php del otro servidor:
header("Content-Type:application/json");
$data = json_decode(file_get_contents('php://input'), true);
$host_name = "localhost";
$database = "mibasededatos";
$user_name = "root";
$password = "12345678";
$cnn = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno()) {
echo "ERROR AL conectar: " . mysqli_connect_error();
}
else {
// echo "TODO BIEN<hr>";
}
$sql = "insert into usuarios(nombre, apellidos, edad,ciudad,email) values ('".$data["nombre"]."','".$data["apellidos"]."','".$data["edad"]."','".$data["ciudad"]."','".$data["email"]."')";
$result = mysqli_query($cnn, $sql);
echo $result;
No hay comentarios:
Publicar un comentario