How to enable Delete button in PHP when Admin is logged in but not for Viewer (normal user)? - php

I am working on a simple report viewer, where PDF's stored in a folder are displayed in the table and can be opened when user clicks on it. That thing is working fine. I also have a Upload functionality which lets the user upload the files to the respective folders and later can be displayed in the table. I also can delete the files by showing a delete link right in front of the file name in table.
At first, I wanted there to be only one user which could do all the things. Now, we want the Delete link and Upload menu to be displayed only when the username is 'Admin'. We do not want to use any databases, because data is not so classified and we are fine using a script based solution. However, I can't figure out how to enable Delete and Upload only for Admin. The code I am using is attached below:
From login.php
<?php session_start(); /* Starts the session */
/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('reader' => '123456','admin' => '654321','username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
?>
Before every page, we insert this code:
<?php session_start(); /* Starts the session */
if(!isset($_SESSION['UserData']['Username'])){
header("location:login.php");
exit;
}
?>
And this is what we are doing inside the table to display list of files and a link to delete them:
foreach($files as $file)
{
if(isset($_GET['delete']))
{
unlink($file);
break;
//a better approach for deletion will be appreciated
}
echo'<tr><td>'.returnFile($file).'</td>
<td>Download</td>
<td>Delete</td>
</tr>';
}

It worked when I changed $_SESSION['UserData']['Username']=$logins[$Username]; into $_SESSION['UserData']['Username']=$Username; in login.php.
Finally adding if($_SESSION['UserData']['Username'] == 'admin') before any code I wanted to appear only when Admin is signed in. Thank you everyone.

Related

PHP use SESSION in the multiple pages

I have 1 SESSION variable that will load when a login form is inserted and it passes the test. But, the variable will only work in one page and when I click on a different page that includes the same file which gives me the SESSION, it doesn't work. It will only work for pages that are linked to the form. I am using the post method. sample.php <- site that is in action="sample.php" therefore its linked.
Beginning code for sample.php
<?php
session_start();
require 'php/login_admin.php';
if (isset($_SESSION['admin']))
echo ' all html code ';
Code for login_admin.php
if ($username == $row['username'] && $password == $row['password'])
{
session_set_cookie_params(3000, "/");
$_SESSION['admin'] = 'open';
} else {
session_close();
echo "Wrong password and username!";
}
NOTE I have this same set up for all pages and I do not know why only the pages linked directly to the form in the action attribute work.
On all your OTHER pages you only need to test for the admin session and if that fails then redirect to the login page... or display it... whatever you decide. But let's assume we go to a dedicated admin login page for fun...
So on All your other pages...except the login page...
<?php
session_start();
// Is the admin logged in?
if (!isset($_SESSION['admin']))
{
header("location:admin_login.php");
exit();
}
echo ' all html code ';

PHP Session not carrying over to protected pages

I've been having a really rough time trying to implement a logon system for my web application.
I have the basic logic working as far as my index.php goes - if users try to navigate there and are not logged in it redirects them to the logon screen. Once they've provided correct credentials they are directed properly back to the protected index.php page.
This logic in code is seen here:
(index.php)
<?php
session_start();
include_once 'db_functions.php';
require_once 'access.php';
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
The problem occurs when a user attempts to navigate to another protected page. My logic was for protected pages to check whether the user was logged in, and if not send them back to the index which would in turn send them to a logon screen.
(protectedpage.php)
<?php
session_start();
require_once 'access.php';
echo "Logged in: " + $_SESSION['loggedIn'];
echo "User: " + $_SESSION['email'];
echo "Password: " + $_SESSION['password'];
// receive data from HTML readcalllog request
$rName=$_POST["registration"]; //irrelevant post data
$rowId=$_POST["rowid"]; //irrelevant post data
if ($_SESSION['loggedIn'] == FALSE) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
}
As you can see I included test echo statements to print out the details of the current session. When I would navigate to the page (turning off the redirect feature) to check the error messages it would print "000", without the "Logged in: " or "User: " text in front of it.
I performed a test and printed out the details successfully on the index.php page, so for some reason the session is being lost as I navigate from index.php to another protected page.
Any help would be greatly appreciated!
EDIT:
Here is a portion of the userIsLoggedIn() in access.php function which sets the session variables:
function userIsLoggedIn()
{
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect.';
return FALSE;
}
}
}
EDIT 2:
If I login to the index page, go to the protected page(which sends me to a logon screen) and login again, the sessions function properly and all protected pages are accessible.
I just need to figure out what's preventing the initial logon from creating a proper session that carries over.
First of all, you do not need to include session_start(); more then once in a page. Just insert it at the beginning of each file.
If I were you, I would use this statement to see if the user is logged in or not in the protected pages:
if ( !isset($_SESSION['email'] && !isset($_SESSION['password'] ) ) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
} else {
echo "Logged in";
}
Also, I would recommend you using both $_SESSION and $_COOKIES to create a stronger log in system.

Session Variables and protected page errors

