PHP - About Registering Globals...
Well 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. Similar TutorialsI have a form where members on my site can update their display name among other things. However, my script is returning the error for if nothing was inputted in the display name input box (members must provide a display name, can't leave that box blank) even though my text input box definitely has a value. The section of my form with the input box: Code: [Select] <tr> <td class='sidebardark' width=40%><b>Display Name</td> <td class='D' width=60%><input type=text name=newdisplayname class='inputtext' value="<? echo $currentname;?>"></td> </tr> And the section in my form-submitted script that has the error that's displaying: Code: [Select] $newdisplay = strip_tags(mysql_real_escape_string($POST['newdisplayname'])); if ($newdisplay == "" || !isset($POST['newdisplayname'])){ errorbox("You must set a display name!"); } Normally I'd think it was a typo on my part but I honestly can't see anything wrong with it. The current display name is showing up just fine in the input box. I asked it to echo $newdisplay above the error box and it echoed nothing so I have to assume it's not passing the variable correctly for some reason. Edit: If it matters, I haven't had any issues with text input boxes on this particular site before. Only this specific one. Hi, I have a site where users can register etc. I was wondering should I use mysql_real_escape_string() for the elements on my registration form example email, name and so on or is it no necessary? One more question could some one tell is this the proper way to use it before inserting into the database. $name=$_POST['name']; mysql_real_escape_string($name) ? Hi there I would be most grateful is someone could tell me why my data is not being entered into my database and not responding with an email confirmation link. Thanks in advance. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <? include('config.php'); // table name $tbl_name="temp_members_db"; // Random confirmation code $confirm_code=md5(uniqid(rand())); // values sent from form $name=$_POST['name']; $email=$_POST['email']; $country=$_POST['country']; // Insert data into database $sql="INSERT INTO $tbl_name(confirm_code,name,email,password,country) VALUES('$confirm_code','$name','$email','$password','$country')"; $result=mysql_query($sql); // if suceesfully inserted data into database, send confirmation link to email if($result){ // ---------------- SEND MAIL FORM ---------------- // send e-mail to ... $to=$email; // Your subject $subject="Your confirmation link here"; // From $header="from: your name <your email>"; // Your message $message="Your Comfirmation link \r\n"; $message.="Click on this link to activate your account \r\n"; $message.="http://www.yourweb.com/confirmation.php?passkey=$confirm_code"; // send email $sentmail = mail($to,$subject,$message,$header); } // if not found else { echo "Not found your email in our database"; } // if your email succesfully sent if($sentmail){ echo "Your Confirmation link Has Been Sent To Your Email Address."; } else { echo "Cannot send Confirmation link to your e-mail address"; } ?> </body> </html> Please help with my register page: http://www.retroandvintage.co.uk/register.php after someone has registered they are stuck on reg_script.php and don't get redirected back to main.php being already logged in?! here is my code: Code: [Select] <?php session_start(); include_once("config.php"); //include_once("functions.php"); require_once('captcha/recaptchalib.php'); $privatekey = "6Ldhhr4SAAAAAKFoL2INOZV0_VuF6_z3OwDjVFNn"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { // Your code here to handle a successful verification $rsPostCode = $_POST['rsPostCode']; $rsGender = $_POST['rsGender']; $rsUser = $_POST['rsUser']; $rsPass = $_POST['rsPass']; $rsEmail = $_POST['rsEmail']; $rsMobile = $_POST['rsMobile']; $rsAge = $_POST['rsAge']; $sql = "INSERT INTO members_copy (RSPOSTCODE, RSGENDER, RSUSER, RSPASS, RSEMAIL, RSMOBILE, RSAGE) VALUES ('$rsPostCode', '$rsGender', '$rsUser', '$rsPass', '$rsEmail', '$rsMobile', '$rsAge');"; //echo $sql; mysql_query($sql); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); /* Login script: This script does the following: Checks that the user is NOT already logged in - if they are they are redirected to the members page by the 'checkLoggedIn()' function. Checks if the login form has been submitted - if so, the 'login' and 'password' fields are checked to ensure they are of the correct format and length. If there are any problems here an error is added to the $messages array and then the script executes the 'doIndex()' function - this function basically outputs the main 'index' page for this script - ie the login form. If there are no problems with the previous step, the 'login' and 'password' field data is passed to the 'checkPass' function to check that an entry exists in the 'users' table for that login/password pair. If nothing is returned from the 'checkPass()' function, an error is added to the $messages array and the 'doIndex()' function is called as above. If a row of data is returned from the 'users' table, the data is passed to the 'cleanMemberSession()' function - which initializes session variables and logs the user in. The user is then forwarded to the members page. If the form hasn't yet been submitted, then the 'doIndex()' function is called and the login page is displayed. */ // Check user not logged in already: checkLoggedIn("no"); // Page title: $title="Member Login Page"; // if $submit variable set, login info submitted: if(isset($_POST["Register"])) { // // Check fields were filled in // // login must be between 4 and 15 chars containing alphanumeric chars only: field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 4, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 4, 15); // if there are $messages, errors were found in validating form data // show the index page (where the messages will be displayed): if($messages){ doIndex(); // note we have to explicity 'exit' from the script, otherwise // the lines below will be processed: exit; } // OK if we got this far the form field data was of the right format; // now check the user/pass pair match those stored in the db: /* If checkPass() is successful (ie the login and password are ok), then $row contains an array of data containing the login name and password of the user. If checkPass() is unsuccessful however, $row will simply contain the value 'false' - and so in that case an error message is stored in the $messages array which will be displayed to the user. */ if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { // login/passwd string not correct, create an error message: $messages[]="Incorrect login/password, try again"; } /* If there are error $messages, errors were found in validating form data above. Call the 'doIndex()' function (which displays the login form) and exit. */ if($messages){ doIndex(); exit; } /* If we got to this point, there were no errors - start a session using the info returned from the db: */ cleanMemberSession($row["rsUser"], $row["rsPass"]); // and finally forward user to members page (populating the session id in the URL): header("Location: main.php"); /* This function displays the default 'index' page for this script. This consists of just a simple login form for the user to submit their username and password. */ } } ?> hey guys just wondering what u think the best way to do this.....on my form registration for users....I have a drop down for countrys....but I dont want to have 2 drop downs 1 for state and 1 for province if they choose canada/usa....I have seen alot of java scrit on such sites where if you choose Canada for country, then it switches to a drop down for just provinces, not states. Same for zip code/postal code...american zip code would be like 90210 where as a postal code would be like n5j2S1. Is there a script or something already I can use with all the countrys/provinces/states etc already entered so im not re-inventing the wheel here? If someone can point me in right directon id appreciate it. Thanks 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? 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? What does this mean? Code: [Select] {$GLOBALS['path']} Hey guys, Just lately I have been trying to start a specific project for myself. I started off by designing the pages etc on HTML, and then a friend of mine helped me convert them to PHP.
At the moment, when a user registers to the site, they only require to enter a Username and Password. I would like to add their email to it too, due to adding slightly extra security. It would also be used for future reasons such as sending emails out etc.
I'm not sure about adding this, I know that most likely it is going to be VERY similar to how it already is, but I couldn't seem to get it to work when I tried.
Ill give the coding which I am using for this below (the documents which I believe would need editing) :
Register.php
<?php require($_SERVER['DOCUMENT_ROOT'] . '/TruckWorld/includes/config.php'); $sOutput .= '<div id="register-body">'; if (isset($_GET['action'])) { switch (strtolower($_GET['action'])) { case 'register': // If the form was submitted lets try to create the account. if (isset($_POST['username']) && isset($_POST['password'])) { if (createAccount($_POST['username'], $_POST['password'])) { $sOutput .= '<h1>Account Created</h1><br />Your account has been created. You can now login <a href="login.php">here</a>.'; }else { // unset the action to display the registration form. unset($_GET['action']); } }else { $_SESSION['error'] = "Username and or Password was not supplied."; unset($_GET['action']); } break; } } // If the user is logged in display them a message. if (loggedIn()) { $sOutput .= '<h2>Already Registered</h2> You have already registered and are currently logged in as: ' . $_SESSION['username'] . '. <h4>Would you like to <a href="login.php?action=logout">logout</a>?</h4> <h4>Would you like to go to <a href="index.php">site index</a>?</h4>'; // If the action is not set, we want to display the registration form }elseif (!isset($_GET['action'])) { // incase there was an error // see if we have a previous username $sUsername = ""; if (isset($_POST['username'])) { $sUsername = $_POST['username']; } $sError = ""; if (isset($_SESSION['error'])) { $sError = '<span id="error">' . $_SESSION['error'] . '</span><br />'; } $sOutput .= '<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Truck World - Register</title> <!-- Core CSS - Include with every page --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="font-awesome/css/font-awesome.css" rel="stylesheet"> <!-- SB Admin CSS - Include with every page --> <link href="css/sb-admin.css" rel="stylesheet"> </head> <body> <div align=center><img src="images/logintitle.png" alt="LoginTitle" /></div> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="login-panel panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Register To Join Truck World!</h3> </div> <div class="panel-body"> ' . $sError . ' <form name="register" method="post" action="' . $_SERVER['PHP_SELF'] . '?action=register"> <fieldset> <div class="form-group"> <input class="form-control" placeholder="Username" name="username" type="username" autofocus=""> </div> <div class="form-group"> <input class="form-control" placeholder="Password" name="password" type="password" value=""> </div> <div class="form-group"> <input class="form-control" placeholder="Email" name="email" type="email" value=""> </div> <!-- Change this to a button or input when using this as a form --> <input type="submit" class="btn btn-lg btn-success btn-block" name="submit" value="Register" /> <a href="login.php"class="btn btn-lg btn-success btn-block">Login</a> </fieldset>'; } $sOutput .= '</div> </div> </div> </div> </div> <div align=center><h5><small>Copyright - Lewis Pickles 2014 - All Rights Reserved</small></h5></div> <!-- Core Scripts - Include with every page --> <script src="js/jquery-1.10.2.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/plugins/metisMenu/jquery.metisMenu.js"></script> <!-- SB Admin Scripts - Include with every page --> <script src="js/sb-admin.js"></script> </body> </html> '; // display our output. echo $sOutput; ?>Functions.php (Not sure if this would need editing, I think it might, Correct me if I'm wrong) <?php function createAccount($pUsername, $pPassword) { // First check we have data passed in. if (!empty($pUsername) && !empty($pPassword)) { $uLen = strlen($pUsername); $pLen = strlen($pPassword); // escape the $pUsername to avoid SQL Injections $eUsername = mysql_real_escape_string($pUsername); $sql = "SELECT username FROM users WHERE username = '" . $eUsername . "' LIMIT 1"; // Note the use of trigger_error instead of or die. $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // Error checks (Should be explained with the error) if ($uLen <= 4 || $uLen >= 11) { $_SESSION['error'] = "Username must be between 4 and 11 characters."; }elseif ($pLen < 6) { $_SESSION['error'] = "Password must be longer then 6 characters."; }elseif (mysql_num_rows($query) == 1) { $_SESSION['error'] = "Username already exists."; }else { // All errors passed lets // Create our insert SQL by hashing the password and using the escaped Username. $sql = "INSERT INTO users (`username`, `password`) VALUES ('" . $eUsername . "', '" . hashPassword($pPassword, SALT1, SALT2) . "');"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); if ($query) { return true; } } } return false; } /*********** string hashPassword (string $pPassword, string $pSalt1, string $pSalt2) This will create a SHA1 hash of the password using 2 salts that the user specifies. ************/ function hashPassword($pPassword, $pSalt1="2345#$%@3e", $pSalt2="taesa%#@2%^#") { return sha1(md5($pSalt2 . $pPassword . $pSalt1)); } /*********** bool loggedIn verifies that session data is in tack and the user is valid for this session. ************/ function loggedIn() { // check both loggedin and username to verify user. if (isset($_SESSION['loggedin']) && isset($_SESSION['username'])) { return true; } return false; } /*********** bool logoutUser Log out a user by unsetting the session variable. ************/ function logoutUser() { // using unset will remove the variable // and thus logging off the user. unset($_SESSION['username']); unset($_SESSION['loggedin']); return true; } /*********** bool validateUser Attempt to verify that a username / password combination are valid. If they are it will set cookies and session data then return true. If they are not valid it simply returns false. ************/ function validateUser($pUsername, $pPassword) { // See if the username and password are valid. $sql = "SELECT username FROM users WHERE username = '" . mysql_real_escape_string($pUsername) . "' AND password = '" . hashPassword($pPassword, SALT1, SALT2) . "' LIMIT 1"; $query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error()); // If one row was returned, the user was logged in! if (mysql_num_rows($query) == 1) { $row = mysql_fetch_assoc($query); $_SESSION['username'] = $row['username']; $_SESSION['loggedin'] = true; return true; } return false; } ?>The Database for the email is as follows: Edited by Lewis2212, 06 August 2014 - 10:20 AM. 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-BHi 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? 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; } ?> 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? 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? 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 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 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 |