PHP - Usual Variables Vs Global
Hi there,
I am a highly concerned about ever using global variables (as many guides I have seen on security issues with PHP say you should avoid them, kind of understand why though to be fair), but I was wanting to really understand custom based session handlers in PHP and this first one he http://uk.php.net/manual/en/function.session-set-save-handler.php on the example: 'Example #1 session_set_save_handler() example' uses them. Now would it be better to take the global variable in function: ''open()' and then return the variable $sess_save_path then pass it up to the next function that may need it perhaps? I just don't want to use globals if I can avoid it, been working out a system that work use for some old solution we use and it uses globals and it really bugs the living life out of me, why people are so lazy they can't avoid them at all costs grrr. Any advice generally speaking is of great appreciation, Jeremy. Similar TutorialsI use $db object to handle database function like $db->get_row for example. Is there any way that I don't need to put into every function global $db or do I actually need to repeat in every function global $db? Code: [Select] function example(){ global $db //Do I need to repeat this in each function? } $errors=0; //NEW USER NAME HAS BEEN SUBMITTED, CHECK IT OUT AND THEN ADD IF OKAY $newuser=$_REQUEST['newuser']; function TryAgain(){ global $errors; $errors++; echo '<br/><br/>Please try again <a href="index.php?locate=admin&sub=add_admin">here</a>'; echo "<br/>errors=[$errors]"; } echo "<br/>Trying to add user: $newuser<br/><br/>"; if ($newuser){ }else{ // field was left blank, report this to user and give them option to try again echo '<br/>Field was left empty, you must pick a username.';TryAgain(); } if (strlen($newuser)<5){echo 'Username should be at least 5 characters.';TryAgain();} if (!$errors){echo "continue to SQL [errors=$errors]";} what is wrong with this code? For some reason if I increment $errors with $errors++ within the function it doesn't increment outside the function's scope. even though I declare it as a global at the start of the function. I know I'm doing something stupid here but can somebody please tell me what it is? Thanks If I want to load some user information from the database into an object/array and share it throughout my application, what's the best approach for this? Here is what I thought of doing: - I can call a function (e.g user_info() ) that will return the user information whenever I need it , but It'll have to run a DB query each time I call it. - Load user information once from the DB, assign it into a global array/object, then call that object whenever I need it. A lot of people recommended against using global variables, but I think performance wise it's better than running a query each time. Are there any better alternatives than the above approaches? I need the following three variables to be available globally, that is to every page. (An common header.html uses them at every page). Please teach me how to initialize them. (inside the header.html maybe?) 'U_M_CODE' => append_sid("{$phpbb_root_path}faq.$phpEx", 'mode=bbcode'), 'U_M_TERMS' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=terms'), 'U_M_PRV' => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=privacy'), Thank you. Hi, In all my classes, I need to declare globals for everything else, from site variables even to objects (other classes). I obviously don't want to as globals are horrible and I need to have functions clean without globals. I have included a list of all the global vars in the construct and it still doesn't work. Example: start.php <?php $vars = array(some values); $some = more; $variables = foo; $helper = new Helper(); $home = new Home(); This is a little bit simplistic, but for some reason, the variables just don't want to go in the main class without a global. Functions will not run if they require any of these variables. Hello I've have read that global variables should not be used. so if i have 2 .php files: index.php - main content php file sitefunctions.php - php functions site file on my index.php page i have the following (an example of my problem): <?php displayError($errorID); ?> and in the sitefunctions.php file i have the following (an example of my problem): <?php function displayError($errorID) { if($errorID == 1) { echo "Password Failure"; } else { echo "Other Failure"; } } ?> now that works but since when first accesing that page the $errorID is not set then i get an error. How can i achieve this without first setting a blank $errorID global variable? Thanks Hello, my global variable is getting whacked (defined null or being undefined) after a function call. I'm not sure if it's happening when leaving the function that assigns it or when the form is "posted", or something else. Code: [Select] <? //global variables $globalVarString = ""; //function definitions function displayResults() { global $globalVarString; if ($globalVarString == "") {displayForm("please enter your search string again");} else {displayForm("you typed: $globalVarString");} } function getResults($searchInput) { global $globalVarString; $globalVarString = $searchInput; //give status ?> <html><head><title>Search</title></head><body> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Thanks for entering your data (<? echo "$globalVarString" ?>).<br><br>Please press the submit button to process your data    <input type="Submit" value="Submit" name="processQuery"> </form></body></html> <? } function displayForm($message) { //prompt for input ?> <html><head><title>Search</title></head><body> <form action=" <? $_SERVER['PHP_SELF'] ?>" method="post"> <h3>Please enter your search <input type="text" name="searchString">    <script type="text/javascript">document.forms[0].searchString.focus();</script> <input type="Submit" value="Submit Query" name="searchQuery"></h3> </form> <? if (!$message == ""){echo "<br>    <h4>" . $message . "</h4><br>";} ?> </body></html> <? } //main() if(array_key_exists('searchQuery', $_POST)) {getResults($_POST['searchString']);} elseif (array_key_exists('processQuery', $_POST)) {displayResults();} else {displayForm("");} ?> This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=350034.0 hi all. i am so lost here guys,i need your help. basically, i have 3 pages here. _add_tsubject, _query_subject, and _do_addtsubject. _add_tsubject here contains a livesearch javascript that searches for subjects which i query in _query_subject. the result of that is displayed in _add_tsubject. i am using get method for that and for the url. now, my problem is how to pass or should i say combine the url from _add_tsubject with the url inside the <a href> in _query_subject?or is it possible??i'm sorry if it sounds confusing. but if it's confusing you please have a look at the code.. _add_tsubject <?php include("dbconnection_wmsuipil.php"); $id = $_GET['item']; $t_id = $_GET['t_id']; $lname = $_GET['lname']; $fname = $_GET['fname']; $result= mysql_query("SELECT * FROM tblSetSY")or die(mysql_error()); while($row = mysql_fetch_array($result)) { $setYear=$row['SchoolYear']; $setSem=$row['Sem']; } ?> <!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>Adding subject to teacher..</title> <link rel="stylesheet" href="style.css"/> <link rel="stylesheet" href="validator_style/screen.css"/> </head> <body> <div style="margin-right:30px; padding:10px;" align="right"><a href="#" onclick="window.location.reload()">Reload</a> | <a href="#" onclick="window.close()">Close</a></div> <form name="form" id="cmxform_sched" class="cmxform" method="post" action="_do_addtsubject.php"> <fieldset> <p> <label for="t_id">Teacher ID: </label> <input type="hidden" name="school_year1" value="<?php echo $setYear;?>"/> <input type="hidden" name="sem1" value="<?php echo $setSem;?>"/> <input type="hidden" name="id" value="<?php echo $id;?>" size="15"/> <input type="text" name="t_id" value="<?php echo $t_id;?>" size="15"/> </p> <p> <label for="name">Name: </label> <input type="text" name="name" value="<?php echo $fname.' '.$lname;?>" size="25"/> </p> <p><i>*Add subjects to be handled...</i></p> <p><label for="keyword">Enter Subject ID: </label> <input type="text" name="sid" id="sid" size="15" onkeyup="showResult(this.value)" /> </p> <div id="livesearch" align="center"><b>->Subject info will be listed here<-</b></div> </table> </fieldset> </form> <script type="text/javascript"> function showResult(str) { if (str.length==0) { document.getElementById("livesearch").innerHTML=""; document.getElementById("livesearch").style.border="0px"; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("livesearch").innerHTML=xmlhttp.responseText; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","_query_subject.php?q="+str,true); xmlhttp.send(); } </script> </body> </html> _query_subject (i get an error on the _POST here..) <?php include("dbconnection_wmsuipil.php"); $t_id=$_POST['t_id']; $name=$_POST['name']; $sy=$_POST['school_year1']; $sem=$_POST['sem1']; $q=$_GET['q']; $sql="SELECT * FROM admin_subject WHERE subj_id like '%".$q."%'"; echo "<table border='1'> <tr> <th>#ID</th> <th>Subject ID</th> <th>Subject Code</th> <th>Description</th> <th>Lect</th> <th>Lab</th> <th>Units</th> </tr>"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { $OutLine = array('id'=>'','subj_id'=>'','subj_code'=>'','subj_desc'=>'','lecture'=>'','laboratory'=>'','units'=>''); $OutLine['id'] = $row['id']; $OutLine['subj_id'] = $row['subj_id']; $OutLine['subj_code'] = $row['subj_code']; $OutLine['subj_desc'] = $row['subj_desc']; $OutLine['lecture'] = $row['lecture']; $OutLine['laboratory'] = $row['laboratory']; $OutLine['units'] = $row['units']; $countTsubj=0; if($row>$countTsubj) { echo "<tr>"; echo "<td>".implode('<td/>',$OutLine); echo '<td><a href="_do_addtsubject.php?id='.$row['id'].'&subj_id='.$row['subj_id'].'&code='.$row['subj_code'].'&desc='.$row['subj_desc'].'&lect='.$row['lecture'].'&lab='.$row['laboratory'].'&units='.$row['units'].'">[Add]</a></td>'; echo "</tr>"; } } echo "</table>"; ?> _do_addtsubject <?php include("dbconnection_wmsuipil.php"); $t_id=$_POST['t_id']; $name=$_POST['name']; $sy=$_POST['school_year1']; $sem=$_POST['sem1']; $id=$_GET['id']; $subj_id=$_GET['subj_id']; $code=$_GET['code']; $desc=$_GET['desc']; $lect=$_GET['lect']; $lab=$_GET['lab']; $units=$_GET['units']; echo $t_id; echo $name; echo $sy; echo $sem; echo $id; echo $subj_id; echo $code; echo $desc; echo $lect; echo $lab; echo $units; ?> there guys..i hope you can help me..the last page is where plan to echo the url once it's combined..please please help.. This question may sound very lame... ... But I have never able to know how to define a variable that I can use in different functions in a same file. There is no class structure just a PHP file with some functions. Is it possible to use some type of variable that can be share by all functions and that variable should not be a session variable . Something like: <?php $my_global_var; function A() { // use $my_global_var here } function B() { // use $my_global_var here and should retain the last value } ?> Something like in VB6.... Thanks It's a function=> Code: [Select] function _wp_call_all_hook($args) { global $wp_filter; //var_dump($wp_filter); //exit(); reset( $wp_filter['all'] ); do { foreach( (array) current($wp_filter['all']) as $the_ ) if ( !is_null($the_['function']) ) call_user_func_array($the_['function'], $args); } while ( next($wp_filter['all']) !== false ); } Why is $wp_filter variable declared as global ? Was $wp_filter assigned before ? i have two classes and I am trying to call one class in through another here is my code but my welcome is not showing at all ever when i change the var's to 1 Code: [Select] class site { function DisplayContent ($page) { global $Users; echo '<div align="center"> <div id="Header"> <div id="NavBar">'; if ($Users->logged == 1) { echo 'Welcome '. $Users->user .' - <a href="?page=viewreminders">View Reminders</a> - <a href="?page=addreminder">Add Reminder</a> - <a href="logout.php" id="Logout">Logout</a>'; } else { echo '<a href="?page=login">Login</a> - <a href="?page=register">Register</a> - <a href="?page=forgotpassword">Forgot Password?</a>'; } echo '</div> </div> <div id="Content">'; $this->ShowPage($page); echo '</div> <div id="Footer">Copyright © '.date('Y').'<br /> Coded and Designed by Chris Cloyd</div> </div>'; } } class users { var $logged; var $user; var $email; var $level; function LogIn ($name,$email,$level) { $this->logged = 1; $this->user = $name; $this->email = $email; $this->level = $level; } function LogOut () { $this->logged = "0"; $this->user = ""; $this->email = ""; $this->level = ""; } } Just wanted to know if $_Session was a global thing or does php require cookies setup?
I assumed that I could do something like this:
PAGE: A.php session_start(); $_Session['Cat'] = 'Meow'; // ----------------------- PAGE: B.php if (isset($_Session['Cat']) && !empty($_Session['Cat'])){ echo $_Session['Cat']; } OUTPUT: Meow // ----------------------- PAGE: C.php if (isset($_Session['Cat']) && !empty($_Session['Cat'])){ echo $_Session['Cat']; } OUTPUT: MeowI can't seem to get this to work. Page: Handler.inc // ========================================================= Session Log in / out public function logon($username, $password){ if ($username == "admin" && $password == "coffee"){ session_start(); $_SESSION['USER_STATUS'] = '1'; echo 'IN SESSION LOGIN HANDLER'; echo $_SESSION['UserLogged']; } } public function logout(){ $_SESSION['USER_STATUS'] = '0'; echo 'IN SESSION LOGOUT HANDLER'; session_destroy(); //session_unset(); }Page: index.php if (!isset($_SESSION['USER_STATUS']) && empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 0){ if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; echo $handler->logon($username, $password); } <LOGIN FORM CODE> }else{ if (isset($_SESSION['USER_STATUS']) && !empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 1){ echo 'Session name: '. $_SESSION['USER_STATUS']; } if (isset($_POST['btn_logout']) && !empty($_POST['btn_logout'])){ $handler->logout(); echo '<br />Logged out<br />'; } <LOGOUT FORM BUTTON CODE> }Could someone point me in the right direction please. It does not seem to hold its session. hello, ok if i set a Global on index.php (wwwroot/admin/index.php) it works Code: [Select] $page1='hello from page1 on index'; global $page1; echo $page1; i can echo $page1 on other pages like (wwwroot/admin/pages/home.php) and it will echo out "hello from page1 on index". GREAT but if i write a Global on (wwwroot/admin/pages/home.php) it does not work. i also can not echo it out on any other page Code: [Select] $page2='hello from page2 on home'; global $page2; echo $page2; why is this ??? I have some variables that I have set with the global command but they don't seem to be working correctly. It's probably my order of operation but not sure. Here's the stripped down version of whats going on: locator() //functions function geoip() global $zip, $city, $areacode, $metrocode, $state, $country, $latitude, $longitude; function locator() geoip() use globals from geoip pass to- ad_display() function ad_display() does some work stat_tracking() function stat_tracking() access global $zip, $city, $areacode, $metrocode, $state, $country, $latitude, $longitude; The problem is once I call stat_tracking() and try to access the global variables, they are all empty. Just to clarify the chain of events is: page loads, calls locator(), locator() calls function geoip() fine then passes work to ad_display(), ad_display() calls stat_tracking(), stat_tracking() now tries to access the globals I made but all variables are blank if I echo them. Any ideas? hello. I have some oop code that pulls information about a page out of a mysql db but i dont want to put the code on every page. Instead in want to put it in the a function and pass it back to each page. do i put it in a function in my functions.php file or can i put it into my includes/pages.php includes file ?? the code looks for the page name on the page and then pulls that pages info from the db. this code works on the page - home.php Code: [Select] <?PHP require_once("../includes/initialize.php"); $currentPages = Pages::find_all(); $pName = "adminHome"; $page_id = ""; $visible = ""; $pageZones = ""; $pageCRUD = ""; $pageTypes = ""; $module = ""; $title = ""; $sub_title = ""; $description = ""; $image = ""; $about = ""; foreach($currentPages as $currentPage){ $page_id = $currentPage->id; $pageName = $currentPage->pageName; $visible = $currentPage->visible; $pageZone = $currentPage->pageZones_id; $pageCRUD = $currentPage->pageCRUD_id; $pageType = $currentPage->pageTypes_id; $module = $currentPage->module_id; $title = $currentPage->title; $sub_title = $currentPage->sub_title; $description = $currentPage->description; $image = $currentPage->image; $about = $currentPage->about; if($pageName == $pName){ echo $pageName.'<br/>'; echo $page_id.'<br/>'; echo $visible.'<br/>'; echo $pageZone.'<br/>'; echo $pageCRUD.'<br/>'; echo $pageType.'<br/>'; echo $module.'<br/>'; echo $title.'<br/>'; echo $sub_title.'<br/>'; echo $description.'<br/>'; echo $image.'<br/>'; echo $about.'<br/>'; } } ?> i would like to be able to just put global $page or something like that to get all the db info for each page. i tried this in my includes/pages.php includes file but it cant get the page name. Code: [Select] public static function find_by_pageName(){ global $database; global $pName; $sql = "SELECT * FROM ".self::$table_name." WHERE pageName=".$pName.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } any suggestions ???? whats the best way to do this ? thanks ricky Sorry, this will be a simple question. Say you define two global variables in your functions.php file as: GLOBAL $salesTax = .07; GLOBAL $shipping = 5.00; Those variables would be accessiible in the checkout.php page, right? Can someone tell me what some of the purposes of this would be? global $PHP_SELF; its defined right after a function like this function myFunction(module =' '){ global $PHP_SELF; .... } Thanks Hey, I've been developing a browsergame. In this you are able to produce something ("weed"). Now I've got some kind of trouble with the function that is responsible for updating the "weed" on the user accounts. Im going to explain, how my script is working First step: Loading the datas from "worlds". In this case id, weed_factor, weed_basis. What this is required for you will see in the next steps <?php include 'includes/settings/mysql.php'; mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbbase); $time = time(); $update_weed_world_data_sql = "SELECT id, weed_factor, weed_basis FROM worlds"; $update_weed_world_data_res = mysql_query($update_weed_world_data_sql) OR DIE (mysql_error()); while($update_weed_world_data_while = mysql_fetch_assoc($update_weed_world_data_res)){ $update_weed_world_id = $update_weed_world_data_while['id']; $update_weed_world_basis[$update_weed_world_id] = $update_weed_world_data_while['weed_basis']; $update_weed_world_factor[$update_weed_world_id] = $update_weed_world_data_while['weed_factor']; global $update_weed_world_basis; } Second step: This is the function which is editing each account by the data given as parameters. function do_update_weed($profile_id,$world,$update,$level,$time){ $update_weed_period = $time - $update; $update_weed_add = ($update_weed_period / 3600 * $update_weed_world_basis[$world] * pow($update_weed_world_factor[$world],$level)) +1; echo $update_weed_world_basis[$world]; echo "<br>"; mysql_query("UPDATE profiles SET weed = weed +$update_weed_add, weed_update = $time WHERE id = $profile_id LIMIT 1"); } Note: echo $update_weed_world_basis[$world]; doesnt result an output. In step three, the accounts are loaded: function todo_update_weed($time){ $todo_update_weed_sql = "SELECT * FROM profiles WHERE weed_update < $time"; $todo_update_weed_res = mysql_query($todo_update_weed_sql) or die (mysql_error()); while($todo_update_weed_while = mysql_fetch_assoc($todo_update_weed_res)){ do_update_weed( $todo_update_weed_while['id'], $todo_update_weed_while['world_id'], $todo_update_weed_while['weed_update'], $todo_update_weed_while['level_farm'], $time ); } } And the last step is calling function "todo_update_weed" with the time. todo_update_weed($time); I script calculate the time between the last update and the current time. This make a difference in time. With this value I calculate something else. And then the update time has to be saved. The script has just working fine, when I set the variable "$update_weed_add" with a fix value. But by now the script doesn't work, because I don't know how to make the array available inside functions. I considered whether I put the database-function for the world_data inside the function that updates the profiles. But if I do this, the database will be called thousands of times... Hope anybody has a nice idea to fix the problem |