PHP variables lost their values? - php

So, I'm trying to build a template-loader system with PHP. Here's what I got so far:
config.php:
<?php
$style_assets_path = "/includes/styles/";
$template = "";
if ($_GET['pageid'] <= 100) {
$template = "/main/main.php";
}
function loadTemplate() {
global $style_assets_path;
global $template;
require_once dirname(__FILE__) . $style_assets_path . "templates" . $template;
}
?>
home.php:
<?php
$page_title = "Homepage";
$menu_selected = "active";
$menu_selected_2 = "";
$menu_selected_3 = "";
$menu_selected_4 = "";
$content_heading = "Featured Content";
$page_contents = "";
$special_id = "home";
require_once dirname(__FILE__) . "/config.php";
if ($_GET['pageid'] !== '1'){
header('Location: /home.php?pageid=1');
exit(0);
}
loadTemplate();
?>
So the variables:
$page_title = "Homepage";
$menu_selected = "active";
$menu_selected_2 = "";
$menu_selected_3 = "";
$menu_selected_4 = "";
$content_heading = "Featured Content";
$page_contents = "";
$special_id = "home";
don't have their values even if declared?
What am I doing wrong?

You are calling require_once inside a function, so only local variables and ones declared global will be available to the required file.
function loadTemplate() {
global $style_assets_path;
global $template;
require_once dirname(__FILE__) . $style_assets_path . "templates" . $template;
}
You would need to declare all these variables global, like so.
function loadTemplate() {
global $style_assets_path,
$template,
$page_title,
$menu_selected,
$menu_selected_2,
$menu_selected_3,
$menu_selected_4,
$content_heading,
$page_contents,
$special_id;
require_once dirname(__FILE__) . $style_assets_path . "templates" . $template;
}
UPDATE:
It's not clear how the files are organized, but it might be necessary to set all the variables with global.
global $page_title = "Homepage";
As said in the comments, this is probably not the best way to make a template engine.

include() and require() work as if you've literally cut/pasted the included text into the location where you called include()/require(). Since you're doing your include() INSIDE a function call, the variables you set are inside that function's scope. When you return from the function, the variables are destroyed as part of the post-function cleanup.
e.g. consider this:
inc.php:
<?php
$foo = 'bar';
test.php:
<?php
function baz() {
include('inc.php');
echo "Inside baz(): $foo\n";
}
baz();
echo "Outside baz(): $foo\n";
You get this as output:
inside baz(): bar
PHP Notice: Undefined variable: foo in /home/marc/test.php on line 9
Outside baz():
Note how the "outside" output produced an undefined variable notice.

Related

variable scope in php function

