问题
I am trying to get a POST result but the server has block it. I have tried with
- fsockopen
- curl
- file_get_contents
but I got a same result from the server as an eroor massage of "Access denied" .
Is there any way to get the POST results from the block server.
<?php
$post_arr = array ("regno" => "1");
$addr = 'url';
$fp = fsockopen($addr, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$req = '';
foreach ($post_arr as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&" . $key . "=" . $value;
}
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
fwrite($fp, $header);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
and also
<?php
$postdata = http_build_query(
array(
'regno' => 1
)
);
$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);
echo $result;
?>
Both the above method give me a access denied output.
回答1:
Try setting the HTTP_REFERER variable.
'header' => "Content-type: application/x-www-form-urlencoded\r\nReferer: http://urltopost\r\n",
And if that doesn't work, try to mimic more of the headers. This is what I have from looking at the Network Tab of Chrome Developer Tools:
POST /hse/result.asp HTTP/1.1
Host: urlhost
Connection: keep-alive
Content-Length: 17
Cache-Control: max-age=0
Origin: url
User-Agent: something
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: url
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: ASPSESSIONIDASRCTADA=FBHLDODAOCBACEKMNFLJIMGO
Edited to include working code: If you replace the $opts definition in your second code snippet with this, it will work. It works for me.
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n"
."Referer: url\r\n",
'content' => $postdata
)
);
Full code:
<?php
$postdata = http_build_query( array( 'regno' => 1 ) );
$opts = array('http' => array( 'method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n" ."Referer: urltopost\r\n", 'content' => $postdata ) );
$context = stream_context_create($opts);
$result = file_get_contents('urltopost', false, $context);
echo $result;
?>
来源:https://stackoverflow.com/questions/10577316/how-to-set-post-data-to-url-and-get-results-in-string-variable