PHP:Defing a global scope variable - php

I am in a situation .
My php folder structure is like
UI
user
login.php
logout.php
jquery
somejs
css
somecss
blah.php
blah.php
Now to import any css ,js or any php file i am using the file path like
localhost/UI/user/index.php // example
Now i am trying to define a global variable on any page like
<?php
$somevar = "localhost";
GLOBAL $somevar;
?>
So that i could import any css js like
<?php echo $somevar ;?>/UI/user/index.php // example
Problem : It is working on that page only where i declared the variable as GLOBAL
I want to use the variable on each page and don't want to use include
Is there any other alternative to define a variable for files folder in php ?

You do not declare variable with global. You just make it available within you method or function body even it was set (or using your terminology "declared") outside of it. So there's no way to have the variable unless it is declared. And there's no way to do that without running the PHP code (simplification, but it does not matter here). And code is not coming from nowhere, hence the need of include or require of said code that sets variable.
You may try to use php.ini's auto_include_file to have your variables auto-included, but still, the PHP code needs to be used for that.
But you generally doing it wrong. move all global variables into class, set autoloader and access i.e. statically. The code will be much cleaner.

Well, my experience says .. global is used for accesing variables inside the function those which defined outside the function.
There can be many different solutions to the same, one i will suggest is use sessions or cookies. Store the data in session / cookies and access it across wherever required.

You have to use define() function for this purpose
config.php
<?php
define("host", "localhost");
?>
now include this page wherever you want to access HOST variable.
you can access this variable like this echo host;

You can use the special PHP-defined $GLOBALS array. The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal
You may not need to define a global variable to apply the css, js or any static files viz Images etc to your application. you may use relative path to include js and css files. You can refer to this article to know more about relative and absolute path.

Related

Passing arguments via url parameters inside include function in php

Suppose, I have an index.php file like this:
<?php
$id=2;
include('php/config.php');
require_once "php/variables.php";
?>
Is there any way to pass the variable $id via url parameter to config.php and variables.php files so that I can perform some tasks based on the variable after getting it
by $_GET['id']?
You can use $id in both file, because you are already including those two file in your current file so you can able to access $id, try to print echo $id; in both files and you can see the value.
Yes, You can directly access $id in both files as saied by Karthik.
Or you can use global variables
include('php/config.php');
require_once "php/variables.php";
The include and require_once functions, take a filesystem path by default; not a URL. Consequently "URL parameters" (and the corresponding $_GET superglobal) are irrelevant here, because you are not passing a URL.
(Yes, you can pass a URL to these functions if you have the appropriate fopen wrappers set and this will trigger an HTTP request - but this is most probably not what you want to do here.)
The include and require_once functions include the referenced document in-place and therefore inherit the current scope. Consequently the $id variable will be available as-is to these included scripts (as the other answers have already pointed out).

How to use a variable from another php file

I know similar questions have been asked, but unfortunately I didn't manage to solve the problem after going through them.
Assuming this situation: In one.php I'm retrieving some data from an input field and saving it as a variable and later on I require two.php
one.php
$rejon = $_POST['rejon'];
require 'two.php';
two.php
--here I would like to use $rejon ---
When I try to use $rejon in two.php, it doesn't work (I try to insert it into a database to be exact). On the other hand, if I don't require the two.php but instead paste the code into one.php, it works.
I don't understand why this happens. W3schools claims that "The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement." - http://www.w3schools.com/php/php_includes.asp
but it doesn't seem to work like a copy as manualy copying gives other results (variable $rejon is accesible).
1) What exactly does require do and what are its limitations?
2) Most importantly - how do I retrieve that $rejon variable in two.php?
Works for me:
$ cat one.php
<?php
$rejon = 'this value came from POST';
require 'two.php';
$ cat two.php
<?php
echo $rejon . PHP_EOL;
$ php one.php
this value came from POST
The W3Schools description is, unsurprisingly, misleading. Nothing is copied. The contents of the file are read, evaluated, and inserted at the point of the require. With respect to variables, the PHP manual says this:
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
Which is why my example above works as it does.
To diagnose this issue, continue to simplify your code to reduce it to the simplest possible example. If you're trying to use $rejon in a function inside of two, then you need to make the variable global. Like:
global $rejon;
$rejon = $_POST['rejon'];
// now you have $GLOBALS['rejon'] everywhere
Side note, $_SESSION should not be necessary unless you're crossing a page refresh boundary.
You can do this by the following two ways
1.Using Session
You can store the data in the session and than you can use it in the another file two.php
one.php
<?php
session_start();
$rejon = $_POST['rejon'];
$_SESSION['rejon'] = $rejon;
?>
two.php
<?php
session_start();
echo $_SESSION['rejon'];
?>
2. Including that file
I have found that you are including the file two.php in your script. If you are including this file than you can directly use the variable $rejon
two.php
<?php
echo $rejon;
?>
You can use sessions http://php.net/manual/en/book.session.php or a constant http://php.net/manual/en/language.constants.php.
Utkarsh already provided some examples for sessions.
To define a constant you use the define() function.
define('CONSTANT_NAME', CONSTANT_VALUE);
As long as your constant is defined and included (if in another file) before you use it you can then call CONSTANT_NAME in your code to get the value.