Here is my script.
I declared few variable outside function. I want to use it in function, would it be available?
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('follow.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$userid = $content->{'id'};
$temp = "1";
$tweets1 = $connection->get("https://api.twitter.com/1.1/statuses/retweets_of_me.json?count=200");
$tweets3 = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?trim_user=true&include_rts=true");
$tweets4 = $connection->get("https://api.twitter.com/1.1/statuses/home_timeline.json?include_rts=true&trim_use=true");
foreach ($tweets1 as $item)
{
$text = $item->text;
$follow_count = getfollow($m[1]);
echo "followe count is $follow_count <br>";
lookup($item->user->id_str);
}
function lookup($userid)
{
//echo "userid : $userid temp : $temp";
$tweets5 = $connection->get("https://api.twitter.com/1.1/users/lookup.json?user_id='.$userid.' ");
$CONNECTION IS not availabl here? WHY?
foreach ($tweets5 as $item)
{
$text = $item->name;
}
return;
}
?>
A function has its own scope. You have to provide all variables you want to use in arguments except if they are in the $_SESSION, $_SERVER etc. variables.
Hand it over via parameter:
function lookup($userid, $connection) {
//code here
}
Only Superglobals are availible inside functions. Everything else is handed over via parameters.
You can use outside variable by defining them as global or you can pass them to functions as a parameters.
$str= 'str';
function test()
{
global $str;
echo $str;
}
or
function test($str)
{
echo $str;
}
using the global keyword should do the trick:
$foo = '123';
function bar() {
global $foo;
echo $foo;
}
but the way I see it, you could just pass the variable to that function instead.

If statement doesn't work in a function

Not sure if this is a common problem or not, but I ran upon it. When trying to put a if/else statement into a function, it simple does not work. But when do the if/else without the function, it does work (So, I know that the if/else is correct).
I have 2 separate documents, Home.php and Functions.php here is what I have inside those files"
Home.php (the PHP)
<?php
$db = new PDO("mysql:host=localhost;dbname=TEST;charset=utf8","Xero","");
include("Functions.php");
menu();
?>
And then we have the Functions.php (the PHP)
<?php
$db = new PDO("mysql:host=localhost;dbname=TEST;charset=utf8","Xero","");
function menu() {
echo "
<div id='menu'>
<div id='user-menu'>
";
// Check AutoLogin-User then :
$getAutoUser = $db->prepare("SELECT * FROM `users-PHP_FNC` WHERE `ip`='" . $_SERVER['REMOTE_ADDR'] . "'");
$getAutoUser->execute();
if ($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC)) {
echo "
" . $autoUser['user'] . "
";
}
// If no AutoLogin-User was found:
else {
echo "
Test
";
}
echo "
</div>
</div>
";
}
?>
Not sure why this doesn't work. Are you not allowed to have if/else statements in a PHP function?
Actually, you can be sure that if ... else statements work inside the scope of a function.
Therefore, the problem lies elsewhere... But there is another thing that you should do:
// Replace this
if ($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC))
// By this
if ($autoUser == $getAutoUser->fetch(PDO::FETCH_ASSOC))
Why ?
Because when you say if ($something = $somethingElse) you tell PHP different things in a particular order:
1st => assign the current value of $somethingElse to $something
2nd => test if $something and $somethingElse share the same value
2nd becoming obviously true because of 1st.
To bypass the 1st step, simply use == in place of =.
$db is not in the function's scope. You would have to pass it in. I would make my code more like:
// connect.php - should be in a separate secure folder I'll call restricted
<?php
function db(){
return new PDO('mysql:host=localhost;dbname=TEST;charset=utf8', 'Xero', '');
}
?>
// index.php
<?php
include_once 'restricted/connect.php';
function menu(){
$db = db();
echo "<div id='menu'><div id='user-menu'>";
// Check AutoLogin-User then :
$getAutoUser = $db->prepare("SELECT * FROM `users-PHP_FNC` WHERE ip='{$_SERVER['REMOTE_ADDR']}'");
$getAutoUser->execute();
if($autoUser = $getAutoUser->fetch(PDO::FETCH_ASSOC)) {
echo $autoUser['user'];
}
else{
// If no AutoLogin-User was found:
echo 'Test';
}
echo '</div></div>';
}

PHP variable scoping

I'm having some trouble with variable scoping in PHP. Here's the structure of my code--
<?php
$loader = new ELLoad();
$sessionid = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
global $loader;
$loader->load($file['text']);
global $sessionid;
$sessionid = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
global $sessionid;
$extractor->extract($sessionid); //$session id for some reason is still ' ' here
}
The sequence of the requests from the client is always load followed by extract. Can anyone tell me why my $sessionid variable may not be getting updated right?
$sessionid is still '', because It's not change if first condition == false
Improvement of your code:
$loader = new ELLoad();
$sessionid = $loader->getSessionId();
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
$loader->load($file['text']);
// do more stuff
}
else if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
$extractor->extract($sessionid);
// do more stuff
}
Also It's better to use $_GET or $_POST depend on your case, instead of $_REQUEST and finally using else if in separate and repeated conditions.
You don't have to declared global $... unless you're in a function. A block (if, while, ...) have the same scope than the line just before.
I don't know what you want to do, but you have to keep you $sessionid content in a real session, like:
<?php
session_start();
$loader = new ELLoad();
$_SESSION['id'] = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
$loader->load($file['text']);
$_SESSION['id'] = $loader->getSessionId();
}
if (strcasecmp($method, "extract") == 0) {
$extractor = new ELExtract();
$extractor->extract($_SESSION['id']); //$session id for some reason is still ' ' here
}

How to get $var outside the function without using global php?

