PHP - Initialize Global Variables
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. 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 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. 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? 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 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, 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 hello. i want to create an oop website on my localhost but im having trouble getting the initialize file to find my config file. if i point my browser to my local host my index page works fine because it does not need the initialize file at this stage, but if i point my browser to my admin index (http://localhost/djsonrotation/admin/) i get this error Quote Warning: require_once() [function.require-once]: URL file-access is disabled in the server configuration in /Applications/MAMP/htdocs/djsonrotation/includes/initialize.php on line 9 Warning: require_once(http://localhost/djsonrotation/config.php) [function.require-once]: failed to open stream: no suitable wrapper could be found in /Applications/MAMP/htdocs/djsonrotation/includes/initialize.php on line 9 Fatal error: require_once() [function.require]: Failed opening required 'http://localhost/djsonrotation/config.php' (include_path='.:/Applications/MAMP/htdocs/php5/lib/php') in /Applications/MAMP/htdocs/djsonrotation/includes/initialize.php on line 9 the initialize file is basically 1 place that points to lots of different places and mine looks like this: Code: [Select] <?PHP defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR); defined('SITE_DOMAIN') ? null : define('SITE_DOMAIN', 'http://localhost/djsonrotation'); defined('SITE_ROOT') ? null : define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT']); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_DOMAIN.DS.'includes'); defined('CSS_PATH') ? null : define('CSS_PATH', SITE_DOMAIN.DS.'css'); require_once(SITE_DOMAIN.DS.'config.php'); require_once(SITE_DOMAIN.DS."functions.php"); require_once(SITE_DOMAIN.DS."session.php"); require_once(SITE_DOMAIN.DS."database.php"); require_once(SITE_DOMAIN.DS."user.php"); ?> this is the config file its looking for: Code: [Select] <?PHP defined('DB_SERVER') ? null : define("DB_SERVER", "localhost"); defined('DB_USER') ? null : define("DB_USER", "admin"); defined('DB_PASS') ? null : define("DB_PASS", "*************"); defined('DB_NAME') ? null : define("DB_NAME", "djsonrotation"); ?> this is how my mamp is set up Quote PORTS - 80 - 3306 PHP - 5 APACHE - /Applications/MAMP/htdocs this is where my file are located on my wwwroot /index.php /includes/initialize.php /includes/config.php /admin/index.php this is the line of code calling the initialize on /admin/index.php Code: [Select] require_once("../includes/initialize.php"); thanks rick Hello All,
I've encountered one more problem (with the first WebApp I'm building), and I have no idea how to fix it. I've tried something, but it doesn't seem to work, so I'd appreciate some help in getting it fixed.
Here's what's happening:
So after I perform an operation (let's say "ADDing a record")...the records gets added correctly, but then, if/when I press [F5] in my browser window (or click on the Refresh/Reload icon), the same input details are being used and a second identical record is being added. I believe the same thing happens for some (or perhaps all) of the other CRUD operations.
What do I need to do to disable that behavior?
The only thing I could think of is to set the $functionSelected variable to blank ("") - which I've done towards the bottom of my code (shown below) - but that doesn't seem to be doing anything...the problem persists.
if(isset($_POST['action'])) { $functionSelected = $_POST["action"]; } if(isset($functionSelected)){ switch($functionSelected){ case "insert": $initialize_flag = "N"; // Store POST(ed) user-entered values into memory variables $store_name = $_POST['store_name']; $item_description = $_POST['item_description']; $qty_pkg = $_POST['qty_pkg']; $pkg_of = $_POST['pkg_of']; $price = $_POST['price']; $flyer_page = $_POST['flyer_page']; $limited_time_sale = $_POST['limited_time_sale']; $flyer_date_start = $_POST['flyer_date_start']; $nos_to_purchase = $_POST['nos_to_purchase']; // Setup customized query $sql = "INSERT INTO shoplist (store_name, item_description, qty_pkg, pkg_of, price, flyer_page, limited_time_sale, flyer_date_start, nos_to_purchase, shopper1_buy_flag, shopper2_buy_flag, purchased_flag, purchase_later_flag) VALUES (:store_name, :item_description, :qty_pkg, :pkg_of, :price, :flyer_page, :limited_time_sale, :flyer_date_start, :nos_to_purchase, :shopper1_buy_flag, :shopper2_buy_flag, :purchased_flag, :purchase_later_flag)"; try { $statement = $conn->prepare($sql); $statement->bindParam(':store_name', $store_name); $statement->bindParam(':item_description', $item_description); $statement->bindParam(':qty_pkg', $qty_pkg); $statement->bindParam(':pkg_of', $pkg_of); $statement->bindParam(':price', $price); $statement->bindParam(':flyer_page', $flyer_page); $statement->bindParam(':limited_time_sale', $limited_time_sale); $statement->bindParam(':flyer_date_start', $flyer_date_start); $statement->bindParam(':nos_to_purchase', $nos_to_purchase); $statement->bindParam(':shopper1_buy_flag', $initialize_flag); $statement->bindParam(':shopper2_buy_flag', $initialize_flag); $statement->bindParam(':purchased_flag', $initialize_flag); $statement->bindParam(':purchase_later_flag', $initialize_flag); // Execute the query $statement->execute(); $statement->closeCursor(); $functionSelected = ""; // WILL THIS STATEMENT NOT SERVE TO INITIALIZE/RESET THE OPERATION??? break; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; } case "update-delete": ... ... ...Thanks. 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 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 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 = ""; } } 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? 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 ? 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. Through out my program I have used global $mysqli; as a connection to my database - this has worked fine so far. Now I have called $sql_statement = "SELECT * FROM items WHERE name='$itemName'"; $itemStats = mysqli_fetch_array(mysqli_query($mysqli, $sql_statement), MYSQLI_ASSOC); via a function and I get the following warnings - Quote Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /functions/getdata.php on line 27 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /functions/getdata.php on line 27 it still works though and returns the correct information. If I take the code out of the function and use it normally then I get no Warnings - but this defeats the whole purpose of having functions! How do I get rid of the warnings? (and no, I don't mean turn the warnings off ) 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? 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 |