I would like to know if anyone can help me with this $_SESSION variable problem. I want to add a script to a signup page that will allow someone that is already logged in to access the page from the backend and for someone who is not logged in to be redirected to the index page. Currently what is happening is that the page, when accessed from outside is redirected to index which is perfect, but from within the backend, when clicked on add user, it stays on the same page. Please excuse all the mistakes = still very new to PHP.
require 'function.php';
session_start();
if (isset($_SESSION['authenticated']) && !empty($_SESSION['authenticated'])) {
header('Location: ../../scripts/backend_login/signup.php');
} else {
header('Location: ../../scripts/backend_login/index.php');
}
You should start your session on every page where you use $_SESSION
session_start()
before the rest of your code
Start off by ensuring you have a session_start() on every page needing the session variable.
Next, change your code to this:
if (isset($_SESSION['authenticated']) {
if ($_SESSION['authenticated'] == true) {
header('Location: ../../backend_login/index.php');
} else {
header('Location: ../../backend_login/signup.php');
}
}
Try that and see
The true will only work if that is the value of the authenticated session
----EDIT----
The ($_SESSION['authenticated'] == true) is not vital, it is just another fail-safe to be double sure the correct session state is active, can be completed without this
I fixed my own problem. Here is the solution.
require_once('function.php');
session_start();
if (!is_user()) {
redirect('index.php');
}
thank you all for helping!
Related
I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>
This is my code to check if user is logged in or not:
if (!$_SESSION['userInfo']['name'])
{
Redirect('login.php');
}
and code to redirect the page is:
function Redirect($url)
{
ob_start();
header('location:'.$url);
exit;
}
This code is working properly when i press the refresh button one time but when I press the refresh button more than one time then the session variable is unset and redirects to login page.
I am using this code with API that take almost 5-10 second to load the page.If i press refresh button before loading then it's happened.
What may be issue?
Try checking with empty()
if (empty($_SESSION['userInfo']['name']))
{
Redirect('login.php');
}
NOTE: Please make sure you are not setting any value in $_SESSION['userInfo']['name'] before login. Also after login you have to clear it.
Try using isset() function (ref: http://www.php.net/isset):
if (!isset($_SESSION['userInfo']['name']))
{
Redirect('login.php');
}
And be sure to not clear the $_SESSION variable during a valid session, and still, be sure to clear it when the user logs out.
Maybe still use:
if (!isset($_SESSION['userInfo']['name']))
{
header('Location: login.php');
}
You may be omitting the code from your snippet, but are sure you starting your session?
session_start()
if (!isset($_SESSION['userInfo']['name']))
{
Redirect('login.php');
}
www.example.com/index.html on my website is a page that asks for a password, and when entered, runs through www.example.com/login.php.
<?php
if (isset($_POST['pw']) && ($_POST['pw'] == "mypassword"))
{
// Location after Logged in
header('Location: http://example.com/kareha/index.html');
}
else
{
// If not Logged in
header('Location: http://example.com/index.html');
}
?>
And then gets redirected to www.example.com/kareha/.
The problem is, anyone can just type in and directly navigate to www.example.com/kareha/.
Is there any way I can protect this index file (or anywhere else on the site) so anyone who isn't logged in is redirected to the main login page?
Also, would it help if it was protected through .htaccess? (/kareha/index.html is automatically updated according to a template, which has broken every time I mess around with it)
Edit: Maybe something along the lines of starting a session with /login.php and then having .htaccess in the /kareha/ folder check for the session?
you need to use sessions or .htpasswd. To use sessions, change your html files to php
here's the top of your login script
<?php
session_start();
// see if the form has been posted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// check for the password
if($_POST['pw'] == "mypassword") {
// set a session
$_SESSION['loggedin'] = true;
// redirect to kareha/
header('Location: http://example.com/kareha/index.php');
}
} else {
header('Location: http://example.com/index.html');
}
// put HTML and login form here...
the very top of kareha/index.php
<?php
session_start();
if(!isset($_SESSION['loggedin'])) {
// redirect to login page
header('Location: http://example.com/index.html');
}
// put rest of page here
you can read about sessions here: http://www.php.net/manual/en/book.session.php
Edit: I misread the original question. Revised...
I created a login page in php named as index.php. Now when the user logs in it redirects to mypage.php. The login works fine. But also mypage.php gets open when I type the url of mypage.php even without login. I want the user must logged in to see mypage.php and incase if he changes the url in browser then an error message should be triggered. What to do?
1.localhost/index.php
2.localhost/mypage.php
In index.php, once the user gets logged in successfully, set an session. like $_SESSION['login'] = true; before redirect. If invalid login, use $_SESSION['login'] = false; Don't forget to start the session on the top of the page. session_start();
In mypage.php, check if that session is set or not. If not set, throw error, else show the page.
session_start();
if(isset($_SESSION['login']) && $_SESSION['login'] == true) {
echo 'You are welcome';
} else {
echo 'redirecting to login page';
header('Location: index.php');
exit;
}
How are you storing the state of being 'logged in'?
You'll need to have your mypage.php check a variable that has been set by the index.php's successful login process.
Can you paste your code here and I can take a look
In order for a login to work correctly, your "secure" page (I use that term relatively because nothing is truly secure) needs to have some sort of validation conditional. In other words you need to have some way of determining if the user is logged in.
A simple way to do this in PHP is to set a session variable when you process the user's credentials. For example:
When the user successfully logs in set a session variable like so:
$_SESSION['isLoggedIn'] = true;
Then on the mypage.php check to see if the variable is set:
if(!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] != true) {
header("Location: index.php");
exit;
}
Please also note, it is imperative if you are using sessions that you have session_start(); as the first line of all of your files. This allows $_SESSION variables that were set on a separate page to be able to be read on the current page.
Hope this helps.
I want to make my php page only accessible from another page redirect and prevent my user from accessing it directly.
I mean, let's say I have a page called "main.php" and another PHP file that I want to prevent direct access to, called "noaccess.php".
I want to make noaccess.php accessible only if I redirect from main.php
Any suggestions?
UPDATE: Session is a good idea, but the problem is I have to use JavaScript to redirect the page, so the question is, can I use ajax to set a PHP session?
UPDATE 2: OK I found the solution, I don't need preventing direct access now, as I can check from mysql whether the page needs to be accessible or not.
What if everytime you were going to redirect you saved a value in the $_SESSION variable. So you have
//code
$_SESSION['fromMain'] = "true";
header("Location: noaccess.php");
Then in noaccess.php put
if($_SESSION['fromMain'] == "false"){
//send them back
header("Location: foo.php");
}
else{
//reset the variable
$_SESSION['fromMain'] = "false";
}
I really don't know if this would work or not, but this is what I would try off the top of my head.
try this
if (!isset($_SERVER['HTTP_REFERER'])){
echo "uh?"; }
else {
// The script
}
I think you're probably coming at the problem from the wrong direction, but if you really want to implement this I'd most likely do it with a session variable. Just have main.php set a flag indicating that they're now able to access noaccess.php and then redirect there. noaccess.php checks for the flag, and only functions if it's been set.
To prevent access to pages, the best practice is to use session variables say $_SESSION['username'] and $_SESSION['password'] to check against your database table record assuming your table name is "users", the fields 'username' and 'password' in order for users to gain access to the page, else they are redirected to the log in page for them to supply the correct username and password through the input field.
Below is an anatomy of Preventing Direct Access to a PHP Page.
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$query="select * from users where username='$_SESSION[username]' and password='$_SESSION[password]'";
$result=mysql_query($query);
if($result)
{
echo "Your login was successful..";// the page you want to go to if login successful
{
else
{
header("Location:index.php?action=login");//any page you want to return to if log in failed
}
I know this has already been answered. Although the answers are good, I was just facing the same situation so I thought I would put my two bit in.
I would not use HTTP_REFERER It is not reliable and not every browser even shows it.
I would not use a session variable as that is stateful and you will have to write more lines of code to check it on every request leading to unnecessary bloat.
Ideally I would create a controller class with two functions main and no access
Or If you dont want to go through that trouble, I would create a variable which is globally accessible in noccess.php with a simple true false.
This is what I would do:
class Access{
protected $access = false;
public function main(){
//Authenticate and set
include_once 'main.php';
$this->access = true;
}
public function no access(){
if($this->access === true){
include_once 'no access'.php;
}else{
header('location: main.php');
}
}
}
Or if you dont want to go through that trouble You could create a simple function or set a simple variable which is accessible from noaccess.php:
//main.php
$access = false;
header('location: noaccess.php');
//noaccess.php
include 'main.php';
if($access){
//Continue
}else{
header('location: main.php');
}
Im sure you could simplify this, but this would be the simplest and safest approach rather than relying on server variables.
I would not use a $_SESSION or $_POST as that means unnecessarily posting a form when all you want to do is secure access
You can use $_SERVER["HTTP_REFERER"]. Put the following code in the beginning of your php file and set $url to be equal of your desired url for example http://a.com/main.php
if ($_SERVER['HTTP_REFERER'] != $url) {
header('Location: noaccess.php');
exit();
}
Why not to just include instead of redirect?
The other folks are right there are issues with $_SERVER["HTTP_REFERER"] so I guess the best way will be to have a variable set into a $_SESSION or $_POST and you will need to check if that variable exists, if not it means it is a direct access.
You tried on this Iva. Below is the code that works:
$url != 'your-url-which-you-do-not-what-direct access';
if ($_SERVER['HTTP_REFERER'] == $url) {
header('Location: otherurl.php'); //redirect to some other page
exit();
}
Ensure this appears at the top of the page where you do not want direct access to.
I think I am late to answer this but my way would be
<?php
$page = basename($_SERVER['PHP_SELF']);//gets current URL
if ($page == "nonaccesspage.php") //any page u don't want to be accessed directly
header('Location:index.php');
else if($page == "nonaccesspage2.php") //page 2 which is not accessible
header('Location:index.php');
?>
If you want to authorize the user for accessing the page (I mean there is a page which is not included but can be accessed with the URL) just use $_POST or $SESSION for authorizing the user with ID and password or something like that.