I currently have a login form that redirects the user to another page if the login is successful. The page is supposed to be a protected page that will not open for the user if they are not logged in and will redirect them to the login form page.
In order to do this I stored the login data (email & password) as session variables and used these to verify if the user is allowed to view the page.
In my login php page I have the following code
<?php
session_start();
if ($count == 1) {
$_SESSION['logged'] = 1;
$_SESSION['email'] = $myemail;
$_SESSION['password'] = $mypassword;
header("Location: account.html");
exit();
}
?>
And I begin my account html file with the following :
<?php
session_start();
if ($_SESSION['logged'] != 1) { //no session
header("Location:memberlogin.html");
exit();
}
?>
However any time I load the account page I am allowed to view it each time. Its my first time using the Session variableand Im not sure if i Used it correctly.
FIXED Thanks to suggestions below
I tweaked the code suggested below and my protected page is now working. Thanks for all the help.
The php code won't be referenced from an html page.
So, change account.html to account.php then add the session check code on top of the page as follows:
account.php:
<?php
if ($_SESSION ['logged'] !=1) {
//User is not logged in
header ("Location:memberlogin.html");
exit();
}
?>
However, redirecting is not the best solution, you can display an error message if user is not logged in, else grant user access to the page information.
You can implement it as follows:
account.php:
<?php
if ($_SESSION ['logged'] !=1) {
//User is not logged in, display an error message
echo 'You need to be logged in to access this page';
exit();
}
else{
//Display all information that only a logged in user can view
echo 'You are logged in, you can view the page';
}
?>

PHP Dynamic signup page

I wanted to create a dynamic signup.php. The algorithm is as follow:
Algorithm
when signup.php is requested by client, the code will attempt to check whether user send any data in $_POST.
if $_POST does not contains any data (means it's the first time user request for signup.php), a signup form will be return to the user, allowing user to enter all his/her details and again send back to signup.php through submit button.
if $_POST does contains data (means user has fill up the signup form and is now sending all the data back to signup.php), then the php code will attempt validate all those data and return result showing user has been successfully registered or error if failed to do so.
The problem I'm having right now is how am I going to check whether it's the first time user request for signup.php or not?
Use isset() to check if $_POST contains data.
http://php.net/isset
To answer your question, "how am I going to check whether it's the first time user request for signup.php or not?", honestly, probably for other users......
There are a few ways, cookies, storing request ips in a database, bleh, bleh, bleh. But...... None of them are guaranteed. The user can disable cookies, use a dynamic ip, etc. You could issue a unique hash and place it as a login.php?q=encValueForUniquePageRequest
but...... The architecture you laid out won't be practical.
Sorry :(
To check that request is POST:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//process new user
}
?>
Example:
<?php
Class signup_controller extends controller{
private $data = array();
private $model = array();
function __construct(Core $core){
parent::__construct($core);
/* load models - assign to model */
$this->model['page'] = $this->core->model->load('page_model', $this->core);
$this->model['auth'] = $this->core->model->load('auth_model', $this->core);
/* check script is installed - redirect */
if(empty($this->core->settings->installed)){
exit(header('Location: '.SITE_URL.'/setup'));
}
}
function index(){
/* do signup - assign error */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($this->model['auth']->create_user(1)===false){
$this->data['error'] = $this->model['auth']->auth->error;
}
}
/* not logged in */
if(empty($_SESSION['logged_in'])){
/* assign form keys */
$_SESSION['csrf'] = sha1(uniqid().(microtime(true)+1));
$_SESSION['userParam'] = sha1(uniqid().(microtime(true)+2));
$_SESSION['passParam'] = sha1(uniqid().(microtime(true)+3));
$_SESSION['emailParam'] = sha1(uniqid().(microtime(true)+4));
/* get partial views - assign to data */
$this->data['content_main'] = $this->core->template->loadPartial('partials/signup', null, $this->data);
$this->data['content_side'] = $this->core->template->loadPartial('about/content_side', null, $this->data);
/* layout view - assign to template */
$this->core->template->loadView('layouts/2col', 'content', $this->data);
}
/* signed in - redirect */
else{
exit(header('Location: ./user'));
}
}
}
?>

php session creating / reading problem

I'm trying to create a very simple login in php. All i want to do is,
register a session called user if the login is successful and direct the user to an inner page. in that inner page i have a include file which should check if the user session is created or not
if created -> authorize user
if not created -> redirect to login again.
But still I couldnt get this up and running. below is my code
login.php
session_start();
global $user;
if (($_POST['Submit'])){
$login = $_POST['login'];
$password = $_POST['password'];
if ((do_login($login, encrypt_password($password))) > 0){
$_SESSION['user'] = $login;
header('Location: home/dashboard.php');
}
else{
// load login again
}
}
and in my dashboard.php page this is how I'm checking it (and this part i have in another file called 'authentication.inc')
<?php
session_start(); // If
if (!isset($_SESSION['user'])) {
// User is not logged in, so send user away.
header("Location:/login");
die();
}
?>
updated ::
when I do an echo $_SESSION['user'], I'm expecting to see login name ($login) of the user which i done get :C
Am I missing something here... thanks in advance
cheers
sameera
if (!isset ($_POST['Submit']) || $_POST['Submit'] != 'Login'){
The code inside that if block won't get run if the form is submitted properly, because that condition reads " if Submit isn't set or it isn't 'Login' ". Try flipping the logic of that condition, ie:
if (isset ($_POST['Submit']) && $_POST['Submit'] == 'Login'){
-> " if Submit is set and it is 'Login' "
The Location header takes an absolute URL, not a relative URL, of the form:
header("Location: http://www.example.com/login.php");
There is an example on the PHP Manual header() page that can help to create the absolute URL.
And what #Brian says regarding the logic of your IF expression.

Categories