Passaggio di valori $ _POST con cURL


Risposte:


167

Dovrebbe funzionare bene.

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

Abbiamo due opzioni qui, CURLOPT_POSTche attiva HTTP POST e CURLOPT_POSTFIELDSche contiene un array dei nostri dati di post da inviare. Questo può essere utilizzato per inviare dati a POST <form>s.


È importante notare che curl_setopt($handle, CURLOPT_POSTFIELDS, $data);accetta $ data in due formati e che ciò determina come verranno codificati i dati del post.

  1. $datacome array(): I dati verranno inviati in quanto multipart/form-datanon sempre accettati dal server.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
  2. $datacome stringa codificata nell'URL: i dati verranno inviati come application/x-www-form-urlencoded, che è la codifica predefinita per i dati del modulo html inviato.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));

Spero che questo aiuti gli altri a risparmiare tempo.

Vedere:


La tua nota mi ha risparmiato almeno un'ora di debug. Grazie.
— Vivek Kumar

30

Ross ha l'idea giusta per inviare il solito formato parametro / valore a un URL.

Recentemente mi sono imbattuto in una situazione in cui avevo bisogno di POST di XML come Content-Type "text / xml" senza coppie di parametri, quindi ecco come farlo:

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

Nel mio caso, avevo bisogno di analizzare alcuni valori dall'intestazione della risposta HTTP, quindi potrebbe non essere necessario impostare CURLOPT_RETURNTRANSFERo CURLOPT_HEADER.


1
Non è quello che chiede il poster, ma è proprio quello che stavo cercando, grazie!
— davr

Sono contento che qualcun altro l'abbia trovato utile.
— Mark Biek,

1
il tuo "curl_setopt ($ httpRequest, CURLOPT_HTTPHEADER, array (" Content-Type: text / xml "));" risolto qualcosa che mi ha richiesto già un paio d'ore! grazie mille :)
— Alexei Tenitski

Ciao Mark, se hai tempo, potresti darmi una mano? .. Per favore. clicca qui
— jayAnn

Speso il nostro cercando di capire perché i miei dati xml non sono stati accettati quando inviati come urlencoded. Il Content-Type e nessun urlencode mi hanno salvato. Grazie.
— Samuel,

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

3

Un altro semplice esempio PHP di utilizzo di 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
?>

Esempio trovato qui: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/

Invece di usare curl_setoptpuoi usarecurl_setopt_array .

http://php.net/manual/en/function.curl-setopt-array.php


Grazie!! - Il tuo codice curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to postmi ha fornito quello che stavo cercando :)
— asugrue15



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

1
Potresti approfondire questa risposta? Poche righe di codice non danno una risposta.
— Rich Benner

1) Specifica l'URL 2) Crea un array di parametri 3) Inizializza curl 4) imposta Opzioni richieste di curl 5) Esegui Curl 6) Chiudi Curl
— Aniket B

0
<?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.
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.