PHP发布请求

时间:2014-12-02 10:48:18

标签: php post curl httprequest

我必须使用PHP发帖请求,但我无法使其发挥作用。低html请求有效

<form action="http://example.com/form.php" method="post" id="form-success">
<input type="hidden" name="id" id="itemid" value="12345">
<input type="hidden" name="key" id="sh" value="79c830e5bf78218685a350cd5df3cdac">
<input type="submit"/>
</form>

我试过这两种方式在php中请求,但两者都不起作用。

$content = http_build_query(array('id'=>'12345','key'=>'79c830e5bf78218685a350cd5df3cdac'));

$context = stream_context_create(array(
    'http' => array(
        'method'  => 'POST',
        'content' => $content,
    )
));

$result = file_get_contents('http://example.com/form.php', null, $context);

echo $result;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/form.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('id'=>'12345','key'=>'79c830e5bf78218685a350cd5df3cdac');

$pagina = curl_exec ($ch);

echo $pagina;

没有错误消息,只知道页面未正确重定向。 有任何想法吗? 谢谢

1 个答案:

答案 0 :(得分:0)

我用这个:

function file_get_contents_post($url, $var_post = array()) {
    define('MULTIPART_BOUNDARY', '--------------------------'.microtime(true));
    $header = 'Content-Type: multipart/form-data; boundary='.MULTIPART_BOUNDARY;
    $content = '' ;

    foreach ( $var_post as $key => $value ) {
        $content .= "--".MULTIPART_BOUNDARY."\r\n".
                    "Content-Disposition: form-data; name=\"".$key."\"\r\n\r\n".
                    $value."\r\n";
    }

    $content .= "--".MULTIPART_BOUNDARY."--\r\n";

    $context = stream_context_create(array(
        'http' => array(
              'method' => 'POST',
              'header' => $header,
              'content' => $content,
        )
    ));
    return file_get_contents($url, false, $context) ;
}