¿Cómo se pasan los valores $_POST
a una página usando cURL
?
Respuesta
Debería funcionar bien.
$data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
Tenemos dos opciones aquí, lo que convierte CURLOPT_POST
POST HTTP, y en CURLOPT_POSTFIELDS
que contiene un conjunto de nuestros datos postales para enviar. Esto se puede utilizar para enviar datos al POST
<form>
s.
Es importante señalar que curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
toma los datos $ en dos formatos, y que esto determina cómo se codifican los datos de envío.
$data
comoarray()
: Los datos serán enviados comomultipart/form-data
que no siempre es aceptado por el servidor.$data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$data
como cadena codificada url: Los datos serán enviados comoapplication/x-www-form-urlencoded
, que es la codificación predeterminada para los datos de formulario HTML presentados.$data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
espero que esto ayudará a otros a ahorrar su tiempo.
Ver:
Salida this page que tiene un ejemplo de cómo hacerlo.
Ross has the right idea para PUBLICAR el formato de parámetro/valor habitual en una url.
Hace poco me encontré en una situación en la que tenía que publicar algunos XML como Content-Type "text/xml" sin ningún tipo de pares de parámetros Así que aquí está cómo hacerlo:
$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>';
$httpRequest = curl_init();
curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));
curl_setopt($httpRequest, CURLOPT_POST, 1);
curl_setopt($httpRequest, CURLOPT_HEADER, 1);
curl_setopt($httpRequest, CURLOPT_URL, $url);
curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);
$returnHeader = curl_exec($httpRequest);
curl_close($httpRequest);
En mi caso, yo necesitaba para analizar algunos valores del encabezado de respuesta HTTP, por lo que no es necesario que establezca CURLOPT_RETURNTRANSFER
o CURLOPT_HEADER
.
Esto no es lo que el póster pregunta, pero resulta que es exactamente lo que estaba buscando, ¡gracias! – davr
Me alegra que alguien más lo haya encontrado útil. –
su "curl_setopt ($ httpRequest, CURLOPT_HTTPHEADER, array (" Content-Type: text/xml "));" ¡resolvió algo que ya me llevó un par de horas! Muchas gracias :) –
Compruebe hacia fuera el cUrl PHP documentation page. Ayudará mucho más que solo con scripts de ejemplo.
$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If any HTTP authentication is needed.
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This is a sample array. You can use $arrPostData = $_POST
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your post data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // Only USE this when request JSON data.
$mixResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // Only USE this when requesting JSON data
),
// If HTTP authentication is required, use the below lines.
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));
// $mixResponse contains your server response.
Otro ejemplo de PHP sencillo de usar cURL:
<?php
$ch = curl_init(); // Initiate cURL
$url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
$output = curl_exec ($ch); // Execute
curl_close ($ch); // Close cURL handle
var_dump($output); // Show output
?>
Ejemplo encontrar aquí: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/
En lugar de utilizar curl_setopt
puede utilizar curl_setopt_array
.
¡¡Gracias !! - Su código 'curl_setopt ($ ch, CURLOPT_POSTFIELDS," var1 = value1 & var2 = value2 & var_n = value_n "); // Definir lo que desea publicar' me proporcionó lo que estaba buscando :) – asugrue15
$url='Your url'; // Specify your url
$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
¿Podría ampliar esta respuesta? Algunas líneas de código no hacen una respuesta. –
1) Especifique ur url –
1) Especifique su url 2) Cree una matriz de parámetros 3) Inicialice la curva 4) Establezca las opciones requeridas de curl 5) Ejecute Curl 6) Cierre Curl –
- 1. ¿Cómo reenviar $ _POST con PHP y cURL?
- 2. pasando credenciales en PHP cURL ayuda
- 3. ¿Cómo obtengo los valores clave de $ _POST?
- 4. tipos posibles de $ _POST y $ _GET valores
- 5. índice indefinido con $ _POST
- 6. Pasando valores al diseño en Zend Framework .....?
- 7. Pasando valores html a las funciones javascript
- 8. ASP.NET MVC AuthorizeAttribute pasando valores a ActionMethod?
- 9. Params anidados con cURL?
- 10. Imprimir $ _POST nombre de la variable junto con el valor
- 11. ¿CÓMO PUBLICAR datos JSON con PHP cURL?
- 12. $ _POST max array size
- 13. limpieza $ _POST variables
- 14. $ _POST Array del formulario html
- 15. Cargas múltiples de archivos con cURL
- 16. Cómo imprimir_r $ _POST matriz?
- 17. $ _POST para discapacitados seleccione
- 18. prevenir bombardeo $ _POST
- 19. Compilando php con curl, ¿dónde está curl instalado?
- 20. Cómo CURL Entrar con Captcha y sesión
- 21. Backbone Sync devuelve un array $ _POST vacío
- 22. Cómo usar stream_notification_callback con cURL
- 23. PHP Curl con --data bandera?
- 24. Equivalente a file_get_contents() con CURL?
- 25. CURL con PHP - Muy lento
- 26. núcleo Recargar Solr con curl
- 27. Cómo iniciar sesión con cURL con POST y Cookie
- 28. Pasando valores enum a una función en PowerShell
- 29. richfaces suggestionBox pasando valores adicionales al bean de respaldo
- 30. PHP "php: // input" vs $ _POST
Si bien esto puede responder a la pregunta en teoría, [sería preferible] (http://meta.stackexchange.com/q/8259) para incluir las partes esenciales de la respuesta aquí, y proporcione el enlace para referencia. – Nanne