I am wondering what is the best option to use variables in an included file who are declared in his parent file.
When I want to check privileges in an included file because I do not want to copy the whole function to any file I want to check the privileges.
I tried a few ways. Which is the best, or should I do it another way?
just include:
<?php
// head file
$userlevel = 2;
$minimumlevel
include('testprivileges.php');
?>
<?php
// testprivileges file
if ($userlevel < $minimumlevel){
die('no privileges');
}
or
<?php
//head file
$userlevel;
$minimumlevel
include('checkprivileges.php?userlevel=$userlevel&minimumlevel=$minimumlevel');
// i dont care this wont work. you understand what I try to do
?>
<?php
$userlevel = $_GET['userlevel'];
// and check for privileges
?>
or
<?php
// testprivileges function file
function testprivileges($userlevel, $minimumlevel){
if($userlevel < $minimumlevel){
die('no privileges');
}
}
?>
<?php
//head file
$userlevel = 2;
$minimumlevel = 3;
include('testprivilegesfile.php');
testpriviles($userlevel, $minimumlevel);
?>
or are all of those options bad?
Your first code works, and its the best practice.
Your second example is bad because this:
include('checkprivileges.php?userlevel=$userlevel&minimumlevel=$minimumlevel');
cant work.
Your last code is also a bad practice because you have to copy paste the same function to every file. Not only is that duplication of code, but also hard to manage.
Like I said, the first code works best.
Some notes though:
$userlevel Should come from high above. You shouldn't have to re-declare it in every file. Just set it once in a global config.php.
$minimumlevel = minimum level for current page?
Ideal code:
<?php
$minimumlevel = 1;
require_once ('includes/config.php'); // Contains $userlevel
Checkrights($minimumlevel);
?>
functions.php
function Checkrights($minimumlevel){
global $userlevel;
if ($userlevel < $minimumlevel){
die('no privileges');
}
}
config.php
require_once ('functions.php');
$userlevel = 2;
Bitwise permission system
If you are really into a better permission system you might want to hit this tutorial about the bitwise permission system. I use it myself and its VERY simply. If you create a new table in SQL containing some permissions, you can give privileges PER module per sé. Highly recommended.
http://www.php4every1.com/tutorials/create-permissions-using-bitwise-operators-in-php/
Simply just include in the beginning of the file if you will use it.
<?php
include("testprivileges.php");
//use to check privilege
?>
Related
This is my code in index.php
include ($_GET['page']);
Actully i need to include page from url like
"?page=go.php"
on the other-hand i can not filter
"?page=example.com"
as for some case i need to include this value also. But this is a remote file inclusion (RFI) vulnerability. how can i prevent RFI attack from my site?
I am doing something like
$filename = $_GET['page'];
if (file_exists($filename)) {
{
include ($_GET['page']);
}
But it filters only
"?page=go.php"
this shorts of page.
And i am sucked with
"?page=example.com"
this shorts of page.
If I understand the question correctly; You could setup an array with 'allowed' pages such as:
$allowedPages = array('go.php', 'stop.php', 'file.php');
$filename = $_GET['page'];
if(in_array($filename, $allowedPages) && file_exists($filename)){
include ($filename);
}else{
//output error
}
I think this answer is too late, but for those who might search for this problem, I guess it can be done like this, too:
1.Define a constant with full path.
2.Define a white-list of allowed pages.
3.Get the $_GET variable, and convert it to lower case.
4.Then if the page returned by $_GET variable is in your white-list array, then require it, otherwise, redirect the user to the home page, and display an error message.
<?php
# this is abcd.php
define('SITE','http://www.yoursite.com/');
$allow = [SITE.'1.php', SITE.'2.php', SITE.'3.php'];
$get = strtolower(SITE.$_GET['page']);
if(in_array($get,$allow)){
include $get;
} else {
header('Location: index.php?param=incorrect');
}
?>
<?php
# this is index.php
if(isset($_GET['param']) && $_GET['param'] == 'incorrect'){
?>
<script type="text/javascript">
alert("INCORRECT PARAMETER PROVIDED");
</script>
<?php
} else die('ERROR');
I'm not 100% sure this will work without any probs, but I guess is a good start and you can play around with it and figure out what's suitable for you.
To be honest, your method of creating a dynamic website is definitely not the way to go.
To answer within the scope of this question, you'd do something like the following:
You'd have to set up a whitelist of files that are**ALLOWED** to be included through this function.
That could look something like this:
<?php
$whitelist = array(
'file1.php',
'file2.php',
'file3.php',
'file4.php',
'file5.php',
);
?>
Now before including the said file, you'd run a check with in_array()
<?php
if(in_array($_GET['page'] . '.php', $whitelist) && file_exists($_GET['page'] . '.php')) {
include($_GET['page'] . '.php');
}
?>
This, as you can see is not very pretty!
Another alternative would be doing something like:
<?php
$file = strtolower($_GET['page']) . '.php';
if(isset($whitelist[$file]) && file_exists($file)) {
include($_GET['page'] . '.php');
}
?>
Don't accept a page.php parameter, but just the name of the file.
"?page=go"
Then check if $_REQUEST["page"] is alphanumeric
if (ctype_alnum($_REQUEST["page"]))
And just don't give non-alpha-numeric names to your files.
Then do if file_exists on $_REQUEST["page"] and you should be quite good.
PS
$_REQUEST["page"] is about the same with $_GET["page"], it just intersects with $_POST
You can filter other domain urls instead of filtering files.
If parameter contains a hostname less than 3 letters, it is fine as no domain is 2 letters.
$tmp= parse_url ($_GET['page']);
if(strlen($tmp['host'])<3)
include($_GET['page']);
If there are some trusted hosts then you can validate them too.
I have a file called admin.php in which I have a button with the name send. What I want to do is when I click it, to make visible a link on the user's page, user.php. How can I do this?
I have a file with all my functions called functions.php in which I have a function called onSubmit($var); I initialize the variable $var is admin.php with the value $_POST['send'] but when I call the function in the file user.php I have no way of telling him who the variable $var is so I get 'undefined index'.
Is there another way to do this?
EDIT Added code
This is admin.php
<input type="button" name="send" value="Submit" /><br/>
require 'functions.php';
$posted = $_POST['send'];
onSubmit($posted);
This is user.php
require 'functions.php';
onSubmit($var); //here it says undefined index var because it doesn't know who the variable is
if($isSent == 1) {
<a style="visibility:visible;" href="test3.html" id="test3">Test3</a> <br/>
}
And this is functions.php
global $isSent;
function onSubmit($var) {
if(isset($var)) {
$isSent = 1;
}
}
Basically you need to use sessions like below:
if(isset($_SESSION['makeVisible']) && $_SESSION['makeVisible'] == true){
echo '<button>Button init</button>'; //you could also use html like the comment below.
}
/*
if(condition){?> <!-- this is now html --> <button>Button init</button><?}
*/
Then to set this variable on your admin page use:
if(isset($_POST['submitButton'])){
$_SESSION['makeVisible'] == true;
}
You'll also need a form for this method to work but there are other methods but I prefer this one.
<form name="buttonMakerThing" method="POST">
<input name="submitButton" value="Make button init Visible" type="submit"/>
</form>
Without an action the form defaults to 'POSTING' the form information to the current page. Making the condition if(isset($_POST)) return true.
You will need to add a $_SESSION declaration at the top of every php page you have on your site for this to work. It MUST go on the very first line of every page! for example:
01: | <?php session_start();
02: |//rest of script;
Please look more into $_SESSIONS for unnsetting/destroying your sessions and more uses for them :) http://php.net/manual/en/reserved.variables.session.php
Right I've done a bit of research on Caching and this is what I've come up with. It might not be 100% correct but it's a start as like I've said I've never tried it myself lol
In your admin.php I'd put this function in:
if(isset($_POST['send'])){
if($enabled == true){
$enabled == false;
}
else{
$enabled == true;
}
apc_add('enabled',$enabled);
}
Now to 'get' our $enabled var:
$enabled = apc_fetch('enabled');
Then to check the the var within your client page:
if($enabled == true){
echo ' button';
}
Now the only things I haven't fully looked at is the security of the apc_ function and the client usage. I believe it works for all clients of the server but I'm not 100% certain. Here the php manual to give better examples.
This is the method I was thinking of. But again I'm not sure on the security of it but I'm sure you can find something to keep it secure. The video is actually is tutorial for a Youtube API. But he does cover saving a variable to a cache text file which should be of use to you :)
If you have functions.php which defines functions, simply include it in admin.php file and then you can call the function from there and also pass value.
I keep getting an 'Undefined variable' notice when I call on an object I 'think' I have instantiated, but apparently haven't. I can't put a finger on my the error. The object is $fgmembersite, according to my error messages it doesn't exist, I'm confused about why. It maybe a simple case of me messing up my directories in the include/require portion of my scripts but I've been looking at them and can't see anything wrong. Tell me if you guys want to look at my file hierarchy.
And again thanks for the help!
I have three PHP files that are at play.
First one is login-home.php
<?PHP
require_once("./profile_settings/view.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("login.php");
exit;
}
?>
/*a bunch of stuff*/
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation(); ?>"></img>
/*a bunch of stuff*/
Next I have view.php which holds a function I use to generate the path-name of where I store my picture.
<?php
include("./include/membersite_config.php");
function fetchAvatarLocation()
{
$user_id = $fgmembersite->UserId();
$query = mysql_query("SELECT * FROM ddmembers WHERE id_user = '$user_id'");
if(mysql_num_rows($query)==0)
die("User not found!");
else
{
$row = mysql_fetch_assoc($query);
$location = $row['imagelocation'];
return $location;
}
}
?>
And finally I have membersite_config.php
<?PHP
include("fg_membersite.php");
$fgmembersite = new FGMembersite();
//Provide your site name here
$fgmembersite->SetWebsiteName('Mysitename.com');
//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('My.Email#Provider.net');
//Provide your database login details here:
//hostname, user name, password, database name and table name
//note that the script will create the table (for example, fgusers in this case)
//by itself on submitting register.php for the first time
$fgmembersite->InitDB(/*hostname*/'localhost',
/*username*/'user',
/*password*/'password',
/*database name*/'database',
/*table name*/'table');
//For better security. Get a random string from this link: http://tinyurl.com/randstr
// and put it here
$fgmembersite->SetRandomKey('**************');
?>
fg_membersite is a file that contains the class fgmembersite that stores a bunch of functions, the ones that I need it for are...
function UserId()
{
return isset($_SESSION['userid_of_user'])?$_SESSION['userid_of_user']:'';
}
function UserName()
{
return isset($_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
}
The object is not in the scope of the function, so it is undefined. You need to pass it in as a parameter:
function fetchAvatarLocation( $fgmembersite)
Then call it with the object as a parameter:
<img id="profile_avatar" src="profile_settings/<?php echo fetchAvatarLocation( $fgmembersite); ?>"></img>
An alternative is to use global variables, but I wouldn't recommend it.
I want to somehow use this function on a non-wordpress page :
<?php
if (is_user_logged_in()){
echo "Welcome, registered user!";
}
else {
echo "Welcome, visitor!";
};
?>
Is there any way to do this? I was told it is possible if I include my wp-header.php in the Non-wordpress page, but I do not want to do this. Any other methods?
You have to load the Wordpress Core into your current script. You can do it like this:
//wp-admin
require $_SERVER['DOCUMENT_ROOT'].'/wp-load.php';
//Check if someone is logged in
global $user_level;
get_currentuserinfo() ;
//echo "User Level = $user_level<br>";
if ($user_level < 1)
die('You aren\'t allowed to view this!');
You have to use the Wordpress header because that function is in the core. The only other option is to write your own function with the same name, using the same database of users.
You don't need to include the admin-header.php file. Just include this file:
wp-includes/pluggable.php
This file contains definition of is_current_logged_in() as well as many other user data helpers such as wp_set_current_user(), wp_get_current_user() etc.
Including wp-load.php is the best way to go. There are loads of ways around this, but I use something similar to the following:
$wp_load_location_array = array();
$wp_load_location_array[] = "../../../../../../wp-load.php";
$wp_load_location_array[] = "../../../../../wp-load.php";
$wp_load_location_array[] = "../../../../wp-load.php";
$wp_load_location_array[] = "../../../wp-load.php";
$wp_load_location_array[] = "../../wp-load.php";
foreach($wp_load_location_array as $wp_load_location)
{
if(file_exists($wp_load_location))
{
require_once($wp_load_location);
}
}
It's a bit of a hack and if you actually know the location of the wp-load.php file, then you can just use that in the require_once() function.
Put that at the top of your file and you'll be able to use all of WordPress' functions in your non-wordpress page.
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.
if(condition here){
include "myFile.php?id='$someVar'";
}
Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.
Can someone please tell me how to achieve this?
Thanks.
Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).
You could do something like this to achieve the effect you are after:
$_GET['id']=$somevar;
include('myFile.php');
However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).
In this case, why not turn it into a regular function, included once and called multiple times?
An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :
<?
if ($condition == true)
{
$id = 12345;
include 'myFile.php';
}
?>
And in "myFile.php" :
<?
echo 'My id is : ' . $id . '!';
?>
This will output :
My id is 12345 !
If you are going to write this include manually in the PHP file - the answer of Daff is perfect.
Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:
<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
// find ? if available
$pos_incl = strpos($phpinclude, '?');
if ($pos_incl !== FALSE)
{
// divide the string in two part, before ? and after
// after ? - the query string
$qry_string = substr($phpinclude, $pos_incl+1);
// before ? - the real name of the file to be included
$phpinclude = substr($phpinclude, 0, $pos_incl);
// transform to array with & as divisor
$arr_qstr = explode('&',$qry_string);
// in $arr_qstr you should have a result like this:
// ('id=123', 'active=no', ...)
foreach ($arr_qstr as $param_value) {
// for each element in above array, split to variable name and its value
list($qstr_name, $qstr_value) = explode('=', $param_value);
// $qstr_name will hold the name of the variable we need - 'id', 'active', ...
// $qstr_value - the corresponding value
// $$qstr_name - this construction creates variable variable
// this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
// the second iteration will give you variable $active and so on
$$qstr_name = $qstr_value;
}
}
// now it's time to include the real php file
// all necessary variables are already defined and will be in the same scope of included file
include($phpinclude);
}
?>
I'm using this variable variable construction very often.
The simplest way to do this is like this
index.php
<?php $active = 'home'; include 'second.php'; ?>
second.php
<?php echo $active; ?>
You can share variables since you are including 2 files by using "include"
In the file you include, wrap the html in a function.
<?php function($myVar) {?>
<div>
<?php echo $myVar; ?>
</div>
<?php } ?>
In the file where you want it to be included, include the file and then call the function with the parameters you want.
I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)
In your myFile.php you'd have
<?php
$MySomeVAR = $_SESSION['SomeVar'];
?>
And in the calling file
<?php
session_start();
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;
?>
Would this circumvent the "suggested" need to Functionize the whole process?
I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:
<?php
include('references.php');`
?>
User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:
<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>
I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.
<?php
function include_get_params($file) {
$parts = explode('?', $file);
if (isset($parts[1])) {
parse_str($parts[1], $output);
foreach ($output as $key => $value) {
$_GET[$key] = $value;
}
}
include($parts[0]);
}
?>
The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.
Here is an example on the form page when called:
<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
include_get_params(DIR .'references.php?count='. $i);
} else {
break;
}
}
?>
Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.
You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];
If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:
one.php:
<?php
$vars = array('stack','exchange','.com');
include('two.php'); /*----- "paste" contents of two.php */
testFunction(); /*----- execute imported function */
?>
two.php:
<?php
function testFunction(){
global $vars; /*----- vars declared inside func! */
echo $vars[0].$vars[1].$vars[2];
}
?>
Try this also
we can have a function inside the included file then we can call the function with parametrs.
our file for include is test.php
<?php
function testWithParams($param1, $param2, $moreParam = ''){
echo $param1;
}
then we can include the file and call the function with our parameters as a variables or directly
index.php
<?php
include('test.php');
$var1 = 'Hi how are you?';
$var2 = [1,2,3,4,5];
testWithParams($var1, $var2);
Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :
if(condition){
$someVar=someValue;
include "myFile.php";
}
As long as the variable is named $someVar in the myFile.php
I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:
<?php
header("Location: http://localhost/planner/layout.php?page=dashboard");
exit();
?>