I have a file, index.php that produces a link to a page that I want my user to only be able to access if some $var == True.
I want to be able to do this through the $GLOBALS array, since my $_SESSION array is already being filled with instances of a specific class I want to manipulate further on.
My index.php page:
<?php
$var = True;
$GLOBALS["var"];
echo "<p><a href='next.php'>Click to go to next page</a></p>";
?>
My next.php page:
<?php
if($GLOBALS["var"] == False)
exit("You do not have access to this page!");
else
echo "<p>You have access!</p>";
?>
Currently, next.php is echoing the exit text. Am I accessing/assigning to the $GLOBALS array correctly? Or am I not using it properly?
Thanks!
EDIT:
So I've tried some of the suggestions here. This is my new index.php:
<?php
$GLOBALS["var"] = True;
echo "<p><a href='next.php'>Click to go to next page</a></p>";
?>
My next.php:
<?php
if($GLOBALS["var"] == False)
exit("You do not have access to this page!");
else
echo "<p>You have access!</p>";
?>
However, I'm still running into the same issue where the exit statement is being printed.
It's much better to use sessions for this, since they are more secure and exist for this purpose. The approach I would recommend, is starting a new separate session array.
session_start();
$_SESSION['newSession']['access'] = true;
Then to access it use the same key/value.
Related
I have the following code
<?php
if($_SESSION['loggedin']){
echo '<li id="login-btn">Logout</li>';
}
else{
echo '<li id="login-btn">Login</li>';
}
?>
This is inside of the HTML for my Navbar. I want it to where if they are logged in, it will show "Logout", if they aren't logged in, it'll show "Login", (self explanatory)
I have this in my login.php
$loggedin = "";
$_SESSION['loggedin'] = true;
For some reason, no matter what I do, my navbar keeps displaying "Login"? Help please, thank you!
Session are global variables in php...
Session variables are not passed individually to each new page,
instead they are retrieved from the session we open at the beginning
of each page (session_start()).
if you want to access it on different page... you have to add
<?php
session_start();
?>
at the begining .... even in your login.php page
I developing a Intranet and I'm a bit stuck with allowing access for individual users. All works fine when I limit the access to an element, if that element in at the bottom/last element. I need this to usable where ever I want. If you are in the Directors group, get the element. If you are in the All group only, you get nothing. Any help would be great.
The HTML:
.....
<?php include('admin/Directors.php');
echo 'foooooo':
?>
....
<?php include('admin/All.php');
echo 'baaaar':
?>
...
The PHP (Directors.php):
<?php
session_start();
$allowed_users = array('mark','joe','allan');
if(!in_array($_SESSION['user'],$allowed_users)) die('');
?>
From wat I understand is happening here is that its reading the Directors.php file and applying it to entire HTML file.
Try this In your Directors.php:
session_start();
$allowed_users = array('mark','joe','allan');
return in_array($_SESSION['user'],$allowed_users));
And this in your html:
$allowed = include('admin/Directors.php');
if($allowed)
{
echo 'foooooo';
}
Instead of killing script with die() simply return the evaluation value check it in your html. But if there is other stuff in Director.php you can do this.
Try this In your Directors.php:
session_start();
$allowed_users = array('mark','joe','allan');
$allowed =in_array($_SESSION['user'],$allowed_users));
And this in your html:
include('admin/Directors.php');
if($allowed)
{
echo 'foooooo';
}
I am looking to set a session variable based on a search conducted by the user. The idea is that the search is populated with their last search wherever they go on the site.
I have the following code that I thought would set the variable if the variable geo-box was present and use the saved variable if it isn't, but this doesn't work...
session_start();
if(isset($_GET['geo-box'])){
echo $_SESSION['town'] = $_GET['geo-box'];
} else {
echo $_SESSION['town'];
}
session_start();
if(isset($_GET['geo-box']))
$_SESSION['town'] = $_GET['geo-box'];
echo $_SESSION['town'];
You can't echo a variable while defining it.
Best of Luck!
You are trying to echo a variable and set it in the same line.
Try this:
session_start();
if( isset($_GET['geo-box']) ) {
$_SESSION['town'] = $_GET['geo-box'];
}
echo $_SESSION['town'];
You can not echo a value and assign it at the same time. Give this a try!
Hope this helps.
I have the following code which I use in conjunction with a members script which displays a members username the page or asks guests to login or register.
PHP code:
if ($_SESSION['username'])
{
echo "".$_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}
else
echo "Welcome Guest!<br><small>Login or Register</small>";
It works perfectly well, though now I want to modify it so if a user with admin privileges logs in it identifies the username and offers a link to the admin page.
So here's my modified code:
<? php
$validateadmin = $_SESSION['username'];
if ($validateadmin == "admin1" or $validateadmin == "admin2")
{
echo "Hello $validateadmin, you have admin privileges.<br><small>Click here to logout</small>";
}
else if ($_SESSION['username'])
{
echo "".$_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}
else
{
echo "Welcome Guest!<br><small>Login or Register</small>";
}
?>
Any idea's what I'm doing wrong? It either leaves me with a blank page or errors.
I know it's probably a newbie error but for the life of me I don't know what's wrong.
Generally you should use elseif in php not "else if" because the php parser will interpret else if as else { if { .... }} and you can have some weird errors.
Also, it is a great practice to ALWAYS use braces with control statements to avoid dangling clauses.
Also to avoid notices about array indexes don't do checks like if($array[$index]) if the index may not exist. Use any of array_key_exists, isset, empty, etc (they all are slightly different) to check if an array contains a key you are looking for.
try the following
<?php #removed space
session_start(); #you will need this on all pages otherwise remove it if already called
$validateadmin = $_SESSION['username'];
if($validateadmin == "admin1" || $validateadmin == "admin2"){
echo "Hello $validateadmin, you have admin privileges.<br><small>Click here to logout</small>";
}elseif(isset($_SESSION['username'])){ #you should use isset to make sure some variable is set
echo $_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}else{
echo "Welcome Guest!<br><small>Login or Register</small>";
}
?>
To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.
What are the best practices for:
How I should handle the (likely) possibility that when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?
How to handle varying page titles?($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)
(An excerpt of the code I have written so far is in the history.)
Do a separate SELECT to check whether the username is already in use before attempting to INSERT.
More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.
<?php
// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();
// If the user is submitting the form ..
if ($_POST) {
// Validate the input.
// This includes checking if the username is taken.
$errors = validate_registration_form($_POST);
// If there are no errors.
if (!count($errors)) {
// Add the user.
add_user($_POST['username'], $_POST['password']);
// The user has completed.
$form_completed = true;
// Optionally you could redirect to another page here.
} else {
// Update the page title.
$title = "Registration, again!"
}
}
?>
<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>
<?php if ($form_complete): ?>
<p>Thanks for registering!</p>
<?php else: ?>
<?php if (count($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit">
</form>
<?php endif; ?>
</body>
</html>
Well, one thing you can do instead of repeating code down near the bottom is this:
if( $result === true ) {
$gPageTitle = 'Registration successful';
$response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
$gPageTitle = 'Username already taken';
$response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
trigger_error('This should never happen');
}
require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';
Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.
Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.
One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:
function error($field)
{
global $error;
if(isset($error[$field]))
{
echo $error[$field];
}
}
and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.
Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].
Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:
$pageTitle = "My Website";
if(isset($gPageTitle))
{
$pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";
Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.
I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app.
I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember.
You could pass the function call directly into the IF statement.
if (addUser($username, $passwd));
I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables.
Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it
display_title($pgTitle);
or
display_title("Registration Successfull");
or
$header->display_title("Registration Successfull")
if you like OO style better
Let me know if that helps. :)
You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
Suppose the username entered is in a post variable such as $_POST['username'].
Have your database check where that username exist:
$res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
if(mysql_num_rows($res) > 0) {
echo "Username exists.";
// more code to handle username exist
} else {
// ok here.
}
What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.