AngularJS ngRoute and PHP $_SESSION variables - php

I have 3 pages:
index.php
login.php
display.php
index.php
Sets up AngularJS using the ngRoute module to navigate my pages.
login.php
Loaded by default and sets PHP $_SESSION variables.
display.php
Echos the contents of $_SESSION.
I navigate to display.php from login.php using a link setup with ngRoute.
Problem
display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.
I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.
Why is this?

I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:
<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">
That is not how it works. Your $_SESSION will never be available in your templates.
What you can do, is use an ajax request for your login authentication and have that request give you a session id.
Then use that session id when starting your session in further ajax requests (as already mentioned).
Then, when you want to store something to the php session, access the data via ajax request and php service.
a VERY, VERY, VERY, simple Example:
inside getFromSession.php
session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);
inside storeToSession.php
session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;
inside your login.php
$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
session_start();
echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling
inside anywhere in your angular where you need to access session data:
$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service

In general, no reason exists, why AngularJS apps, which request
PHP-based server-side stuff, won't be able to read $_SESSION.
That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.
Additionally, put just this in display.php:
<?
echo __FILE__
. '<br />' . date( DATE_RFC822 )
. '<br />' . var_dump( $_SESSION )
;
// intentionally skipped dangerous closing PHP-tag
Now run your AngularJS app and tell what comes out.

Make sure you start the session before reading the SESSION variables.
<?php
session_start();
echo $_SESSION["user9"];
?>

I don't think you're looking for angularJS.
I think you're looking for something more like this.
index.php:
<html>
<header>
<title>Login</title>
</header>
<body>
<form method="POST" action="login.php">
<input type="username" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
login.php
<?php
session_start();
if(empty($_POST)) {
die("You don't have permission to be here.");
} elseif(empty($_POST['username']) or empty($_POST['password'])) {
die("All fields are required.");
}
$username = "admin";
$password = "password";
if($_POST['password'] == $password && $_POST['username'] == $username) {
$_SESSION['loggedIn'] == "true";
header("Location: show.php");
} else {
die("Invalid login");
}
?>
show.php
<?php
if($_SESSION['loggedIn'] == "true") {
echo "You are logged in";
} else {
die("You don't have permission to be here.");
}
?>

Related

How to call an HTML file from PHP

I am trying to create an administrator login page using HTML and PHP (the PHP is here for several other purposes too) where once the administrator logs in, an HTML file needs to run.
I will include my login page code below. I need to insert the command in the if statement in the PHP file. I tried different ways of using the include function; maybe I am not using it right.
Code:
PHP file
?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username =='admin' and $password =='Parthurnax')
{
include 'test.html';
}
else
{
echo 'you are not the admin';
}
?>
HTML file:
<html>
<body>
<div align="center">
<form action="page.php" method="POST">
<b>Username:</b><input type="text" name="username"><br>
<b>Password:</b><input type="password" name="password"><br>
<input type="submit">
</form>
</div>
</body>
</html>
change
if ($username =='admin' and $password =='Parthurnax')
{
<?php include 'test.html';?>
}
else
{
echo 'you are not the admin';
}
to
if ($username =='admin' and $password =='Parthurnax')
{
include 'test.html';
}
else
{
echo 'you are not the admin';
}
You have openend PHP tags in an already open PHP script.
Don't forget the test.html page is still accesible without logging in.
If i were to directly put in test.html in my browser, i'd get your protected page.
Change it to a PHP script and check for a logged in user. If the user is not logged in either 301 them to the login page or die your script.
use below if you want to redirect to the new page
if(whatever_condition_set_true) {
header('Location: whatever_page.html');
exit;
}
or
if your want to include any page based on condition then use
if(whatever_condition_set_true) {
include_once('whatever_page.html');
}
Use header("yourlink.html"); and don't forget to exit()

Check if regenerate_session_id() function actually works / Other security questions

