I used Guzzle lib for my project.
I use guzzle to log in to a website (domain.com/login.php) and then I can get another (domain.com/post.php) as a logged in user.
The question is "How I can use cookies to load (domain.com/post.php) many requests as I want without log in the website again?"
My mine is something like that:
login = check cookies saved
if ( login ) then get domain.com/post.php
else
log in again, then get domain.com/post.php
Many thanks.
Simply Like,
PHP Sessions
PHP Cookies
Login.php
<?php
session_start();
if(login_success){
$_SESSION["active_user"] = "user-ID or Token";
}else{
//show login error
}
?>
Post.php
<?php
session_start();
if($_SESSION['active_user']){
// Check ID or Token to validate User
}else{
// redirect to login page
}
?>
Related
I built a php website where a user signs in and a session with the user credentials are created. For every page that requires users to be signed in, I created a function where it checks for the session variables. Now all of my code seems to work like a charm when I use the site directly with the server IP address (example: http://123.45.67.891/mywebsite). However, once I assigned a subdomain via "domain masking" from GoDaddy, all the session seems to not work at all. I tried to search through other Stackoverflow posts and any google searches but cannot seem to resolve it. The website does not redirect any pages to a different subdomain like I've read to other posts. All redirects on this website I built is within the same subdomain masking. Now, I do suspect that this masking is causing the cookies to get confused...
So the result I'm getting currently is that when you submit the signin form, the php code runs, creates the sessions successfully, returns success info to ajax, the ajax success function redirects to the next page, but as soon as it reaches to the next page, my code to check for credentials immediately throws the user back to the index page as it does not see any Sessions. The function is working as intended as I wrote it to prevent anyone from accessing the page without being signed in. But with the domain masking, a user is never able to signin...
Is there a solution to this or do I need to rid the subdomain masking and purchase a separate domain for this so it can work like a normal website?
Below is a snippet where I create the session and the snippet where I run the credential check.
Thanks!
//====== Create sessions at signin
... mysqli calls before this with Posts from ajax ...
session_set_cookie_params(0,'/','.mywebsite.com');
session_start();
$_SESSION["TYPE"] = $row[3];
$_SESSION["USERNAME"] = $row[0];
$_SESSION["FULLNAME"] = $row[2];
session_write_close();
... some codes returning success call to ajax where javascript then redirects to the user dashboard page...
//======= Credential Check
function checksignin(){
session_set_cookie_params(0,'/','.mywebsite.com');
session_start();
if(!isset($_SESSION["USERNAME"])){
session_destroy();
header('Location: ../index.php');
exit;
else if(empty($_SESSION["USERNAME"])){
session_destroy();
header('Location: ../index.php');
exit;
}
}
So I'm hosting my website (let's call is abc.com) on goDaddy.
I have a login page (abc.com/login.html).
Which takes me to a second page called booking (abc.com/booking.html) once the login credentials are verified.
So I don't want people to be able to just type abc.com/booking.html and access it. I want them to go to abc.com/login.html and then go to abc.com/booking.html
So I came across 2 ways to fix this -
Include a validating php script in booking.html and changing the extension from html to phtml. -> This didn't work for me
Include a .htacess file. -> I'm not really sure how to do that
so your login screen should already have session code implemented into it that has a variable that specifies if the user is logged in or not. If you don't have that implemented yet, the code would look similar to:
<?php session_start();//at the very top of the page
?>
//... your own code
//if the user successfully logs in then:
$_SESSION['authenticated']=true;
Then on the booking.php page (it should be php to allow php scripts which is super important for validating if a user is logged in), you would then check if the user did log in. If he did, the rest of the page loads, if he didn't, you would redirect them to login.php:
at the very top of booking.php:
<?php session_start();
if (!isset($_SESSION['authenticated']))
{
//if the value was not set, you redirect the user to your login page
header('Location https://www.example.com/login.php');
exit;
}
else
{
//if the user did login, then you load the page normally
}
Use $_SESSION or
Pass a variable from login.php to booking.php. And then authenticate every user based on the variable passed using the $_POST method.
eg.
if (!isset($_POST['auth'])) {
// redirect user back to login page
} else {
// successful login
}
You can do it like
rename extensions of all pages where you want this authentification
e.g.
login.html >> login.php
booking.html >> booking.php
booking-suceess.html >> booking-success.php
create one script namely auth.php with following code
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:login.php");
}
?>
In login.php add session
$_SESSION['username'] = $_POST['username'];
Now you can add auth.php in any php page where you want login compulsory as follow :
include ('auth.php');
Found a major problem on my website. I found tha if I login with user A. it sometimes kinda does log in but actually doesn't. Then I login with user B -> enter the site. I log out and then go manually back to url where login is needed and it somehow goes in with user A. It seems that I have two (maybe could have more) session_id cookies on different tabs or there is a ghost session_id that comes active I don't know. Pulling my hairs here.
Also found that, lets say I have a user dashboard and test page. With a little going back and forth with different credentials. I get this result:
Dashboard echoes user A's id, test echoes user B's id or not id at all. What the heck I am doing wrong with my sessions?
Login is done with AJAX. Login validation is the same on every page.
COMMON FUNCTIONS:
function validateUser($userid) {
session_regenerate_id();
$_SESSION['valid'] = 1;
$_SESSION['usersid'] = $userid;
}
function isLoggedIn() {
if (isset($_SESSION['valid']) && $_SESSION['valid'] == 1) {
return true;
} else {
return false;
}
}
function logout() {
$_SESSION = array();
session_unset();
session_destroy();
}
LOGIN/DB:
Login page:
session_start();
include 'include_files.php';
if(isLoggedIn()){
header('Location:loginrequiredpage.php');
die();
}
Login page sends username/password with AJAX to an controller php file that uses db functions as included file. It executes usercheckfunc() which checks user from db and then echoes succes or fail back to ajax.
from db functions - part of user check function
//if user found from db and password hash match
validateUser(**ID FROM DATABASE**);
Back in login page if ajax gets success message back, JS send user to login required url.
Here's where mystery sometimes occur The browser acts like if i just logged in somewhere, but the login page is loaded again. Sometimes I can manually go to login required page via address bar. Sometimes if I logout/idle too long etc. and login with different username/password I get in as a wrong user. Entered as user A, See user B's data OR echo different userids on pages or echo id only on other page.
LOGIN REQUIRED PAGE:
<?php
session_start();
require_once 'include_files.php';
if (!isLoggedIn()) {
logout();
header('Location:login.php');
die();
}
echo $_SESSION['usersid'];
Test page:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'include_files.php';
if (!isLoggedIn()) {
logout();
header('Location:login.php');
die();
}
echo $_SESSION['usersid'];
Is there a "best" way to manage sessions? Help is much appreciated :)
Got rid of the problem by manually setting session cookie parameters everywhere before session_start is executed. Now the session cookie domain doesn't behave unexpectedly. Sorry, no idea why it did that mysterious changeing before.
This cookie parameters sets it to be valid on whole domain. I guess it's no good in situation where you need different sessions on the same domain (different applications etc.). But for me it was the healing patch I needed.
session_set_cookie_params(0, '/', '.example.com');
session_start();
I am working on a the backend of a website. It is already working, and everything is in place, but I recently built a user management section. Now I would like to create user rights for users, and only allow those who are set as administrators on the database to access the user management pages.
I had done something with .NET which has a very nice authentication feature, and on page load I check if the user is authorised to access this page, if not redirect him to an access denied page. Is there something similar for PHP? Which would get the username of the user logged in and check it with the database, if he is allowed he would see the website, otherwise he gets redirected to an access denied page.
If there is a better solution, please feel free to post it here!
It really depends on what you need the system to handle. Most PHP-based authenication systems use session variables and MySql to store and keep active user information available to the application. I've never used this, but SUMO is apparently an easy to implement authentication system. It's also relatively easy to build a basic user authentication/permissions system with PHP. A google search will bring up thousands of tutorials.
Here is a basic(for-starter) example:
In every page(place this a the top: line:1) that requires authentication:
<?php
session_start();
//check if login key is already present, if yes user is already login
if(!isset($_SESSION['login']) {
header('location: login.php'); //redirect to login page
}
//sample of accessing a session variable
echo "current user is ", $_SESSION['username'];
?>
On login page:
<?php
session_start();
//check if user credentials
if(username and password) {
//set a marker on the session
$_SESSION['login'] = true;
$_SESSION['username'] = $username;
//place additional info on the session
}
?>
On you logout page:
<?php
session_start();
unset($_SESSION['login']);
//or $_SESSION = array(); //clears all session variables
?>
I am doing a web-application using PHP for job searching.
I have one query; when user is not logged in and wants to apply for the job given by clicking 'apply' button, he redirects to the login page. If the user is logged in when clicking, he should get directly to the application page. I'm not sure how to implement this.
I'm confused because I'm new to PHP.
Your question is very vague - maybe start with Authentication in PHP
Well, when the user clicks on 'apply' in your application the user is redirected to the login page if he is not logged in(which you can check if user session exists or not), remember when you redirect the page send the url of the current page in parameters to your login page so that when the user logs in he can be redirected back to the previous page and click on apply for that particular job.....
This is how the logic works, if you want the php, mysql explanation it would take some time for you to understand as you yourself conceded you are new to php..
You could store a value in the Session called "Login" and set this when the user logs in. This can also be used to re-direct the user if they haven't been logged in:
<?php
// check that the session variable does exist
// check that the user 'LoggedIn' has been set to 1 (true)
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1)
{
// redirect to login page for user to authenticate themselves.
// pass page location (with parameters if necessary) to redirect
// the user on successful login.
header("Location: Login.php?redir=ApplyForJob.php?JobID=12345");
}
else
{
// user is logged in
// redirect the user directly to the apply for job page.
header("Location: ApplyForJob.php?JobID=12345");
}
?>
Can you, when the user logs in, assigns a $_Session variable to that user? i.e., after authentication, you set the $_SESSION['user'] variable.
$_SESSION['user']='admin';
So if you want to check whether the user is already log in after that, just use this:
if(isset($_SESSION['user']))
{
// user is login, direct to the job page
}
else
{
// no login, go to the login page
}
On each page set a cookie or session to which page they were just on:
$expire=time()+60*60*24*30;
setcookie("wherewasi","",time() - 1000);
setcookie("wherewasi",$_SERVER['REQUEST_URI'], $expire);
Then after login redirect them:
$loc = ($_COOKIE['wherewasi'])?$_COOKIE['wherewasi']:'index.php';
header("location: ".$loc);
exit();
There are two things that you need to worry about... checking that they've logged in, and then once they've logged in, directing them to the correct page.
This is all about 'saving state' across page requests. To do this you need can use cookies or more usefully sessions (which may be done via cookies or handled by the PHP engine for you automatically).
Sessions are probably a good way to go. To use sessions, every page needs to start with a
<?php session_start(); ?>
at the very least, before any html code that writes to the browser.
Once that's done you can use your the session variable to store
<?php $_SESSION['user']='joe_blow'; ?>
(and check)
<?php
if(isset($_SESSION['user']) && $_SESSION['user']!='' {
// do something
}
?>
whether the user is logged in, and which page they need to be redirected to after login.
<?php header("location: ".$_SESSION['redirect_location']));
But in order to write the any more useful code I think people would need to know what authentication method you were using... (How are you doing your login? Are you storing ID's in a database? Are you using an off-the-shelf package?)