Getting Results from an url with sending it url variables - php

i need to send get command and take it's results. Sorry about my bad english.
i need to get result from a file whish sended url parameters
for example:
<?php
$adata["command1"] = "testcommand1";
$adata["command2"] = "testcommand2";
$getresult = sendGetCommand("https://website.com/api.html", $arrayofdata);
echo "["; // for json data;
$arrayresult = explode("\n",$getresult);
foreach ($getresult in $line) {
$arrayline = explode("\n",$line);
echo "{ ";
foreach ($arrayline in $cmdid => $cmd) {
echo "'".$cmdid."' : '".$cmd."',";
}
echo "{";
}
?>
somethink like this..
url is like:
"https://website.com/api.html?command1=testcommand1&command2=testcommand2"
url result is like:
command1,testcommand1,,yes
command2,testcommand2,,error,error text here
i'll explode the data line by line and then get the data from JavaScript
this is a domain search api.
another question:
explode("\n",$string) can be used for read it line by line? (windows os)

are you talking about file_get_contents? you can create the url with something like:
$url = "https://website.com/api.html?command1=".$adata["command1"]."&command2=".$adata["command2"];
$getresult = file_get_contents($url);
good luck;

for reading the result, you should take a look at str_getcsv and/or fgetcsv instead of doing this by hand using explode.
EDIT: for sending a get-request, you should take a look at fsockopen and its examples. you could use a function like this (just change POST to GET and the content-type like you need it):
function _get($type,$host,$port='80',$path='/',$data='') {
$_err = 'lib sockets::'.__FUNCTION__.'(): ';
switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port');
if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1);
$fp = fsockopen($host,$port,$errno,$errstr,$timeout=30);
if(!$fp) die($_err.$errstr.$errno); else {
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($str)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $str."\r\n\r\n");
while(!feof($fp)) $d .= fgets($fp,4096);
fclose($fp);
} return $d;
}

Related

Constructing a POST request manually with CPP and submitting a php form with it

I built the next request:
char* messege = "POST / HTTP / 1.1\r\n"
"Host: musicshare.pe.hu \r\n"
"Content-Length: 18\r\n"
"Content-Type: text/plain\r\n"
"Accept: text/plain\r\n\r\n"
"command=michaeliko";
This request I built by looking at some capturing wintin Wireshark because I didnt find any appropriate guide to it.
I get an OK messege OK on it, but without the "echo" (print) command I did on the php side.
So for example, a regular chrome capture respond will look like this:
Hello michaeliko\n
\n
\n
\n
<form method="post">\n
\n
Subject: <input type="text" name="command"> <br>\n
\n
</form>\t
And for the POST REQUEST I showed abouve, I will get this from the website server:
\n
\n
\n
<form method="post">\n
\n
Subject: <input type="text" name="command"> <br>\n
\n
</form>\t
The php side looks like this:
<?php
if( isset($_POST['command']))
{
$command = $_POST['command'];
echo 'Hello ' . $command . "\n";
}
?>
<form method="post">
Subject: <input type="text" name="command"> <br>
</form>
I tried to manipulate this code by many ways but find no answer.
What is wrong with my request?
I'm not able to comment yet, so unable to ask questions, such as: How are you submitting the data? Are you trying to do this from a PHP program? Below is a function I wrote years ago, I don't know if it is what you are looking for; if not, you might try the cURL library.
/*
* POST data to a URL with optional auth and custom headers
* $URL = URL to POST to
* $DataStream = Associative array of data to POST
* $UP = Optional username:password
* $Headers = Optional associative array of custom headers
*/
function hl_PostIt($URL, $DataStream, $UP='', $Headers = '') {
// Strip http:// from the URL if present
$URL = preg_replace('=^http://=', '', $URL);
// Separate into Host and URI
$Host = substr($URL, 0, strpos($URL, '/'));
$URI = strstr($URL, '/');
// Form up the request body
$ReqBody = '';
while (list($key, $val) = each($DataStream)) {
if ($ReqBody) $ReqBody.= '&';
$ReqBody.= $key.'='.urlencode($val);
}
$ContentLength = strlen($ReqBody);
// Form auth header
if ($UP) $AuthHeader = 'Authorization: Basic '.base64_encode($UP)."\n";
// Form other headers
if (is_array($Headers)) {
while (list($HeaderName, $HeaderVal) = each($Headers)) {
$OtherHeaders.= "$HeaderName: $HeaderVal\n";
}
}
// Generate the request
$ReqHeader =
"POST $URI HTTP/1.0\n".
"Host: $Host\n".
"User-Agent: PostIt 2.0\n".
$AuthHeader.
$OtherHeaders.
"Content-Type: application/x-www-form-urlencoded\n".
"Content-Length: $ContentLength\n\n".
"$ReqBody\n";
// Open the connection to the host
$socket = fsockopen($Host, 80, $errno, $errstr);
if (!$socket) {
$Result["errno"] = $errno;
$Result["errstr"] = $errstr;
return $Result;
}
// Send the request
fputs($socket, $ReqHeader);
// Receive the response
while (!feof($socket) && $line != "0\r\n") {
$line = fgets($socket, 1024);
$Result[] = $line;
}
$Return['Response'] = implode('', $Result);
list(,$StatusLine) = each($Result);
unset($Result[0]);
preg_match('=HTTP/... ([0-9]{3}) (.*)=', $StatusLine, $Matches);
$Return['Status'] = trim($Matches[0]);
$Return['StatCode'] = $Matches[1];
$Return['StatMesg'] = trim($Matches[2]);
do {
list($IX, $line) = each($Result);
$line = trim($line);
unset($Result[$IX]);
if (strlen($line)) {
list($Header, $Value) = explode(': ', $line, 2);
if (isset($Return[$Header])) {
if (!is_array($Return[$Header])) {
$temp = $Return[$Header];
$Return[$Header] = [$temp];
}
$Return[$Header][] = $Value;
}
else $Return[$Header] = $Value;
}
}
while (strlen($line));
$Return['Body'] = implode('', $Result);
return $Return;
}

