第一种方法:file_get_contents模拟post提交

代码如下:

<?php
$data = array (\'foo\' => \'manongjc\');
$data = http_build_query($data);
$opts = array (
\'http\' => array (
\'method\' => \'POST\',
\'header\'=> \"Content-type: application/x-www-form-urlencodedrn\" .
\"Content-Length: \" . strlen($data) . \"rn\",
\'content\' => $data
)
);
$context = stream_context_create($opts);
$html = file_get_contents(\'http://xxx.com/post.php\', false, $context);
echo $html;
?>

 

第二种方法:curl模拟post提交

代码如下:

<?php
$uri = \"http://www.xxx.com/post.php\";
// 参数数组
$data = array (
        \'name\' => \'manongjc\',
        \'password\' => \'manongjc\'
);
 
$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);

 

第三种方法:socket模拟post提交

代码如下:

<?php
function socket_post($url, $post) {
    $urls = parse_url($url);
    if (!isset($urls[\'port\'])) {
        $urls[\'port\'] = 80;
    }

    $fp = fsockopen($urls[\'host\'], $urls[\'port\'], $errno, $errstr);
    if (!$fp) {
        echo \"$errno, $errstr\";
        exit();
    }

    $post = http_build_query($post);
    $length = strlen($post);
    $header = <<<HEADER
POST {$urls[\'path\']} HTTP/1.1
Host: {$urls[\'host\']}
Content-Type: application/x-www-form-urlencoded
Content-Length: {$length}
Connection: close
{$post}
HEADER;

    fwrite($fp, $header);
    $result = \'\';
    while (!feof($fp)) {
        $result .= fread($fp, 512);
    }
    $result = explode(\"\\r\\n\\r\\n\", $result, 2);
    return $result[1];
}

$data = socket_post(\"http://www.xxx.com/post.php\", array(\'name\'=>\'manongjc\', \'email\'=>\'manongjc@gmail.com\'));

var_dump($data);

 

收藏 打印