Toggle navigation
Betabeers
Foro
Empleo
Agenda
Streamers
Tests
Charlas
Cursos
Comunidades
Entrar
Acabas de votar el comentario
Portada
>
Foro
>
Desarrollo web
¿Cómo enviar datos mediante POST y CURL en PHP?
Me gusta
7520 visitas
0
Miquel Camps
27/05/2013 21:42
Muy útil por si hacemos peticiones a APIs, espero que os sirva ;)
Snippet
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query( $postdata ) );
curl_exec($curl);
curl_close($curl);
Nota
Lo que hace la función http_build_query es convertir un array('a'=>1,'b'=>2) en una cadena de texto tipo &a=1&b=2
Responder
Responder
Para comentar tienes que estar registrado.
Registrate
Publicar comentario
1
Chema
13/06/2013 04:00
Para hacerlo con JSON:
function postapi($resourcePath, $method, $body = null)
{
$url = "http://xxx/".$resourcePath;
//
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($method == "POST") {
curl_setopt($ch, CURLOPT_POST, true);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
if($body != null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
if (curl_errno($ch)) {
} else {
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);
if ($data != false) {
$result = json_decode($data);
if ($result != null) {
return $result;
}
}
return false;
}
Responder
Este sitio necesita cookies para que funcione correctamente
Aceptar Cookies
Política de cookies
Snippet
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query( $postdata ) );
curl_exec($curl);
curl_close($curl);
Nota
Lo que hace la función http_build_query es convertir un array('a'=>1,'b'=>2) en una cadena de texto tipo &a=1&b=2
13/06/2013 04:00
function postapi($resourcePath, $method, $body = null)
{
$url = "http://xxx/".$resourcePath;
//
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($method == "POST") {
curl_setopt($ch, CURLOPT_POST, true);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
if($body != null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
if (curl_errno($ch)) {
} else {
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
curl_close($ch);
if ($data != false) {
$result = json_decode($data);
if ($result != null) {
return $result;
}
}
return false;
}