Secure pages with PHP/.htaccess? - 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...

Related

Weird PHP session issue, session variable is still there after restarting the browser

Logout.php script:
session_start();
session_destroy();
session_start();
unset($_SESSION['admin_uname']);
session_regenerate_id();
$_SESSION['success_msg'] = "<strong>You've been logged out.</strong>";
header('location: //domain.com/admin/login');
exit;
Login.php (part):
if (isset($_SESSION['admin_uname']) && !empty($_SESSION['admin_uname'])) {
goPage("//domain.com/admin/dashboard"); // goPage is a selfmade PHP function that checks whether value is self, home or an url and redirects the user to the correct location
exit;
}
Core.php // the core is above all the content on every page. The script below checks whether the user is on a protected page, these pages are defined in the $protectedpages array.
if (isset($_SESSION['admin_uname']) && !empty($_SESSION['admin_uname'])) {
$admin_uname = $_SESSION['admin_uname'];
} else {
$protectedpages = array("contact", "offertes");
$currentpage = str_replace(".php", "", basename($_SERVER['PHP_SELF']));
if (in_array($currentpage, $protectedpages)) {
$_SESSION['error_msg'] = 'Your session either expired or you are not logged in. Please try again.';
header('location: //domain.com/admin/login');
exit;
}
}
When the user is logging out by going to the logout.php page. closes the browser, reopens the browser, goes back to login.php the if (isset($_SESSION['admin_uname']) part of the code on the login.php page is being executed, the user will pass by the core.php and return back to the login.php page with the message Your session either expired or you are not logged in. Please try again. because the core.php doesn't detect the user to be logged in or at least it doesn't detect $_SESSION['admin_uname'] is set or not empty. Normally you would expect this kind of behavior to trigger an infinite loop but it doesn't do that.
I hope it all makes sense and I narrowed it down to the code above. There is no other part of the script that can set the $_SESSION['admin_uname'] variable.

How to grant access to certain users using PHP

I am having an issue with PHP, as I am trying to write a program that will redirect the user back to the previous page (membersOnly.php). Here is the code that isn't currently working for me.
$sess = $_SESSION['sess_username'];
if ($sess == "admin") {
return;
} else {
header("Location: membersOnly.php");
}
My attempt is to only allow the user "admin" into the admin.php page. This code is the first thing to run. The $_SESSION['sess_username'] variable is assigned in login.php with the following code:
session_start();
$_SESSION['sess_username'] = $_POST['user'];
header("Location: membersOnly.php");
Now I know I am correctly setting the session username, because in any page I choose, I can use echo $_SESSION['sess_username']; and it displays the username. But I am not sure what I am doing wrong when I try to send the user back to membersOnly.php if their username is not admin. Currently when I try to go to that page, it denies access to any user, including admin.
[EDIT: SOLVED]
I forgot to add session_start(); at the top of the page.
Danbopes is right, you are "returning" an empty page. You can simply do this. Now note that this code will not work unless the username "admin" is saved in the session.
$sess = $_SESSION['sess_username'];
if($sess !== 'admin'){
header("Location: membersOnly.php");
exit();
}
//ADMIN CONTENT

Re-directing to certain page if logged in

I have a main page that has a log in link on it that takes the user to a login page. However, if a user is already logged in I want to take the user to another page, for example a info page.
I have this function:
function logged_in_redirect() {
if (logged_in() === true) {
header('Location: client.php');
exit();
}
}
I'm wondering where to put this? I've tried pretty much everything. If i put this on the login page, it does not redirect me when i am logged on. I've tried adding it as an onclick function for the link on the home page but it didn't work.
This is my logged_in() function:
function logged_in() {
return (isset($_SESSION['user_id'])) ? true : false;
}
Any suggestions?
Edit:
I have currently fixed the problem by making the button on the home page link to a test.php file which has this code:
<?php
include 'core/init.php';
if (isset($_SESSION["user_id"])) {
header('Location: client.php');
}
else {
header('Location: info.php');
}
?>
Is there any way around this?
If your session is set and the user is properly authenticated this will work.
You don't need extra function to check whether login is set unless you have a common file which is handling authentication related stuff and all the other files calling its function to check if the user is logged in..
Login Page:
<?php
//check if the user is already loggedin
if(isset($_SESSION["user_id"]){
//assuming client.php is in the same directoy
header("Location: client.php"); //you don't need exit since it will be redirected
}
//your login stuff. if your user_id was not set this part will be executed
?>
Also don't forget to destroy session once you log out..

Login Page in PHP

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.

PHP session does not work from page to page

To login I use:
<?php
session_start();
if($_POST){
$csUSER='USERNAME';
$csPASS='PASSWORD';
$user=$_POST['user'];
$pass=$_POST['pass'];
if ($user==$csUSER) {
if ($pass==$csPASS){
$_SESSION['cdb']="1";
header("Location: /");
exit;
} else {
$passerror='<span class="errormsg">Wrong Password.</span>';
} // END IF PASSWORD
} else {
$usererror='<span class="errormsg">Wrong Username.</span>';
} // END IF USERNAME
} // END IF $_POST
?>
To allow myself to do admin tasks per page (included in all pages [top of page]):
<?php
session_start();
if(isset($_SESSION['cdb'])){
$loggedn="WORD";
}
?>
This allows me to:
<?php
if ($loggedn=="WORD") { WHATEVER }
?>
And to make sure I only have access to backend pages when logged in (included in all backend pages):
<?php
// backend login check
if($loggedn!="WORD") {
header("Location: /"); // if not logged in, go to homepage
exit;
}
?>
The problem is, it works perfect on my pc, but I have another pc my wife uses for data collation and it does not stay logged in on her pc. We both use Linux (Fedora) with FF. I have been over ever line of code in each page, help!
A few things to check:
Ensure that you are starting with a clean slate. Clear cache and cookies in your browser to ensure that you don't have an old session open.
Ensure that session data is being stored on the new machine. Session data is commonly stored in /tmp
Ensure that there is no client-specific code being executed in relation to the session.
Call the exit function after redirecting to another page, otherwise the following code will be executed anyway, what can lead to strange behaviour.
if($loggedn != "WORD")
{
// redirect to login page
header("Location: login.php");
exit;
}
// the following code will be executed if exit is not called
...

Categories