How to make a PHP variable available in all pages

I recently took a dive into wordpress, and I noticed something really unusual, When coding I noticed that a particular variable called the $post variable was available for me to manipulate whenever I need it, as along as my page is within the wp-includes, wp-themes or wp-plugins folder without me calling any external page or function.
So I started developing a site without wordpress hoping to understand the mystery behind that anomaly..
I would appreciate all help on making me understand this phenomenon. I would like to use such technique in building sites. Thanks...
That's not an anomaly. That variable is present in global scope and is being defined in either of the files that you have mentioned. You can easily do it like
include.php
<?php
$myGlobal="Testing";
?>
anyfile.php
<?php
include "include.php";
echo $myGlobal;
?>
And you can use it in your functions as well, as long as you refer to the global one, for example
anotherfile.php
<?php
include "include.php";
function test()
{
global $myGlobal;
echo $myGlobal;
}
test();
?>
Theory
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well
By declaring (a variable) global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
Go through this PHP Doc once and you will have much better idea of how it all works.
Take a look at global variables:
http://php.net/manual/en/language.variables.scope.php
and superglobal as well:
http://www.php.net/manual/en/language.variables.superglobals.php
php.ini
register_globals = on
$post
$get
will be available anywhere

Wordpress php page $GLOBALS problem

Hi I've an issue while dealing with a php code inside Wordpress;
I've my aaa.php file wich contains code:
<?php
require_once("lang_file.php");
echo $GLOBALS['general']['username'];
?>
My lang_file.php contains:
<?php
$language['general']['username'] = 'User';
?>
And my Wordpress page contains this:
<?php
include("aaa.php");
?>
If i access directly aaa.php through browser i get the "User" message from the echo on aaa.php.
If i access the Wordpress page with include code it doesn't show nothing. I've already read this answer: Does WordPress clear $GLOBALS?
And i tried to define the variables on lang_file.php as $GLOBALS but this still don't work.
You'd need to use
$GLOBALS['language']['general']['username']
instead.
In PHP, $GLOBALS is an array of all variables defined globally. The first element of the array is the global variable name.
Therefore, to access the global variable $language via $GLOBALS, you would need to use $GLOBALS['language']. You can then append any array structure after that which you want to reference from $language.
You can also access it directly via the name $language if you prefer, by adding global $language; to the code prior to where you want to use it.

PHP: Pass a variable to a file you are including?

I am wondering if there is a way to pass a variable to a file you are including via include()?
I tried this but got an error:
include("header_alt.php?img=hey");
Is there a way to do that?
Thanks!
Just define your variable in the first file ; for instance, in temp.php :
<?php
$my_var = 10;
include 'temp-2.php';
die;
?>
And use it in the second file ; temp-2.php :
<?php
var_dump($my_var);
?>
And it should work : I'm getting this output, from temp-2.php :
int 10
The query-string syntax, using stuff like ?img=hey is used when you are requesting some data from a distant server (like when you are using your browser to surf on websites), not when including a file that is on the same server.
Smarty provides a really good mechanism for this sort of thing. Plus, using Smarty just makes for better php applications.
http://www.smarty.net/manual/en/language.function.include.php
Variables can be passed to included
templates as attributes. Any variables
explicitly passed to an included
template are only available within the
scope of the included file. Attribute
variables override current template
variables, in the case when they are
named the same.
All assigned variable values are
restored after the scope of the
included template is left. This means
you can use all variables from the
including template inside the included
template. But changes to variables
inside the included template are not
visible inside the including template
after the {include} statement.

Categories