php post empty if textarea over 1 million characters

I have a textarea, it works fine if there are less than 1 million characters. As soon as something is posted over 1 million characters that field is missing in $_POST (all other fields are posted).
What could be causing this? When searching all I have seen mentioned is there are no character limits only post size limit and memory limit. No errors are being displayed and these are set well over the 2Mb text size.
Managed to solve the issue, it was suhosin limiting the characters. I needed to set the following:
suhosin.request.max_value_length = 100000000
suhosin.post.max_value_length = 100000000
Did you try increasing post_max_size in php.ini file?
Moreover, you can also use some other way to post your data i.e use:
//execute an async method
function curl_request_async($url, $params, $type='GET'){
$post_params = array();
foreach ($params as $key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
(isset($parts['scheme']) && $parts['scheme'] == 'https')? 443 : 80,
$errno, $errstr, 999999999);
$out = "$type ".$parts['path'] . (isset($parts['query']) ? '?'.$parts['query'] : '') ." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
// Data goes in the request body for a POST request
if ('POST' == $type && isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
You can call this function like:
$url = "somefile.php";
$data['mydata'] = "some data some data some data";
curl_request_async( $url, $data, 'POST' );
Note:
Do not use any type of Session based authentication in file "somefile.php". And you can access post data like $_POST['mydata']. You can also call this function in by GET. Don't know what you are actually looking for.

How to POST to an XML API?

We are integrating the travel API of www.transhotel-dev.com.
The code is like this:
<?php
$servletHOST = "www.transhotel-dev.com";
$servletPATH = "/interfaces/SController";
$pXML = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><Login><Username>Username</Username><Password>Password</Password></Login>";
$pCall = "Login";
$postdata = "pXML=" . urlencode($pXML) . "&pCall=" . urlencode($pCall);
$fp = pfsockopen($servletHOST, 1184);
if ($fp) {
fputs($fp, "POST $servletPATH HTTP/1.0\n");
fputs($fp, "Accept: */*\n");
$strlength = strlen( $postdata );
fputs($fp, "Content-length: " . $strlength . "\n\n");
fputs($fp, $postdata . "\n" );
$output = "";
while (!feof($fp)) {
$output .= fgets($fp, 1024);
}
fclose($fp);
echo $output;
}
?>
HTTP compression and POST method are required to go beyond this point. Can anybody help?
The following calls require the use of https secure protocol
(https://www.transhotel-dev.com:1449/interfaces/SController):
Login
AddAmountCardHPlus
GetNifInvoices
NifAgencyReservations
NifHotelReservations
ConfirmReservation (When contain the data of a credit card)
BuildSearchForm
LoginRQ
LoginB2B
CreateAgency
NifActivitiesReservations
GetActivitiesProvider
NifTransfersReservations
GetTransfersProvider
LoginHPlus
UserLogInHPlus
so you should use ssl protocol for login action:
$fp = pfsockopen("ssl://www.transhotel-dev.com", 1449);

Paypal IPN cannot get verified

I am trying to implement Paypal IPN but it never reaches the url I've set. I've written a script to log visits to this url and all I get are my visits.
How long does it take for Paypal to sent the notification?
EDIT
IPNs suddenly started to come but now I can't verify...Here is the code:
$url = 'https://www.paypal.com/cgi-bin/webscr';
$postdata = '';
foreach ($_POST as $i => $v) {
$postdata .= $i . '=' . urlencode($v) . '&';
}
$postdata .= 'cmd=_notify-validate';
$web = parse_url($url);
if ($web['scheme'] == 'https') {
$web['port'] = 443;
$ssl = 'ssl://';
} else {
$web['port'] = 80;
$ssl = '';
}
$fp = #fsockopen($ssl . $web['host'], $web['port'], $errnum, $errstr, 30);
if (!$fp) {
echo $errnum . ': ' . $errstr;
} else {
fputs($fp, "POST " . $web['path'] . " HTTP/1.1\r\n");
fputs($fp, "Host: " . $web['host'] . "\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: " . strlen($postdata) . "\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $postdata . "\r\n\r\n");
while (!feof($fp)) {
$info[] = #fgets($fp, 1024);
}
fclose($fp);
$info = implode(',', $info);
if (eregi('VERIFIED', $info)) {
} else {
}
}
I already commented above. But I'm pretty sure the html encoded & is messing up your callback.
There's big difference between URL encoding and HTML encoding.
Change this '&' to this '&'. & is a url/post character used to separate different sets of key/value pairs. By changing it to &, you made your whole callback a single value.
Also, just some advice, but I would ditch this
if (eregi('VERIFIED', $info)) {} else {}
and replace it with this
if (preg_match('/VERIFIED/', $info)) {} else {}
eregi is depreciated.
http://php.net/manual/en/function.eregi.php

fpassthru in python?

I am trying to find a sample code for download a file in python. To be exact, I am trying to convert a php to python.
My php sameple code:
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($data) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $data;
$response = '';
if( false == ( $fs = #fsockopen($host, $port, $errno, $errstr, 10) ) ) {
die ('Could not open socket');
}
fwrite($fs, $http_request);
$headerpassed = false;
while ($headerpassed == false) {
$line = fgets( $fs);
list($tag, $value) = explode(": ", $line, 2);
if (stristr($tag, 'Location')) {
$target_url = trim($value);
header("Location: http://127.0.0.1/umsp/plugins/".basename(__file__)."?".$url_data_string."\r\ n");
continue;
}
if (trim($line) == "") {
$headerpassed = true;
header('Content-Type: video/avi');
}
header($line);
}
set_time_limit(0);
fpassthru($fs);
fclose($fs);
I found python file download script using urllib, but all the examples I found actually save to physical file unlike php code above.
PS: someone please add 'fpassthru' for me. I don't have permission to add a new tag.
A translation of PHP's fpassthru to Python might be as simple as:
def fpassthru(fp):
""" Reads to EOF on the given file object from the current position
and writes the results to output. """
print fp.read()
The fp argument must be a "file object" returned by open (the standard method for opening files) or a similar stream factory method such as urllib2.urlopen in the case of downloading content from an URL.
For example, this will open an URL and print its contents:
from urllib2 import urlopen # (renamed to urllib.request in Python 3.0)
fp = urlopen('http://www.example.com')
fpassthru(fp)
fp.close()
Note that you can get the HTTP response headers with dict(fp.headers). (But this attribute is only available on file objects returned by urllib2.urlopen, not regular file objects.)

Categories