开发者

How can I forward $_POST with PHP and cURL?

I receive a P开发者_开发知识库OST request at my PHP script and would like to forward this POST call to another script using POST too. How can I do this?

I can use cURL if it's required for this action.


Perhaps:

curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);

From curl_setopt:

This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.


Do this,

curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($_POST));


Here's a fully functional cURL request that re-routes $_POST where you want (based on ZZ coder's reply)

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://urlOfFileWherePostIsSubmitted.com");
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    // ZZ coder's part
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
    $response = 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 need any HTTP authentication

    $username = 'http-auth-username';
    $password = 'http-auth-password';

    $requestType = 'POST'; // This can be PUT or POST

    // This can be $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 requesting JSON data

    $arrResponse = 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 request json data
        ),
        // If HTTP authentication is required , use the below lines
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD  => $username. ':' . $password
    ));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