I am building a website and i would like to secure it against Session Hijacking. Reading for this i came across someone saying that:
A general rule of thumb is to generate the session ID each time a user changes his access level.
1.When a user log in
2.When a user log out
3.When a user get administrative access
For what is worth, my website will be seperating the access levels into users logged-in and users logged-out. All forms are submitted using the POST method.
index.php
<?php
session_start();
//Setting the variable initialy to false
$_SESSION['LOGGED_IN'] = FALSE;
//to use SSL
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(isset($_POST['SUBMIT']))
{
if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])
{
//Open database connection
require_once('connect_db.php');
//Calling functions.php that includes all custom functions
//ErrorHandler()
require_once('functions.php');
$email = $_POST['EMAIL'];
$password = $_POST['PASSWORD'];
$statement = $DBH->prepare("SELECT * FROM user_details WHERE email=:email AND pwd=:password ");
$statement->bindParam(':email',$email);
$statement->bindParam(':password',$password);
$statement->setFetchMode(PDO::FETCH_ASSOC);
try{
$result = $statement->execute();
$rows = $statement->rowCount(); // shows how many times the user is available in the user_details table
$data = $statement->fetch(); //fetches the data related to that user from user_details table
}
catch(PDOException $e)
{
//this is custom function
echo ErrorHandler($e);
}
if($rows == 1)
{
//this means that the user has inserted the correct credentials
//regenerate session_id each time there is a change in the level of privilege to mitigate SESSION FIXATION
session_regenerate_id(true);
//turning logged in variable to true as soon as it finds a match
$_SESSION['LOGGED_IN'] = TRUE;
//saves the email into a session so it can be used in mainpage.php
$_SESSION['EMAIL'] = $email;
//redirect to main page
header('Location:https://www.example.com/mainpage.php');
}
else
{
echo "<br />Wrong username or password!<br />";
}
}//closing *if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])*
}//closing *if($_POST['SUBMIT'])*
//creating a random token to inject in our HTML form
$token = base64_encode(openssl_random_pseudo_bytes(32));
//store the random token in the session variable so we can later compare it to the one in the HTML form
$_SESSION['TOKEN'] = $token;
?>
<form action="index.php" method="POST" accept-charset="UTF-8">
<p>Email: <input type="email" name="EMAIL" /> </p>
<p><input type="hidden" name="TOKEN" value="<?php echo $token; ?>" /></p>
<p>Password <input type="password" name="PASSWORD" /> </p>
<p><input type="submit" name="SUBMIT" value="Submit" /></p>
</form>
The script accepts input email and password from the user,checks the database and if it finds a match it redirects the user to the mainpage.php.
mainpage.php
<?php
ob_start();
//the code to set the header must be called before output begins
session_start();
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(($_SESSION['LOGGED_IN'] == TRUE) && isset($_SESSION['LOGGED_IN']))
{
$email = $_SESSION['EMAIL'];
echo $email;
//Calling functions.php that includes all custom functions
//LogOut()
require_once('functions.php');
if(isset($_POST['LOGOUT']))
{
//its a custom function that is used for logging out
LogOut();
}
echo '
<form method="POST" action="mainpage.php">
<p><input type="submit" name="LOGOUT" value="Log Out" /></p>
</form>
';
}
else
{
echo "Please login in order to use example.com";
}
?>
Is there a way for me to check if the way i have built these 2 scripts really regenerate the Session ID? I am using Firefox's extension LIVE HTTP headers but i am not sure if i am reading it correctly.
Also, i cannot find a way to track down and read the content of COOKIES stored while using my browser (either Chrome or Firefox or even IE11). How can i do that?
Another question that is related with security:
Implementing an anti-CSRF token:
Do i need to implement an anti-CSRF token for each form in my website [i guess the answer is Yes but i want to confirm it]? Should each token be different than the token used in a previous form? For example the token in index.php to be different than the token used in mainpage.php if it had a form as well.
Does the token technique prevent against any other kind of attack?
I would be glad if you indicate wrong programming in the code above, so i can correct it and learn at the same time.
Thanks!
I'm going to focus on your questions and not necessarily a thorough code review, since I think your questions are the main reason you're posting.
A simple way to check your current session id or PHPSESSID is to check under Chrome's Developer Tools > Resources > Cookies. You'll see the (initially-generated) session ID. You can check this value before and after a user logs in. If the value changes, your session id has actually been regenerated.
You can also view cookies in Firefox by right-clicking the current page, going to View Page Info and using the Cookies tab.
On CSRF (prevention) tokens, the answer varies. People use different methods to go about them. I would say a majority of websites set a token in $_SESSION upon any regenerate of the session id. So for the duration of the current session, the CSRF token will remain the same and check against hidden inputs for that CSRF token.
On the other hand, I've also heard of regenerating a CSRF token for every single form that is client-facing. Your way of doing it is up to you. Nothing is 100% bulletproof, but getting as close to 100% as you can is the idea.
Take a few minutes to read up on CSRF tokens and the Synchronizer Token Pattern.
Best of luck!

Website Redirect if not login

