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.)
Related
I'm trying to send a request to a remote server using the fire-and-forget approach. This is my code:
function backgroundPost($url, $data = array()){
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
return false;
} else {
$encoded_data = json_encode($data);
$output = "POST ".$parts['path']." HTTP/1.1\r\n";
$output .= "Host: ".$parts['host']."\r\n";
$output .= "Content-Type: application/json\r\n";
$output .= "Content-Length: " . strlen($encoded_data) . "\r\n";
$output .= "Connection: Close\r\n\r\n";
$output .= $encoded_data;
fwrite($fp, $output);
fclose($fp);
return true;
}
}
//Example of use
backgroundPost('url-here', array("foo" => "bar"));
but the data that arrives is simply empty.
When I spin up the application locally and send the request to my own machine instead, the data does arrive.
Am I misunderstanding something about this pattern?
Why is it working when sending a request to my own machine but not a remote one?
Thanks!
I'm using Nginx 1.7.3 and PHP 7.0.
I created a test.php file like that
<?php
$header = '';
$header .= "GET /test2.php HTTP/1.1\r\n";
$header .= "Host:127.0.0.1\r\n";
$header .= "Connection: close";
$data = $header . "\r\n\r\n";
if ($fp = fsockopen('127.0.0.1', 80))
{
fwrite($fp, $data);
$res = '';
while (!feof($fp))
{
$res .= fgets($fp, 1024);
}
fclose($fp);
}
echo $res;
?>
and I created a test2.php file like that
<?php
echo 1;
?>
then I executed the test.php file by accessing on 127.0.0.1/test.php, but It didn't working. It kept loading and didn't show any text.
so I tested like that
while (!feof($fp))
{
echo 1;
exit;
$res .= fgets($fp, 1024);
}
I excuted it, and it printed '1'.
(I think fgets() doesn't work.)
but I excuted it for a text file as follows.
$header = '';
$header .= "GET **/text.txt** HTTP/1.1\r\n";
$header .= "Host:127.0.0.1\r\n";
$header .= "Connection: close";
It works well. I don't know what I have to do. How can I use fsockopen() for PHP files on localhost. I googled about it much, but unfortunately It wasn't very helpful. If you know about that, please tell me how to do.
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
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;
}
I am trying to send a SOAP message to a service using php.
I want to do it with fsockopen, here's is the code :
<?php
$fp = #fsockopen("ssl://xmlpropp.worldspan.com", 443, $errno, $errstr);
if (!is_resource($fp)) {
die('fsockopen call failed with error number ' . $errno . '.' . $errstr);
}
$soap_out = "POST /xmlts HTTP/1.1\r\n";
$soap_out .= "Host: 212.127.18.11:8800\r\n";
//$soap_out .= "User-Agent: MySOAPisOKGuys \r\n";
$soap_out .= "Content-Type: text/xml; charset='utf-8'\r\n";
$soap_out .= "Content-Length: 999\r\n\r\n";
$soap_put .= "Connection: close\r\n";
$soap_out .= "SOAPAction:\r\n";
$soap_out .= '
Worldspan
This is a test
';
if(!fputs($fp, $soap_out, strlen($soap_out)))
echo "could not write";
echo "<xmp>".$soap_out."</xmp>";
echo "--------------------<br>";
while (!feof($fp))
{
$soap_in .= fgets($fp, 100);
}
echo "<xmp>$soap_in</xmp>";
fclose($fp);
echo "ok";
the above code just hangs . if i remove the while it types ok, so i suppose the problem is at $soap_in .= fgets($fp, 100)
Any ideas of what is happening
Its not just a matter of opening a socket then writing 'POST....' to it - you need a full HTTP stack to parse the possible responses (e.g. what different encodings? Partial Content?). Use cURL.
The reason its currently failing is probably because the remote system is configured to use keepalives - which would again be solved by using a proper HTTP stack.
C.
I recommend, use curl for soap actions. http://www.zimbra.com/forums/developers/9890-solved-simple-soap-admin-example-php.html#post52586