How to pass variable to isset function in php? - php

I am trying to return a $user_id variable from file to if(isset(...)) statement. I will perform a different if statement but just trying to echo out the $user_id variable to test that I am setting the page.
<?php
include 'core/init.php';
include 'init.image.php';
protect_page();
include 'includes/overall/overall_header.php';
if(isset($_GET['username']) === true && empty($_GET['username']) === false){
$username = $_GET['username'];
if(user_exists($username) === true){
$user_id = user_id_from_username($username);
$profile_data = user_data($user_id, 'first_name','last_name','email', 'username');
?>
<h1><?php echo $profile_data['first_name']; ?>'s Yor Page</h1>
<div id="navWrapper">
<ul>
<li>
<img src="uploads/profile/blank_profile.gif" width="150" height="150" id="blank_profile">
</li>
<nav>
<ul>
<li>
Albums
</li>
<li>
Music
</li>
</ul>
</nav>
</ul>
</div>
<?php
if(isset($_GET['action']) && $_GET['action']=='albums'){
$albums = get_profile_albums($user_id);
if(empty($albums)){
echo 'No Albums';
}else{
foreach($albums as $album){
if (empty($album['image'])) {
$album['image'] = 'uploads/profile/blank_profile.gif';
}
?>
<p><?php echo $album['name'],' (', $album['count'], ')'?> <br />
<a href="<?php echo $profile_data['username'];?>?action=album_id=<?php echo $album['id'];?>">
<img src="uploads/thumbs/<?php echo $album['id'];?>/<?php echo $album['image'];?>" />
</a><br />
<?php echo $album['description'];?>...<br />
</p>
<?php
}
}
}
if(isset($_GET['action']) && $_GET['action']=='album_id=$album['id']'){
echo $user_id;
}
if(isset($_GET['action']) && $_GET['action']=='music'){
echo'<h1>Music</h1>';
}
}else{
echo 'Sorry, that user doesn\'t exist';
}
}else{
header('Location: index.php');
exit();
}
include 'includes/overall/overall_footer.php';
?>

