POST and GET without cURL PHP - php

I tried some times release POST and GET in this site http://www.sefaz.pe.gov.br/sintegra, but it doesn´t work
// POST
$data = array('CNPJ' => '02340534000192', 'consulta' => 'OK', 'vazio' => '');
$html = $this->HTTP_Post('http://www.sefaz.pe.gov.br/sintegra/consulta/consulta.asp', $data, $cookie);
$arr = split("Set-Cookie:", $html);
$cookie="";
$count=1;
while ($count < count($arr))
{
$cookie.=substr($arr[$count].";", 0, strpos($arr[$count].";",";")+1);
$count++;
}
// GET after POST
echo $this->get_url('http://www.sefaz.pe.gov.br/sintegra/consulta/exibirResultado.asp', $cookie);
I tried file_get_contents and curl too... both without success
function get_url($url,$cookie=false)
{
$url = parse_url($url);
$query = $url[path]."?".$url[query];
echo "Query:".$query;
$fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
if (!$fp)
{
return false;
}
else
{
$request = "GET $query HTTP/1.1\r\n";
$request .= "Host: $url[host]\r\n";
$request .= "Connection: Keep-Alive\r\n";
if($cookie) $request.="Cookie: $cookie\n";
$request.="\r\n";
fwrite($fp,$request);
while (!feof($fp))
{
$result .= fgets($fp, 128);
}
fclose($fp);
return $result;
}
}
function HTTP_Post($URL,$data,$cookie, $referrer="")
{
$URL_Info=parse_url($URL);
if($referrer=="") $referrer="111";
foreach($data as $key=>$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);
if(!isset($URL_Info["port"]))
$URL_Info["port"]=80;
$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
$request.="Host: ".$URL_Info["host"]."\n";
$request.="Referer: $referer\n";
$request.="Content-type: application/x-www-form-urlencoded\n";
$request.="Content-length: ".strlen($data_string)."\n";
$request.="Connection: Keep-Alive\n";
$request.="Cookie: $cookie\n";
$request.="\n";
$request.=$data_string."\n";
$fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
fputs($fp, $request);
while(!feof($fp))
{
$result .= fgets($fp, 1024);
}
fclose($fp);
return $result;
}
functions GET and POST with fsocket.
any ideas are welcome
Thanks
EDIT 1:
Thank you, but it doesn´t work. I tried 20 times, but this website doesn´t work...
The browser message appears: Atenção: Acesso negado! Favor selecionar algum parâmetro de consulta.
Caution: Access Denied! Please select a query parameter.
my code with your code
function POST()
{
$postdata = http_build_query(
array(
'CNPJ' => '02340534000192',
'consulta' => 'OK',
'vazio' => '',
'CPF' => '',
'IE' => '',
'razaosocial' => ''
));
$headers = array(
'Content-type: application/x-www-form-urlencoded',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => $postdata,
));
$context = stream_context_create($opts);
$result = file_get_contents('http://www.sefaz.pe.gov.br/sintegra/consulta/consulta.asp', false, $context);
return $result;
}

I think you can do file_get_contents for GET
or http://php.net/manual/en/context.http.php for POST
Example from php.net website
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$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('http://example.com/submit.php', false, $context);

Your IP is probably blocked by the website.

Related

dynamic site in file_get_contents