Need small help here. Was reading how bad it is to add global var within function and call it outside but having small issue getting the vars outside. Global helped but I want to be safe also since I am handling some files here
my loop is this
<?php
require_once('functions.php');
?>
<?php
foreach( $files as $key=> $file ){
global $download_link;
get_file_info($key,$file);
?>
<span><?php echo $file->name ?></span>
<?php } ?>
PART of my function.php / is about 150 lines long but this is main snipp
function get_file_info($key,$file){
global $download_link;
$access = explode(",",$file->access);
$permission = in_array(1,$access);
if($permission){
$download_link = 'ok to download';
}else{
$download_link = 'canot download';
}
}
beside the link var I also have few others like date , counter etc but they are all bound by some condition.
I tried to do
return $link; at the end of the function instead using global but getting undefined variable error;
SO base question here is , how to get the download_link var outside the function without using global ?
You can do this a lot easier by modifying your File class
class File {
# ...
function get_url() {
return in_array(1, explode(',', $this->access))
? $this->url # return the file's url
: "/path/to/subscribe" # return a default path for non-access
;
}
}
Your HTML would use it as follows
<?php
foreach ($files as $file) {
echo 'Download this '.$file->name.'';
}
Since you just use get_file_info to set $download_link, why not just return $permission and define $download_link outside the function?
<?php
function get_file_info($key,$file){
$access = explode(",",$file->access);
$permission = in_array(1,$access);
return $permission;
}
foreach( $files as $key=> $file ){
$download_link = 'canot download';
if(get_file_info($key,$file)) {
download_link = 'ok to download';
}
echo '<span>'. $file->name . '</span>';
}
?>
You may change your loop like this:
<?php
require_once('functions.php');
?>
<?php
foreach( $files as $key=> $file ){
$download_link = get_file_info($key,$file);
?>
<span><?php echo $file->name ?></span>
<?php } ?>
And your function code:
function get_file_info($key,$file){
$access = explode(",",$file->access);
$permission = in_array(1,$access);
if($permission){
return 'ok to download';
}
else {
return 'canot download';
}
}

Where in Wordpress will i include my file so i can access its variables throughout the rest of the page?

I tried including my file in header.php or my theme's index.php, but I cannot access the variables in the included file from let's say my theme's footer.php or even my theme's page templates.
Here's what I'm including:
<?php
// some parameters
$var_research = 5;
$var_researchtrans = 7;
$var_output = 9;
$var_edit_indi = 11;
$var_contact = 15;
$var_transition = 19;
?>
Now what I need is to be able to use the variables in footer.php, for example.
Hope someone out there has an answer. Thanks, y'all.
OK, here's how I made it work:
In functions.php
<?php // functions.php
// ...
function my_var($va_var) {
// some parameters
$var_research = 5;
$var_researchtrans = 7;
$var_output = 9;
$var_edit_indi = 11;
$var_contact = 15;
$var_transition = 19;
$var_sometext = "text test";
eval("\$return_var = $" . $va_var . ";");
return $return_var;
}
?>
and in footer.php
<?php // footer.php
// ...
echo "blah blah " . my_var("var_sometext");
// ...
?>
It's working, but did I do it right? is there a better/right way to do this? Thanks again, everyone.
The best place to include your own functions are in your theme's functions.php file.
If you want to access a variable in multiple files, you can create a function in your functions.php and access that function anywhere within the theme.
In functions.php
function your_variable()
{
$var = 'your variable';
return $var;
}
And in your footer.php
echo your_variable();
For your updated query
function my_var($va_var) {
$out = array();
// some parameters
$out['var_research'] = 5;
$out['var_researchtrans'] = 7;
$out['var_output'] = 9;
$out['var_edit_indi'] = 11;
$out['var_contact'] = 15;
$out['var_transition'] = 19;
$out['var_sometext'] = "text test";
return $out[$va_var];
}
I'm not sure what your function does, but the place to define functions is in your themes functions.php file.
humm , the original solution for this problem is that you must save your vars as an option variable in wordpress , something like this :
<?php add_option( $name, $value, $deprecated, $autoload ); ?>
and the function :
<?php
function my_var($va_var) {
add_option( 'var_research', '5', '', 'yes' );
}
?>
and in the footer.php you just need to use this for retrieve your variable:
<?php _e(get_option('admin_email')); ?>
Good Luck

Categories