PHP + curl, HTTP POST código de ejemplo?


¿Puede alguien mostrarme cómo hacer un curl php con un POST HTTP?

Quiero enviar datos como este:

username=user1, password=passuser1, gender=1

A www.domain.com

Espero que el rizo devuelva una respuesta como result=OK. ¿Hay algún ejemplo?

Author: Vladimir Kovpak, 2010-01-26

10 answers

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");

// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);

// Further processing ...
if ($server_output == "OK") { ... } else { ... }
?>
 625
Author: miku,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-07 07:50:19

Procedimiento

// set post fields
$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];

$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

// execute!
$response = curl_exec($ch);

// close the connection, release resources used
curl_close($ch);

// do anything you want with your response
var_dump($response);

Orientado a objetos

<?php
namespace MyApp\Http;

class Curl
{
    /** @var resource cURL handle */
    private $ch;

    /** @var mixed The response */
    private $response = false;

    /**
     * @param string $url
     * @param array  $options
     */
    public function __construct($url, array $options = array())
    {
        $this->ch = curl_init($url);

        foreach ($options as $key => $val) {
            curl_setopt($this->ch, $key, $val);
        }

        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
    }

    /**
     * Get the response
     * @return string
     * @throws \RuntimeException On cURL error
     */
    public function getResponse()
    {
         if ($this->response) {
             return $this->response;
         }

        $response = curl_exec($this->ch);
        $error    = curl_error($this->ch);
        $errno    = curl_errno($this->ch);

        if (is_resource($this->ch)) {
            curl_close($this->ch);
        }

        if (0 !== $errno) {
            throw new \RuntimeException($error, $errno);
        }

        return $this->response = $response;
    }

    /**
     * Let echo out the response
     * @return string
     */
    public function __toString()
    {
        return $this->getResponse();
    }
}

// usage
$curl = new \MyApp\Http\Curl('http://www.example.com', array(
    CURLOPT_POSTFIELDS => array('username' => 'user1')
));

try {
    echo $curl;
} catch (\RuntimeException $ex) {
    die(sprintf('Http error %s with code %d', $ex->getMessage(), $ex->getCode()));
}

Nota al margen aquí: sería mejor crear algún tipo de interfaz llamada AdapterInterface por ejemplo con el método getResponse() y dejar que la clase anterior lo implemente. A continuación, siempre puede intercambiar esta implementación con otro adaptador de su gusto, sin efectos secundarios para su aplicación.

Usando HTTPS / cifrando el tráfico

Normalmente hay un problema con cURL en PHP bajo el sistema operativo Windows. Al intentar para conectarse a un endpoint protegido por https, recibirá un error que le indicará certificate verify failed.

Lo que la mayoría de la gente hace aquí es decirle a la biblioteca cURL que simplemente ignore los errores de certificado y continúe (curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);). Como esto hará que su código funcione, introduce un enorme agujero de seguridad y permite a los usuarios maliciosos realizar varios ataques en su aplicación como Man In The Middle attack o tal.

Nunca, nunca hagas eso. En su lugar, simplemente necesita modificar su php.ini y decirle a PHP dónde su archivo CA Certificate es para permitirle verificar los certificados correctamente:

; modify the absolute path to the cacert.pem file
curl.cainfo=c:\php\cacert.pem

El último cacert.pem se puede descargar de Internet o extraído de su navegador favorito. Al cambiar cualquier configuración relacionada con php.ini recuerde reiniciar su servidor web.

 183
Author: emix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-07 07:52:41

Un ejemplo vivo de usar php curl_exec para hacer un HTTP post:

Pon esto en un archivo llamado foobar.php:

<?php
  $ch = curl_init();
  $skipper = "luxury assault recreational vehicle";
  $fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
  $postvars = '';
  foreach($fields as $key=>$value) {
    $postvars .= $key . "=" . $value . "&";
  }
  $url = "http://www.google.com";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, 1);                //0 for a get request
  curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
  curl_setopt($ch,CURLOPT_TIMEOUT, 20);
  $response = curl_exec($ch);
  print "curl response is:" . $response;
  curl_close ($ch);