Single quotes do not parse the string but double quotes do. For example:
$album_id = 1;
echo 'album_id=$album_id ';
echo "album_id=$album_id";
Will result in album_id=$album_id album_id=1
Thus, $_GET['action']=='album_id=$album_id' is checking if $_GET['action'] is equal to 'album_id=$album_id' and not what $album_id is evaluated to.
Your check should be more along these lines:
if (/* ... */ && $_GET['action']=="album_id=$album_id") {
Edit: Suggestion.
You should check $_GET['action'] once and store $action. From there create an if/else if/else statement checking each possible type of action (music, albums, album, etc). If a type of action requires extra user supplied data, include that in the respective if block. For example:
$action = $_GET['action'];
// URL: /script.php?action=albums
if ($action == 'albums') {
// ...
}
// URL: /script.php?action=album&album_id=12
else if ($action == 'album') {
if (!empty($_GET['album_id'])) {
$album_id = $_GET['album_id'];
echo "User with id $user_id is trying to access album with id $album_id";
}
// ...
}
// ...
No more $_GET['action']=="album_id=$album_id"

You are passing the variable correctly.
What I'm more concerned with in the following line is:
if(isset($_GET['action']) && $_GET['action']=='album_id=$album_id'){
'album_id=$album_id' doesnt look right and is probably why your if is not firing... It looks like you're trying to use the variable $album_id wrapped in single quotes and that will not substitute the value and rather keep $album_id in tact. I'm not sure if this is what you intended but if not its likely the source of your problem.

Related

show logout link in navigation bar when logged in php

When user logged in, the login link on nav bar should be gone and logout link should appear how should i do it?
index.html:
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<p class="menu">Login</p>
<p class="menu">Logout</p>
</nav>
Login.php file:
<?php
require 'db.php';
session_start();
$password = $mysqli->escape_string($_POST['Pass']);
$email = $mysqli->escape_string($_POST['EmailAdd']);
$result = $mysqli->query("SELECT * FROM Account WHERE Usermail='$email'");
//check email in db
if ($result->num_rows == 0)
{
$_SESSION['message'] = "Email does not exist";
print '<script type="text/javascript">alert("' . $_SESSION['message'] .
'");
</script>';
header("Location: ../register.html");
}
else
{
//get user array
$user = $result->fetch_assoc();
if ($password == $user['password'])
{
$box = "Login successful";
$_SESSION['email'] = $user['Usermail'];
$_SESSION['logged_in'] = true;
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Successful')
window.location.href='../index.html';
</SCRIPT>");
}
else
{
$_SESSION['message'] = "Wrong password";
header("Location: ../account.html");
echo "failed";
echo '<script language="javascript">';
echo 'alert("Wrong password")';
echo '</script>';
}
}
?>
I've gone through some of the post in stack overflow and apply things like if (!isset($_SESSION['email'])) and else statement on my index.php but its not working and i don't know what's the prob
Ps Previously was using index.php, since its not working so i change it back to index.html
<?php
if(!isset($_SESSION['logged_in'])){?>
<p class="menu">Login</p>
<?php }
else
{?> <p class="menu">Logout</p>
<?php } ?>
try the above code, Hope this helps
Assuming your code is correctly validating the credential and setting the auth state in the session $_SESSION['logged_in'] = true;
You can do something like this:
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<?php if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true): ?>
<p class="menu">Logout</p>
<?php else: ?>
<p class="menu">Login</p>
<?php endif; ?>
</nav>
Try this in your nav:
<?php
if($_SESSION['logged_in'] == "true"){
echo '<p class="menu">Login</p>';
}
else {
echo '<p class="menu">Logout</p>';
}
?>
It is not working because you use the .html extension instead of .php
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<?php if(empty($_SESSION['logged_in'])){ ?>
<p class="menu">Login</p>
<?php } else{ ?>
<p class="menu">Logout</p>
<?php } ?>
</nav>
This should work:
<nav>
<p class="menu">Home</p>
<p class="menu">Products</p>
<p class="menu">
<?php if(isset($_SESSION['logged_in]) && $_SESSION['logged_in]) {?>
Logout
<?php } else { ?>
Login
<?php } ?>
</p>
</nav>

Else clause not functioning as expected

Currently using this to check the permissions of a user, If the user is logged in then it shows the file and lists the DIR. This works fine along with the login screen showing up if the user is not shown to be logged in.
I need it to be that if the product is not owned by the user (i.e. the permission is not level 3) then it will automatically link them to the brochure. I had a header setup to send the user but it does not function as I want it to.
Now what it does is loads the page but does not pass on the DIV (hence the name to check on the f12 debug to see if it had passed)
What am I missing?
p.s. the PHP logs show no errors
-- Update --
Gone through and commented out sections to see if the IF statement was attached to wrong thing, currently nothing still getting same problem
<?php
if (!securePage($_SERVER['PHP_SELF'])){die();}
$parts = parse_url($_SERVER["REQUEST_URI"]);
$page_name = basename($parts['path']);
//Links for logged in user
if(isUserLoggedIn()) {
//Links for permission level 3 (BOF)
if ($loggedInUser->checkPermission(array(3))){
if ($handle = opendir('CD500/')) {
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..'){
$thelist .= '<a href="/CD500/'.$file.'" target="_blank" >'.$file.'</a></br>';
}
}
closedir($handle);
echo "
<div id='output'>
List of help files:</div>
<div id='List'>
$thelist ";
}
else {
echo " asdfasdfasdfadf ";
}
}
?>
<div id='default'>
<?php } else { ?>
<li><a class="<?php echo ($page_name=='login.php')?'selected':'';?>" href="login.php">Login</a></li>
<li><a class="<?php echo ($page_name=='register.php')?'selected':'';?>" href="register.php">Register</a></li>
<li><a class="<?php echo ($page_name=='forgot-password.php')?'selected':'';?>" href="forgot-password.php">Forgot Password</a></li>
<?php } ?></div>
The problem lies at your else clause not belonging to your first if statement where you check for user login. I have also changed the code a bit at the point where you need to conditionally print some html. Try the following.
<?php
if (!securePage($_SERVER['PHP_SELF'])){die();}
$parts = parse_url($_SERVER["REQUEST_URI"]);
$page_name = basename($parts['path']);
//Links for logged in user
if(isUserLoggedIn()) {
//Links for permission level 3 (BOF)
if ($loggedInUser->checkPermission(array(3))){
if ($handle = opendir('CD500/')) {
while (false !== ($file = readdir($handle))){
if ($file != '.' && $file != '..'){
$thelist .= '<a href="/CD500/'.$file.'" target="_blank" >'.$file.'</a></br>';
}
}
closedir($handle); ?>
<?php if($thelist): ?>
<div id='output'>
List of help files:
</div>
<div id='List'>
<?php echo $thelist; ?>
</div>
<?php endif; ?>
<?php }
} else {
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
} else { ?>
<div>
<li><a class="<?php echo ($page_name=='login.php')?'selected':'';?>" href="login.php">Login</a></li>
<li><a class="<?php echo ($page_name=='register.php')?'selected':'';?>" href="register.php">Register</a></li>
<li><a class="<?php echo ($page_name=='forgot-password.php')?'selected':'';?>" href="forgot-password.php">Forgot Password</a></li>
</div>
<?php } ?>

Showing different content based on $_SESSION UserLevel

I am having a problem with trying to show different menu options based on UserLevel. I have a mysql database with a users table. The users table contains a UserLevel which will either be set to 0 or 1. But for some reason my php just isn't working. In fact, when I add the php to the menu, it then does not display ANYTHING on the site below the menu. Any advice would be much appreciated.
Code that starts session
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
?>
<?php include "mainNav.php"; ?>
<center>
<h2> Campaign Updates</h2>
</center>
<div id="campaignPostWrap">
<div id="campaignScrollBox">
<?php
$con=mysqli_connect("localhost","dorians","ds2953!b67P$","aldentec");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM campaigns ORDER BY postDate desc");
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>
</div>
<?php include "campaignPost.php"; ?>
</div>
<?php include "chat.php"; ?>
<?php
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$userlevel = $row['UserLevel'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['UserLevel'] = $userlevel;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area. If you are not automatically redirected <a href='index.php'>Click here</a></p>";
header( "refresh:10;url=index.php" );
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
Menu code that isn't working
<?php session_start(); ?>
<?php
$userlevel = $_SESSION['UserLevel'];
if($userlevel == 0) {
echo "<ul class="mainNav">
<li> Create Character</li>
<li> Create Quest</li>
<li> View Characters</li>
<li> View Quests</li>
<li> Book List</li>
</ul>";
} elseif($userlevel == 1) {
echo "<li> DM Tools</li>";
}
?>
<?php include "greeter.php"; ?>
Your quotes are undoubtedly the problem here:
if($userlevel == 0) {
echo "<ul class="mainNav">
<li> Create Character</li>
<li> Create Quest</li>
<li> View Characters</li>
<li> View Quests</li>
<li> Book List</li>
</ul>";
} elseif($userlevel == 1) {
echo "<li> DM Tools</li>";
}
Notice the syntax highlighting above shows the issue in your string. See how it turns black when it gets to mainNav? That's because mainNav is no longer part of the string. That's a bad thing here.
Look at the first line of your echo:
echo "<ul class="mainNav">
You open a quote and then close it at class=". Now, it's trying to evaluate mainNav as a constant or some other language construct. On top of that, it doesn't know what to do with mainNav as you haven't provided any kind of operators.
Instead, you should do something like:
if($userlevel == 0) {
echo '<ul class="mainNav">
<li> Create Character</li>
<li> Create Quest</li>
<li> View Characters</li>
<li> View Quests</li>
<li> Book List</li>
</ul>';
} elseif($userlevel == 1) {
echo '<li> DM Tools</li>';
}
Alternatively, you could escape every location where there is a non-string-terminating quote like \".
Another option would be to use Heredoc syntax.

How to concat or pass this variable when isset is called?

if(isset($_GET['action']) && $_GET['action']=='album_id=$album['id']')
Now I am sure all of you can see the error here I am trying to check if this link is clicked
<a href="<?php echo $profile_data['username'];?>?action=album_id=<?php echo $album['id'];?>">
Now this link works and displays as it should in the url but I can not figure out how to pass $album['id'] to the if statements isset?
EDIT
ok i did this:
<a href="<?php echo $profile_data['username'];?>?action=album_id&action_id=<?php echo $album['id'];?>">
and
if($_GET['action'] == 'album_id' && $_GET['action_id'] == $album['id'])
and returned undefined variable in the if statement says album is undefined variable
This is my htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /lr/profile.php?username=$1 [QSA]
Here is my entire php file:
<?php
include 'core/init.php';
include 'init.image.php';
protect_page();
include 'includes/overall/overall_header.php';
if(isset($_GET['username']) === true && empty($_GET['username']) === false){
$username = $_GET['username'];
if(user_exists($username) === true){
$user_id = user_id_from_username($username);
$profile_data = user_data($user_id, 'first_name','last_name','email', 'username');
?>
<h1><?php echo $profile_data['first_name']; ?>'s Yor Page</h1>
<div id="navWrapper">
<ul>
<li>
<img src="uploads/profile/blank_profile.gif" width="150" height="150" id="blank_profile">
</li>
<nav>
<ul>
<li>
Albums
</li>
<li>
Music
</li>
</ul>
</nav>
</ul>
</div>
<?php
if(isset($_GET['action']) && $_GET['action']=='albums'){
$albums = get_profile_albums($user_id);
if(empty($albums)){
echo 'No Albums';
}else{
foreach($albums as $album){
if (empty($album['image'])) {
$album['image'] = 'uploads/profile/blank_profile.gif';
}
?>
<p><?php echo $album['name'],' (', $album['count'], ')'?> <br />
<a href="<?php echo $profile_data['username']; ?>?action=album&album_id=<?php echo $album['id']; ?>">
<img src="uploads/thumbs/<?php echo $album['id'];?>/<?php echo $album['image'];?>" />
</a><br />
<?php echo $album['description'];?>...<br />
</p>
<?php
}
}
}
else if (isset($_GET['action']) && $_GET['action']=='album' && isset($_GET['album_id'])){
echo 'albums';
}
if(isset($_GET['action']) && $_GET['action']=='music'){
echo'<h1>Music</h1>';
}
}else{
echo 'Sorry, that user doesn\'t exist';
}
}else{
header('Location: index.php');
exit();
}
include 'includes/overall/overall_footer.php';
?>
the proper way would be to have the url properly encoded:
<a href="<?php echo $profile_data['username'];?>?action=<?php echo urlencode('album_id='.$album['id']); ?>">
and then decode it
if(isset($_GET['action']) && urldecode($_GET['action'])=='album_id='.$album['id'])
You don't have a destination, where's the php file you try to access? You started with username. Check here href="<?php echo $profile_data['username'];?>?
Try separate the action and the id, it's probably just me, I found it kinda weird to put it like action=album=1
you can try like this
$_GET['action'] == 'album' && $_GET['action_id'] == $album['id']
so the url would be looking like
?action=album&action_id=1
I think #Dreen answered to your question, but I would separate the action parameter to something like action and id:
<a href="<?php echo $profile_data['username'];?>?action=album&id=<?php echo $album['id'];?>">
and check
if(isset($_GET['action']) && $_GET['action']=='album' && isset($_GET['id']) && $_GET['id']==$album['id'])

PHP if statements unsure where I'm wrong

I'm trying to specify that my logo appears on some pages and not on others, the only pages I do not want it showing on are the homepage and /index.php. I have the big logo appearing and disappearing as I want it and so I presumed I could just do the opposite for the small logo but I must be doing something wrong. Here is my current code:
<?php
$dunpage = $_SERVER['REQUEST_URI']; if ($dunpage != '/index.php' || $dunpage != '/') {?>
<h1 class="small-logo">
<span><?php echo $siteName; ?>
</h1>
<?php }
?>
<?php
$currentpage = $_SERVER['REQUEST_URI']; if ($currentpage == '/' || $currentpage == '/index.php') {?>
<h1 class="logo";>
<span><?php echo $siteName; ?>
</h1>
<?php }
?>
Instead of a logical OR in your first condition, you should be using a logical AND:
$dunpage = $_SERVER['REQUEST_URI']; if ($dunpage != '/index.php' || $dunpage != '/') {?>
// Should be
$dunpage = $_SERVER['REQUEST_URI']; if ($dunpage != '/index.php' && $dunpage != '/') {?>
Effectively, you were saying "act if the page is either not index.php, or not /." So in either of those cases, the opposite would be true. If it wasn't index.php, it could be /, for example.
try
if ($dunpage != '/index.php' && $dunpage != '/') {
for your small logo.
You correctly negated the == operator, but not the || operator. You're saying that if dunpage is not /index.php OR dunpage is not /, do that, which basically means do that always. Change || to && for the small logo.
Why don't you use an else?
<?php
$currentpage = $_SERVER['REQUEST_URI']; if ($currentpage == '/' || $currentpage == '/index.php') { ?>
<h1 class="logo";>
<span><?php echo $siteName; ?>
</h1>
<?php
} else {
?>
<h1 class="small-logo">
<span><?php echo $siteName; ?>
</h1>
<?php
}
?>
(You don't actually mention that it's either a large or a small logo that you want to display, but I have to assume that is the case here.)
Or you can use in_array() in this case.
<?php
$displayMainLogo = array('/', '/index.php');
if ( in_array($_SERVER['REQUEST_URI'], $displayMainLogo) ) { ?>
<h1 class="logo";>
<span><?php echo $siteName; ?>
</h1>
<?php
} else {
?>
<h1 class="small-logo">
<span><?php echo $siteName; ?>
</h1>
<?php
}
?>
If you understand how to do a ternary (http://php.net/manual/en/language.operators.comparison.php), then this is as terse as you can make it.
<h1 class="<?php echo (in_array($_SERVER['REQUEST_URI'], $displayMainLogo)) ? 'logo' : 'small-logo' ?>";>
<span><?php echo $siteName; ?>
</h1>

Categories