Press "Enter" to skip to content

php curl模拟post请求

Last updated on 2019-05-17

index.php内容

<?php
header('Content-type:text/html;charset:utf-8');
/*
* @brief 模拟post进行url请求
* @param string $url
* @param string $param
*/
function postRequest($url, $data)
{
//file_get_content
    $postdata = http_build_query($data);

    $opts     = array('http' =>
                         array(
                             'method'  => 'POST',
                             'header'  => 'Content-type: application/x-www-form-urlencoded',
                             'content' => $postdata
                         )
    );
    $context = stream_context_create($opts);
    $result  = file_get_contents($url, false, $context);
    return $result;
}
//方式一
$url  = 'http://localhost/post.php';
$data = array('name' => 111, 'pass' => 222);
var_dump(postRequest($url, $data));
//方式二
$uri = "http://localhost/post.php";
// 参数数组
$data = array(
    'name'     => 'tony',
    'password' => '123456'
);
function postRequest1($uri, $data) {
    $ch   = curl_init();
    curl_setopt($ch, CURLOPT_URL, $uri);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $return = curl_exec($ch);
    curl_close($ch);
    print_r($return);
}

postRequest1($uri, $data);

post.php内容

header("Content-type:text/html;charset=utf-8");
if (isset($_POST['name'])) {
    if (!empty($_POST['name'])) {
        echo 'hello,', $_POST['name'] . '!';
    } else {
        echo 'post data is null';
    }
}
print_r($_POST);

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *