为什么POST方法不起作用?

问题描述:

我已经在跨域中发布了一些信息。我正在通过以下代码实现此功能为什么POST方法不起作用?

<?php 

    function do_post_request($sendingurl, $data, $optional_headers = null) { 

    $params = array(
     'http' => array(
     'method' => 'POST', 
     'url' => $data 
    ) 
    ); 
    if ($optional_headers !== null) { 
     $params['http']['header'] = $optional_headers; 
    } 
    $ctx = stream_context_create($params); 

    $fp = @fopen($sendingurl, 'rb', false, $ctx); 
    if (!$fp) { 
     throw new Exception("Problem with $sendingurl, $php_errormsg"); 
    } 

    $response = @stream_get_contents($fp); 
    if ($response === false) { 
     throw new Exception("Problem reading data from $sendingurl, $php_errormsg"); 
    } 

    return $response; 

    } 

    $response = do_post_request('http://mag16.playtrickz.com/testing.php','http%3A%2F%2Fwww.facebook.com'); 
    echo $response; 

但它不起作用。 在成功POST请求:它会显示它的价值 否则会显示:无数据发现。 为什么它不工作,以及如何使它们工作。

+2

“不工作”不告诉我们很多。 – Jon 2012-03-06 11:32:22

+0

没有:(更多。 – user1192439 2012-03-06 11:35:55

这是我会怎么写你的函数:

function do_post_request($url, $data = NULL, $optional_headers = NULL) { 

    // Build a body string from an array 
    $content = (is_array($data)) ? http_build_query($data) : ''; 

    // Parse the array of headers and strip values we will be setting 
    $headers = array(); 
    if (is_array($optional_headers)) { 
    foreach ($optional_headers as $name => $value) { 
     if (!in_array(strtolower($name), array('content-type', 'content-length', 'connection'))) { 
     $headers[$name] = $value; 
     } 
    } 
    } 

    // Add our pre-set headers 
    $headers['Content-Type'] = 'application/x-www-form-urlencoded'; 
    $headers['Content-Length'] = strlen($content); 
    $headers['Connection'] = 'close'; 

    // Build headers into a string 
    $header = array(); 
    foreach ($headers as $name => $value) { 
    if (is_array($value)) { 
     foreach ($value as $multi) { 
     $header[] = "$name: $multi"; 
     } 
    } else { 
     $header[] = "$name: $value"; 
    } 
    } 
    $header = implode("\r\n", $header); 

    // Create the stream context 
    $params = array(
    'http' => array(
     'method' => 'POST', 
     'header' => $header, 
     'content' => $content 
    ) 
); 
    $ctx = stream_context_create($params); 

    // Make the request 
    $fp = @fopen($url, 'rb', FALSE, $ctx); 
    if (!$fp) { 
    throw new Exception("Problem with $url, $php_errormsg"); 
    } 

    $response = @stream_get_contents($fp); 
    if ($response === FALSE) { 
    throw new Exception("Problem reading data from $url, $php_errormsg"); 
    } 

    return $response; 

} 

这已被重新建立,这样的数据发送到服务器和头部在关联数组传递。所以,你将建立一个数组,看起来像你想$_POST在远程脚本看,并把它传递,也可以通过附加头送一个数组,但功能会自动添加一个Content-TypeContent-LengthConnection头。

所以,你的请求将被称为像这样:

$data = array(
    'url' => 'http://www.facebook.com/' 
); 
$response = do_post_request('http://mag16.playtrickz.com/testing.php', $data); 
echo $response;