else if - what am I doing wrong? - php

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>";
}
?>

Related

Make something disappear for everyone besides admin

How do I make something disappear for everyone besides the admin, I have this code but it only works when you are not logged in when I log in with another user it keeps showing me.
<?php
if( isset($_SESSION['username']) == "admin"){
}else{
echo "<style> .add{display: none} </style>";
}
?>
There are two steps, First you check if username isset, then you compare it. In your code, you are comparing a boolean returned by isset to a string that is "admin", try this:
if (isset($_SESSION['username']) {
// username is set
if ($_SESSION['username'] == "admin") {
// user is admin
} else {
echo("<style> .add {display:none} </style>");
}
}
Also if it is something you want to not have in the page, using display: none is very shallow. Someone can just use inspect element to style it and get it to show.

Am I not using the _GET function properly to open another page?

I'm asking this because my teacher was displeased with how it worked. By that I mean ,when I typed in the query string to change sites, instead of typing ?page=flight and it staying that way it changed to../flight-details.php which is the direct page name.
Router.php:
<?php
$nav =array("home"=>"home.php",
"flight"=>"flight-detail.php",
"order"=>"order-flight.php",
"testimonial"=>"add-testimonial.php");
if ( isset ($_GET) )
{
header('Location: ' . $nav[$_GET['page']]);
}
else
{
header('Location:index.php');
}
There are few issues with your code, such as:
$_GET is a superglobal array, right now you are just checking whether the array is set or not. Your if condition should be like this:
if(isset($_GET['page']) && in_array($_GET['page'], array_keys($nav))){ ...
Otherwise you would get undefined index error if someone types anything other than the following four combinations, ?page=home&..., ?page=flight&..., ?page=order&... and ?page=testimonial&....
header(...); is not enough to redirect the user to a different page, use exit(); immediately after header(...); statement.
So your code should be like this:
$nav =array("home"=>"home.php",
"flight"=>"flight-detail.php",
"order"=>"order-flight.php",
"testimonial"=>"add-testimonial.php");
if(isset($_GET['page']) && in_array($_GET['page'], array_keys($nav))){
header('Location: ' . $nav[$_GET['page']]);
}else{
header('Location:index.php');
}
exit();
Here's the relevant reference:
http://php.net/manual/en/function.array-keys.php

PHP syntax - shows text and not link

With this snippet of code, I'm attempting to show a clickable link (if "admin" is logged in), which will redirect me to adminarea.php
Right now it just prints out "Admin" in text. Nothing to click on. Just simple text.
Am I missing anything? Surely I got it wrong but I cannot see what's missing.
Here is the code:
<?php if (getUser("user") == "admin") { ?>
<option value="adminarea.php">Admin</option>
<?php } ?>
You're printing an option, which is part of the select form input. You're probably looking for an anchor?
Admin
Possibly a better way to do this would be to declare two options for a variable in your PHP first. Something like:
<?php
if(getUser("user") == "admin") {
$adminlink = 'Admin';
} else {
$adminlink = NULL;
}
?>
And in the html:
<?php echo $adminlink; ?>
This would show the href link if the PHP condition was true, and would display nothing if not. Hope this helps!
Well based on your title am assuming you want a link. By the way you can use PHP friend html syntax instead of making the code look "dirty".
<?php if(getUser("user") == "admin"): ?>
Admin
<?php endif; ?>

How to use $GLOBALS to share variables across php files?

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.

How should I handle the case in which a username is already in use?

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.

Categories