example php http curl http-post

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



php curl request header (10)

Procesal

// 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 AdapterInterface 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. Entonces, 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

Por lo general, hay un problema con cURL en PHP en el sistema operativo Windows. Al intentar conectarse a un punto final protegido https, recibirá un error que le indicará que la certificate verify failed .

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

Nunca, nunca hagas eso. En su lugar, simplemente necesita modificar su php.ini e indicar a PHP dónde está el archivo de CA Certificate 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 puede descargarse de Internet o extraerse de su navegador favorito . Al cambiar cualquier configuración relacionada con php.ini recuerde reiniciar su servidor web.

¿Alguien me puede mostrar cómo hacer un enrollamiento php con un HTTP POST?

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?


Un ejemplo en vivo de usar php curl_exec para hacer una publicación HTTP:

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, php foobar.php con el comando php foobar.php , esto arroja 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 en www.google.com y enviaste algunos datos.

Si el servidor hubiera sido programado para leer las variables de publicación, podría decidir hacer algo diferente en función de eso.


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, ""); ... ?>


Mensaje de Curl + Manejo de errores + Encabezado de conjunto [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'', ]);


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);


Si el formulario utiliza redirecciones, autenticación, cookies, SSL (https), o cualquier otra cosa que no sea un script totalmente abierto que espera las variables POST, usted comenzará a lavarse los dientes muy rápido. Eche un vistazo a Snoopy , que hace exactamente lo que tiene en mente al mismo tiempo que elimina la necesidad de configurar una gran cantidad de gastos generales.


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

Este codigo

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

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

Una forma sencilla de verificar si la publicación de inicio de sesión es exitosa es verificar si está configurando cookies nuevamente. Si en la salida tiene una cadena Set-Cookies, esto significa que las publicaciones no tienen éxito y se inicia una nueva sesión.

También la publicación puede tener éxito, pero el estado puede ser redirigido en lugar de 200.

Para asegurarse de que la publicación sea exitosa, intente 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 a continuación comprobar si existen nuevas cookies en la solicitud:

if (!preg_match(''/^Set-Cookie:/s*([^;]*)/mi'', $server_output)) {echo ''post successful''; } else { echo ''not successful''; }


Una respuesta más simple SI está pasando información a su propio sitio web es utilizar una variable SESSION. Comenzar 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, asigne una variable SESSION. 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 SESSION. NOTA: después de usarlo, asegúrese de destruirlo, para que no persista después de usarlo:

if (isset($_SESSION[''message''])) {echo $_SESSION[''message'']; unset($_SESSION[''message'']);}


<?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 { ... } ?>


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; }