problem , Crossing the CAPTCHA in dynamic site .. :(
problem link action form in https://edu.uast.ac.ir ..
sorry My English is not good.
please test my code :
my source code :
a.php
<?php
echo file_get_contents("https://edu.uast.ac.ir");
?>
b.php
<?php
$a = $_POST["captcha_first_page"];
$postdata = http_build_query(
array(
'captcha_first_page' => $a
)
);
$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('https://edu.uast.ac.ir/user/user_manage/userLogin/', false, $context);
echo $result;
?>
please help me
You have to replace the form action, too, cause if not the submitted form want posted to your b.php.
captcha-a.php
<?php
$content = file_get_contents("https://edu.uast.ac.ir");
$content = str_replace('https://edu.uast.ac.ir/user/user_manage/userLogin/','captcha-b.php', $content);
echo $content;
captcha-b.php
<?php
function redirect_post($url, array $data, array $headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
// replace
$headers['Host'] = "edu.uast.ac.ir";
$headers['Origin'] = "https://edu.uast.ac.ir";
$headers['Referer'] = "https://edu.uast.ac.ir";
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if ($fp) {
return stream_get_contents($fp);
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
setlocale(LC_ALL, "en_US.UTF8");
echo redirect_post("https://edu.uast.ac.ir/user/user_manage/userLogin/" ,$_POST, getallheaders());
This should be a good starting point. Don't know if it works cause I can't really speak arabian.

How to make a post request without curl?

Considering I don't want to use curl, which is a valid alternative to make a post request? Maybe Zend_http_client?
I just need the basic stuff (I need to request an url with only one post param)
You could use file_get_contents().
The PHP manual has a nice example here. This is just copy past from the manual:
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$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('http://example.com/submit.php', false, $context);
you can use stream_context_create and file_get_contents
<?php
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
?>
$context = stream_context_create($context_options);
$result = file_get_contents('http://www.php.net', false, $context);
You can implement it yourself via sockets:
$url = parse_url(''); // url
$requestArray = array('var' => 'value');
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, $url['host'], ((isset($url['port'])) ? $url['port'] : 80));
if (!$sock) {
throw new Exception('Connection could not be established');
}
$request = '';
if (!empty($requestArray)) {
foreach ($requestArray as $k => $v) {
if (is_array($v)) {
foreach($v as $v2) {
$request .= urlencode($k).'[]='.urlencode($v2).'&';
}
}
else {
$request .= urlencode($k).'='.urlencode($v).'&';
}
}
$request = substr($request,0,-1);
}
$data = "POST ".$url['path'].((!empty($url['query'])) ? '?'.$url['query'] : '')." HTTP/1.0\r\n"
."Host: ".$url['host']."\r\n"
."Content-type: application/x-www-form-urlencoded\r\n"
."User-Agent: PHP\r\n"
."Content-length: ".strlen($request)."\r\n"
."Connection: close\r\n\r\n"
.$request."\r\n\r\n";
socket_send($sock, $data, strlen($data), 0);
$result = '';
do {
$piece = socket_read($sock, 1024);
$result .= $piece;
}
while($piece != '');
socket_close($sock);
// TODO: Add Header Validation for 404, 403, 401, 500 etc.
echo $result;
Of course you have to change it to fill your needs or wrap it into a function.
The simplest way if you have PHP configured with pecl_http is:
$response = http_post_data($url, $post_params_string);
The function is documented on php.net:
Documentation http://php.net/manual/en/function.http-post-data.php
Install: http://php.net/manual/en/http.install.php
PECL also provides a well documented way to handle Cookies, Redirects, Authentication etc before the POST:
http://php.net/manual/en/http.request.options.php
If you are using the Zend Framework already you should try the Zend_Http_Client you mentioned:
$client = new Zend_Http_Client($host, array(
'maxredirects' => 3,
'timeout' => 30));
$client->setMethod(Zend_Http_Client::POST);
// You might need to set some headers here
$client->setParameterPost('key', 'value');
$response = $client->request();
RESTclient is a nice little app for this: http://code.google.com/p/rest-client/

Processing HTTP Post with Array (no cURL)

function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$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;
}
Does POST array:
$postdata = array(
'send_email' => $_REQUEST['send_email'],
'send_text' => $_REQUEST['send_text']);
How can I get individual array element to individual PHP var?
Part of a page of POST data processor:
...
$message = $_REQUEST['postdata']['send_text'];
...
What's Wrong?
Try this:
At the client side:
function do_post_request ($url, $data, $headers = array()) {
// Turn $data into a string
$dataStr = http_build_query($data);
// Turn headers into a string
$headerStr = '';
foreach ($headers as $key => $value) if (!in_array(strtolower($key),array('content-type','content-length'))) $headerStr .= "$key: $value\r\n";
// Set standard headers
$headerStr .= 'Content-Length: '.strlen($data)."\r\nContent-Type: application/x-www-form-urlencoded"
// Create a context
$context = stream_context_create(array('http' => array('method' => 'POST', 'content' => $data, 'header' => $headerStr)));
// Do the request and return the result
return ($result = file_get_contents($url, FALSE, $context)) ? $result : FALSE;
}
$url = 'http://sub.domain.tld/file.ext';
$postData = array(
'send_email' => $_REQUEST['send_email'],
'send_text' => $_REQUEST['send_text']
);
$extraHeaders = array(
'User-Agent' => 'My HTTP Client/1.1'
);
var_dump(do_post_request($url, $postData, $extraHeaders));
At the server side:
print_r($_POST);
/*
Outputs something like:
Array (
[send_email] => Some Value
[send_text] => Some Other Value
)
*/
$message = $_POST['send_text'];
echo $message;
// Outputs something like: Some Other Value

Send HTTP Post with Array - PHP

I'm trying to use this nice function:
function do_post_request($url, $data, $optional_headers = null) {
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$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;
}
to send a POST command to a specific url, my problem is i'm trying to send the post paramters in a form of an array, something like this
login[username]: myusername
login[password]: mypassword,
however i'm not able to do that, calling the function with :
$login_post = array('login[username]' => $email,
'login[password]' => '');
do_post_request(getHost($website['code']), $login_post);
always send the data to the post in the form:
username: myusername
password: mypassword
How can I avoid this (without using curl)? Thanks a lot.
Thanks
Yehia
Maybe with that ?
<?php
// Define POST data
$donnees = array(
'login' => 'test',
'password' => '******' );
function http_build_headers( $headers ) {
$headers_brut = '';
foreach( $headers as $name => $value ) {
$headers_brut .= $name . ': ' . $value . "\r\n";
}
return $headers_brut;
}
$content = http_build_query( $donnees );
// define headers
$headers = http_build_headers( array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Content-Length' => strlen( $content) ) );
// Define context
$options = array( 'http' => array( 'user_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0',
'method' => 'POST',
'content' => $content,
'header' => $headers ) );
// Create context
$contexte = stream_context_create( $options );
// Send request
$return = file_get_contents( 'http://www.exemple.com', false, $contexte );
?>
$login_post = array(
'login' => array(
'username' => $email,
'password' => ''))
Try using stream_context_create
$url = 'http://your_url.com/path';
$data = array('login' => 'usrnname', 'password' => '**');
$opt = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($opt);
$result = file_get_contents($url, false, $context);
var_dump($result);
This method doesnt use curl.

convert fopen to curl?

I have recently changed servers, and one of my scripts is not functioning on the new server, as fopen is not enabled?
Is it possible to change the following code to use the CURL function instead?
Hope someone can help!
<?php
$postToFileName = 'http://www.somesite.com/postfile.aspx';
$postArr = array(
'NM' => $row['Lead_Name'],
'EM' => $row['Lead_Email'],
'PH' => $row['Lead_Tel'],
);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($postArr)
)
);
$context = stream_context_create($opts);
$fp = fopen($postToFileName, 'r', false, $context);
$returnedMessage = '';
while (!feof($fp)) {
$returnedMessage .= fgets($fp);
}
fclose($fp);
if ($returnedMessage == '') {
$returnedMessage = 'No Message';
} else if (strlen($returnedMessage) > 250) {
$returnedMessage = substr($returnedMessage,0,250);
}
$returnedMessage = preg_replace("/[\r\n]/", '', $returnedMessage);
$returnedMessage = mysql_real_escape_string($returnedMessage, $sql);
$q = "UPDATE leads SET Data_Sent = '$returnedMessage' WHERE Lead_ID = $id";
mysql_query($q, $sql);
array_push($leadsSent, $id);
}
}
mysql_close($sql);
return $leadsSent;
}
?>
Yes, it's quite possible. See the examples here:
http://us.php.net/manual/en/curl.examples-basic.php
Sure. It should probably look like this (not tested of course, might need some minor changes) :
$postToFileName = 'http://www.somesite.com/postfile.aspx';
$postArr = array(
'NM' => $row['Lead_Name'],
'EM' => $row['Lead_Email'],
'PH' => $row['Lead_Tel'],
);
$ch = curl_init($postToFileName);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returnedMessage = curl_exec($ch);
curl_close($ch);

Categories