Here is my login form. aka index.php
<form class="form-3" action="login.php?log=ok" method="post" >
<input type="text" name="username" id="login" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="submit" name="submit" value="Submit">
</form>
And here is my login checker. aka login.php
<?php
require_once 'classes/Personel.php';
$personel = new Personel();
$personel->setUsername($_POST['username']);
$personel->setPassword($_POST['password']);
$personel->login();
header("Location: index.php");
// REDIRECT
session_start();
if (strcasecmp($personel->getRole(), "LTO") == 0 ) {
$_SESSION['role'] = "LTO";
$_SESSION['personel'] = $personel;
header("Location: LTO");
}else if(strcasecmp($personel->getRole(), "LTFRB") == 0){
$_SESSION['role'] = "LTFRB";
$_SESSION['personel'] = $personel;
header("Location: LTFRB");
}else if(strcasecmp($personel->getRole(), "LGU") == 0){
$_SESSION['role'] = "LGU";
$_SESSION['personel'] = $personel;
header("Location: LGU");
}else if(strcasecmp($personel->getRole(), "ADMIN") == 0){
$_SESSION['role'] = "ADMIN";
$_SESSION['personel'] = $personel;
header("Location: admin");
}
?>
now when i try to access any accounts from them i can easily open its index page and other pages even i'am not login. How can i prohibit that? and how can i avoid the url rewriting?
eg. the index page of admin
try to open my link the correct account is admin-admin also try a wrong one..
Big Thanks in advance.
First thing, you need to set the redirect to index.php in proper place, with some condition.
I get your problem, but are you checking the session on each and everypage?
You need to implement a check at the beginning of each page that whether the session is properly set or not. Else redirect back to index.php.
You need to implement this code before each of your pages:
session_start();
if(isset($_SESSION['role'])){
if($_SESSION['role'] != "ADMIN") { //change the "ADMIN" to your unique role per page
echo "Access denied";
exit();
}
else {
header("Location: index.php");
}
You are calling header("Location: index.php") without any condition.
That means that you are always redirecting to index.php.
Any call to login.php will result in automatic redirect to index.php.
I don't know what $personel->login() exactly does but your code should look something like:
$authorized = $personel->login();
if (!$authorized) {
header("Location: index.php");
exit();
}
Also - session_start() should be at the top of the code.
Hope this helps!
You can place a check at the top of every page, and if user not logged in redirect them to an appropriate page, for example a login page.
Here's one approach to doing this.
When you login, set a $_SESSION variable (something like user_id), like this:
//If successful login:
$_SESSION['user_id'] = $userid_from_the_db;
Note that when using sessions, you must place session_start(); at the very TOP of each page.
Then, you can check if the user is logged in before displaying any page data.
Something like:
<?php
protect_page();
Where protect page can look like this:
if (isset($_SESSION['user_id'])===false) {
echo '<p>Please log in first</p>';
echo '<meta HTTP-EQUIV="REFRESH" content="5; url=login.php">';
}
Consider viewing this (free) tutorial from phpAcademy:
Registration and Login - Procedural version
Registration and Login - OOP version
Notes:
You can use either of these methods to redirect the page:
header("Location: pagename.php");
This is the preferred way, however you cannot output any other headers before using this command or it will fail.
<meta HTTP-EQUIV="REFRESH" content="5; url=pagename.php">
As a work-around, you can use this method to redirect the page, and the bonus is that it will wait the specified number of seconds before doing so (5 in this case, or zero if you choose).

PHP Session login crossing between sites on same server

I have CentOS LAMP with multiple sites. I use PHP session variable for the log into the wesites. My problem is if you log into one site you can open another site on the same server and you will be logged in. The sites are completely separate so I want them to have to log into each separately. Each site has a different user DB.
Here are the session variables I am populating upon login.
$_SESSION["username"] = "$username";
$_SESSION["user_id"] = "$user_id";
$_SESSION["act_type"] = "$act_type";
I have created a a little sample so you can recreate the problem
There is 2 separate sites:
/var/www/html/site1
/var/www/html/site2
Each site has 2 pages index.php, secure.php
If I log into one I can open secure.php on the other site to.
/var/www/html/site1/index.php
<?php
session_start();
$user = 'jane';
$pass = '654321';
if ( $user == $_POST[user] AND $pass == $_POST[pass] ) {
$_SESSION[user] = $user;
header("location: secure.php");
}
else {
echo "Bad Login";
}
?>
<form name="form1" method="post" action="index.php">
Username: <input name="user" type="text">
<br />
Password: <input name="pass" type="password">
<br /><br />
<input type="submit" name="Submit" value="Login">
</form>
/var/www/html/site1/secure.php
<?php
session_start();
if ( !isset($_SESSION[user]) ) {
header("location: index.php");
}
?>
Secure Page
/var/www/html/site2/index.php
<?php
session_start();
$user = 'joe';
$pass = '123456';
if ( $user == $_POST[user] AND $pass == $_POST[pass] ) {
$_SESSION[user] = $user;
header("location: secure.php");
}
else {
echo "Bad Login";
}
?>
<form name="form1" method="post" action="index.php">
Username: <input name="user" type="text">
<br />
Password: <input name="pass" type="password">
<br /><br />
<input type="submit" name="Submit" value="Login">
</form>
/var/www/html/site2/secure.php
<?php
session_start();
if ( !isset($_SESSION[user]) ) {
header("location: index.php");
}
?>
Secure Page
I was in a similar situation as yourself, two sites on the same server and using IP (company intranet). Had issue where they were crossing for login, and also destroying each other if you logged out on either. My solution was to use a prefix for the session variables to signify the individual sites.
Session Variables
Site 1
$_SESSION["s1_username"] = $username;
$_SESSION["s1_user_id"] = $user_id;
$_SESSION["s1_act_type"] = $act_type;
Site 2
$_SESSION["s2_username"] = $username;
$_SESSION["s2_user_id"] = $user_id;
$_SESSION["s2_act_type"] = $act_type;
^That will keep the login information separate between the two sites, so they won't "bleed" over to one another. But what about when we log out? Won't session_destroy() get rid of ALL of the variables? Here is what I did for that:
Destroying Session / Logging Out
Site 1
foreach($_SESSION as $key => $value)
{
if (strpos($key, 's1_') === 0)
{
unset($_SESSION[$key]);
}
}
Site 2
foreach($_SESSION as $key => $value)
{
if (strpos($key, 's2_') === 0)
{
unset($_SESSION[$key]);
}
}
^This prevented my websites from destroying each others variables if you logged out on one, and not the other.
Hope this helps someone out there not waste 6 hours like I did! :D
You should use
session_name( 'site1' );
session_start();
You're creating a session tuple like site1.user which is overriding php.ini's default PHPSESSID.
Call it on your logging page index.php, session.php logout.php. This is most common login file skeleton or every time you call session_start(), session_name(<sess_name>) should precede.
I guess your having a collision between the session cookie settings. You should use either a separate php.ini file per site (if that's possible) or a particular setup at the entry point of every site. Take a look at http://ar.php.net/manual/en/function.session-set-cookie-params.php

php: setting cookies and retrieving them?

I'm making a login system with php, and when I submit the correct information, it set's a cookie. the form action sends to the same page, wich has an isset cookie verification on top, but since cookies need a refresh after they're set, you need to refresh page another time so it can notice that cookies are there.
what's a workaround for it? here's my code (where username and password are "admin" just as a placeholder. when I get the system working, I'll pull values from database.)
<?php
if(isset($_COOKIE['user']))
{
echo "Hello, administrator.<br />";
echo "<a href=?logout=yes>logout</a>";
if(isset($_GET['logout']))
{
setcookie("user", $_POST['username'], time() - 3600);
}
}
else
{
if (isset($_POST['submit']))
{
if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
setcookie("user", $_POST['username'], time() + 3600);
}
else
{
echo "empty field or wrong user/pass.";
}
}
else
{
echo "nothing submitted. show form.";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
Unless you absolutely need to use a custom cookie, I would suggest to use the $_SESSION global instead. $_SESSION data is available as soon as you set it. But its more important feature is that the data is not stored on the client. What that mean in plain is that the user can never access its data. So it is harder to hack your login system. With a cookie, as other have pointed out, anybody can read and edit the data!
session_start();
if (isset($_GET['logout']))
{
unset($_SESSION['username']);
}
if ($_SESSION['username'] == 'admin')
{
echo "hello admin!";
}
else if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
$_SESSION['username'] = $_POST['username'];
}
To use the $_SESSION globals, you need to put session_start() at the beginning of your script (before sending any data). It should solve your problem of redirection at the same time. Note that behind the scene, $_SESSION use a small cookie, but you don't really have to think about it. It only contain a small id.
more information on session
http://www.php.net/manual/en/book.session.php
PS : to be honest, I would still use a redirect here. When you POST a form and press the back button, the browser ask you to send the data again and its annoying. Using a redirect with header("Location: " . $newUrl); remove that annoyance. But just my 2 cents.
$loggedin = false;
if(isset($_POST['submit'])) {
// Do login checking and set cookies
$loggedin = true; // if the case
}else if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
// Check if valid login
$loggedin = true; // if the case
}else{
// They are not logged in.
}
Then use the veriable $loggedin to see if they are logged in. I suggest making a user class though to handle this, so do you keep using the same code over and over again in your files.
You can make your own function to set cookies, ie:
function my_setcookie($name,$value,$expire){
$_COOKIE[$name] = $value;
return setcookie($name,$value,$expire);
}
But better idea is to redirect user after successful 'POST' request, so if the page is refreshed, browser won't complain about resending POST data.

Categories