?>

Luego ejecútelo con el comando php foobar.php, vuelca este tipo de salida a la pantalla:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
  A mountain of content...
</body>
</html>

Así que hiciste un POST de PHP para www.google.com y le envié algunos datos.

Si el servidor hubiera sido programado para leer en las variables post, podría decidir hacer algo diferente basado en eso.

 25
Author: Eric Leschinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-21 12:48:17

Se puede llegar fácilmente con:

<?php

$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.domain.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
var_export($response);
 18
Author: Vladimir Kovpak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 05:45:33

Curl Post + Manejo de errores +Configurar encabezados [gracias a @mantas-d]:

function curlPost($url, $data=NULL, $headers = NULL) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if(!empty($data)){
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $response = curl_exec($ch);

    if (curl_error($ch)) {
        trigger_error('Curl Error:' . curl_error($ch));
    }

    curl_close($ch);
    return $response;
}


curlPost('google.com', [
    'username' => 'admin',
    'password' => '12345',
]);
 5
Author: MSS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 14:54:38

Si el formulario está utilizando redirecciones, autenticación, cookies, SSL (https), o cualquier otra cosa que no sea un script totalmente abierto esperando variables de POST, vas a empezar a rechinar los dientes muy rápido. Eche un vistazo a Snoopy , que hace exactamente lo que tiene en mente mientras elimina la necesidad de configurar una gran parte de la sobrecarga.

 5
Author: Anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 15:37:40

Aquí hay algunos códigos repetitivos para PHP + curl http://www.webbotsspidersscreenscrapers.com/DSP_download.php

Incluir en estas bibliotecas simplificará el desarrollo

<?php
# Initialization
include("LIB_http.php");
include("LIB_parse.php");
$product_array=array();
$product_count=0;

# Download the target (store) web page
$target = "http://www.tellmewhenitchanges.com/buyair";
$web_page = http_get($target, "");
    ...
?>
 3
Author: Azi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-10 08:41:58

Una respuesta más simple SI está pasando información a su propio sitio web es usar una variable DE SESIÓN. Comience la página de php con:

session_start();

Si en algún momento hay información que desea generar en PHP y pasar a la página siguiente de la sesión, en lugar de usar una variable POST, asígnela a una variable de SESIÓN. Ejemplo:

$_SESSION['message']='www.'.$_GET['school'].'.edu was not found.  Please try again.'

Luego, en la página siguiente, simplemente haga referencia a esta variable de SESIÓN. NOTA: después de usarlo, asegúrese de destruirlo, para que no persista después de que se utilizado:

if (isset($_SESSION['message'])) {echo $_SESSION['message']; unset($_SESSION['message']);}
 2
Author: user2532795,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-28 17:52:41
curlPost('google.com', [
    'username' => 'admin',
    'password' => '12345',
]);


function curlPost($url, $data) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($ch);
    if (curl_error($ch)) {
        throw new \Exception(curl_error($ch));
    }
    curl_close($ch);

    return $response;
}
 2
Author: Mantas D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-30 06:43:57

Si intenta iniciar sesión en el sitio con cookies.

Este código:

if ($server_output == "OK") { ... } else { ... }

Puede que no funcione si intenta iniciar sesión, porque muchos sitios devuelven el estado 200, pero la publicación no tiene éxito.

Una manera fácil de comprobar si el mensaje de inicio de sesión tiene éxito es comprobar si se configuran cookies de nuevo. Si en la salida tienen una cadena Set-Cookies, esto significa que las publicaciones no tienen éxito y se inicia una nueva sesión.

También el post puede tener éxito, pero el estado puede ser redirigido en su lugar 200.

Para estar seguro de que la publicación es exitosa, pruebe esto:

Siga la ubicación después de la publicación, por lo que irá a la página donde la publicación redirige a:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Y luego comprobar si existen nuevas cookies en la solicitud:

if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 

{echo 'post successful'; }

else { echo 'not successful'; }
 1
Author: Atanas Atanasov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-17 10:02:31