Restrict access to page with session_start() - php

I'm working on a login page who if you login you're redirected to a upload page and i'm trying to restrict access to the upload page if you are not logged in and i don't want people to have access tot he page if they are not loggin.
So far this is my code but i don't know how to restrict access with session's.
my login script:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="ana"; // Database name
$tbl_name="user"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['user'];
$mypassword=$_POST['pass'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE user='$myusername' and pass='$mypassword'";
$result=mysql_query($sql);
// If result matched $myusername and $mypassword, table row must be 1 row
if($myusername=='ana' and $mypassword==''){
session_start();
$_SESSION["myusername"]=$myusername;
$_SESSION["mypassword"]=$mypassword;
// Register $myusername, $mypassword and redirect to file "login_success.php"
echo "Your login was succesfull!";
header("refresh:3;url=upload.php");
}
else {
echo "Wrong Username or Password, please try again.";
header("refresh:3;url=connect.php");
}
?>
and the page that redirects you to it is :
<!DOCTYPE HTML>
<!--
Astral by HTML5 UP
html5up.net | #n33co
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<?php
session_start();
?>
<html>
<head>
<title>Ana Gemescu - Work work work | Upload </title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<!--[if lte IE 8]><script src="css/ie/html5shiv.js"></script><![endif]-->
<script src="js/jquery.min.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/init.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel.css" />
</noscript>
<!--[if lte IE 8]><link rel="stylesheet" href="css/ie/v8.css" /><![endif]-->
</head>
<body>
<!-- Wrapper-->
<div id="wrapper">
<!-- Main -->
<div id="main">
<!-- Me -->
<article id="me" class="panel">
<header>
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select image to upload:<br />
<input type="file" name="fileToUpload" id="fileToUpload"><br />
<select name="Folder" style="width:500px;margin-bottom:5px;margin-top:5px;" >
<option value="photo" style="padding:2px">Photos</option>
<option value="draw" style="padding:2px">Drawings</option>
<option value="video" style="padding:2px">Videos</option>
<option value="other" style="padding:2px">Other</option>
</select><br />
<input type="submit" value="Upload Image" name="submit">
</form>
</header>
</article>
</div>
<!-- Footer -->
<div id="footer">
<ul class="copyright">
<li>© Ana Gemescu</li><li>Design: HTML5 UP, Coded by: zapo</li>
</ul>
</div>
</div>
</body>
</html>
Can please some one help me how do i restrict access to the upload page if your not logged in ?
If you need more information please let me know

Check for the $_SESSION["myusername"], like this
if(ISSET($_SESSION["myusername"]))
{
//upload page code
}
else
{
print "access denied";
}

Always put session_start(); at the top of your page... before any output.
Verifying whether a session variable has been set is simply:
session_start(); //at the very top of your page
if(!isset($_SESSION['your_index'])){ //for example user
//do something
//for example, send the user back to the login page
header('Location: myloginform.php'); //path to where your login form is located. Headers need to be above any output or they will produce an error and thus not work as intended (or at all even!)
exit;
}
Also make sure that you take appropriate security measures in consideration for the script that does the actual uploading of the file.
For example...
Verifying file type being uploaded, you surely don't want to let a user upload anything he/she desires to your server
Correct permissions at your upload folder (e.g. full permissions 777 is just asking for problems)

Start by calling the session_start(); method on each page you need to use it. You can avoid this by calling this method once in a baseclass which sets up your mySQL connection, of course each class that inherits the connection settings will inherit the session_start() method.
As for your authenticity check, consider the below example:
//Create a new session object that will determine when a user is authenticated.
$_SESSION['isAuthenticated'] = false;
You could possibly initialise this in the class which is called when the user successfully logs in, in that case the boolean value would switch to true on successful login.
//Your welcome page, after log-in
if( isset($_SESSION['isAuthenticated']) )
{
$_SESSION['isAuthenticated'] = true
}
On each new page you could then create a condition which checks if the value is set to true (user is authenticated)
if( !isset($_SESSION['isAuthenticated']) || $_SESSION['isAuthenticated'] == false)
{
echo "You are not authenticated to view this page, please log-in";
}
else
{
//start your HTML here
}
This rules out someone simply typing the page url into the address bar and bypassing your login logic.

When a user logs in to the system, then store a flag in a session e.g. $_SESSION['loggedin'] = 1; read out the value each call. If $_SESSION['loggedin'] == 1 then user is safe.

Thank you all for your help! I've manage to made it with session_start();.
Keep up the good work guys and thanks again.

Related

Redirect from a login page

I am building an intranet-like website for my high school students to use and I would like them to login using google sign-in because they all have google accounts. I have successfully integrated google sign-in using Google's instructions.
When a new user visits the first page (the login page) of my site and logs in, I would like them to be automatically redirected to the second page. I have researched this on SO and elsewhere but not found anything yet. How could I do this?
Also, if a user tries to access any page other than the first page without having first logged in, how can I redirect them to the first page?
My website address and code is below. Let me know if you need any more information. Thanks!
First page: http://davidstarshaw.atwebpages.com/test/index.php
<!DOCTYPE html>
<head>
<title>Test login page</title>
<meta name="google-signin-client_id" content="795531022003-rdb02epf7o0qpr5p83326icrseh82gqa.apps.googleusercontent.com"> <!--My google sign-in client ID-->
<script src="https://apis.google.com/js/platform.js" async defer</script> <!--Google platform library. Needed for sign-in-->
<script src="script.js" async defer></script>
</head>
<body>
<p>This is the first page.</p>
<div class="g-signin2" data-onsuccess="onSignIn"></div> <!--This code is straight from google-->
Sign out<br>
<a href=home.php>Manually go to the second page</a>
</body>
Second page: http://davidstarshaw.atwebpages.com/test/home.php
<!DOCTYPE html>
<head>
<title>Test home page</title>
<meta name="google-signin-client_id" content="795531022003-rdb02epf7o0qpr5p83326icrseh82gqa.apps.googleusercontent.com"> <!--My google sign-in client ID-->
<script src="https://apis.google.com/js/platform.js" async defer></script> <!--Google platform library. Needed for sign-in-->
<script src="script.js" async defer></script>
</head>
<body>
<p>This is the second page.</p>
<div class="g-signin2" data-onsuccess="onSignIn"></div> <!--This code is straight from google-->
Sign out<br>
<a href=index.php>Manually go back to the first page</a>
there are lots of ways you can do this. but
the simplest solution is to put this code at top of each php page so that if user visit any page and session is not found then user will be redirected to login page.
<?php
// put at the top of each php page.
session_start();
if (!isset($_SESSION["Authenticated"]))
{
header("location: login.php");
}
?>
and replace login.php with your login php file. what it does just check session variable, if not found then redirect to login page. and on login page you can set session variable.
On login php page (where you ask user to enter his email password) put the following code, you can do this:
get user name and password from html form then pass to database in order to find that register user. if found that user from mysql results row then put these values in session variable.
<?php
// put in only login page
$email = $_REQUEST['email']; // get email from html form
$password = $_REQUEST['password']; // get password from html form
// search for this user in database.
$query = mysqli_query("select * from MyRegisteredUser where email='$email' and password='$password'");
// if any record is founf then get that records fields
if(mysqli_num_rows($query)){
$result_row = mysqli_fetch_fields($query);
$_SESSION["Authenticated"] = true;
$_SESSION['id'] = $result_row->id;
$_SESSION['Name'] = $result_row->name;
$_SESSION['Email'] = $result_row->email;
}else{
// session can't be set due to no user found. so redirect back with some error.
unset($_SESSION);
header("location: login.php");
}
?>
your html form will look like this.
<!DOCTYPE html>
<head>
<title>Login</title>
</head>
<body>
<form method="post" action="login.php">
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email"></input>
<label><b>Password</b></label>
<input type="password" placeholder="Password" name="password"></input>
<input type="submit" value="Login" name="login_btn"></input>
</div>
</form>
</body>
</html>

Building a Log In page with PHP and MySQL Project

I am creating a login form, profile page and logout, but when I receive a wrong username message on the page and click the x button, it does not close. Also, when I add just the username and click on the log in button, the page goes blank. Could someone assist me in identifying what is askew here?
<?php
/*
STEPS WE NEED TO TAKE...
1. Build Login HTML form
2. Check if form has been submitted
3. Validate form data
4. Add form data to variables
5. Connect to database
6. Query the database for username submitted
6.1 If no entries: show error message
7. Store basic user data from database in variables
8. Verify stored hashed password with the one submitted in the form
8.1 If invalid: show error message
9. Start a session & create session variables
10. Redirect to a "profile page"
10.1 Provide link to "logout" page
10.2 Add cookie clear to logout page
10.3 Provide link to log back in
11. Close the MySQL connection
*/
if(isset($_POST['login'])) {
// build a function to validate data
function validateFormData($formData) {
$formData = trim(stripslashes(htmlspecialchars($formData)));
return $formData;
}
// create variables
// wrap the data with our function
$formUser = validateFormData($_POST['username']);
$formPass = validateFormData($_POST['password']);
// connect to database
include('connection.php');
// create SQL query
$query = "SELECT username, email, password FROM users WHERE username='$formUser'";
//store the result
$result = mysqli_query($conn, $query);
// verify if result is returned
if(mysqli_num_rows($result) > 0) {
// store basic user data in variables
while($row - mysqli_fetch_assoc($result)) {
$user = $row['username'];
$email = $row['email'];
$hashedPass = $row['password'];
}
// verify hashed password with the typed password
if(password_verify($formPass, $hashedPass)) {
// correct login details!
// start the session
session_start();
// store data in SESSION variable
$_SESSION['loggedInUser'] = $user;
$_SESSION['loggedInEmail'] = $email;
header("Location: profile.php");
} else { // hashed password didn't verify
// error message
$loginError = "<div class='alert alert-danger'>Wrong username / password combination. Please try again.</div>";
}
} else { // there are no results in database
$loginError = "<div class='alert alert-danger'>No such user in database. Please try again. <a class='close' data-dismiss='alert'>×</a></div>";
}
// close the mysql connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login</title>
<!--Bootstrap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!--HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries-->
<!--WARNING: Respond.js doesn't work if you view the page via file://-->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<h1>Login</h1>
<p class="lead">Use this form to log into your account</p>
<?php echo $loginError; ?>
<form class="form-inline" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<div class="form-group">
<label for="login-username" class="sr-only">Username</label>
<input type="text" class="form-control" id="login-username" placeholder="username" name="username">
</div>
<div class="form-group">
<label for="login-password" class="sr-only">Password</label>
<input type="password" class="form-control" id="login-password" placeholder="password" name="password">
</div>
<button type="submit" class="btn btn-default" name="login">Login!</button>
</form>
</div>
<!--Bootstrap JS-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
"Fred, the varchar on my db for password is set to 255. There is no existing hashed password as of yet. I am trying to create a login page to create one in the db. – Daniel Cortes"
The problem is that there isn't a hashed password in your database to be compared with.
You will need to create one using the password_hash() function.
http://php.net/manual/en/function.password-hash.php
Sidenote:
Using stripslashes(htmlspecialchars doesn't safeguard against an SQL injection. It's best to use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
Also Your alert is not disappearing because Bootstrap depends on Jquery lib, and you did not imported it.

Login functionality in HTML page

I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O

How do you return login form errors to the same page using PHP?

I'm relatively new to PHP and have exhausted the internet trying to find an answer to this problem. I've looked at countless examples but people seem to very different login systems to mine and I have trouble deciphering it.
Here is my code so far:
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Video for Education Log In</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
videoedu.edu </div>
<div id="menu">
<ul>
<li>Create Account</li>
<li>About Us</li>
</ul>
</div>
</div>
<br><br><br><br>
<div id="page">
<div id="content">
<h2>Video for Education helps you connect and share with the videos in your life.</h2>
<h3>Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome
Upload Share Create Using video for your education purposes. Lecturers Welcome</h3>
<div class= "form">
<form name="login" method="post" action="checklogin.php">
Username: <input type="text" name="myusername" id="myusername" class="textb"/><br />
Password : <input type="password" name="mypassword" id="mypassword" class="textb"/><br />
<br>
<input type="submit" name="login" value="Login" id="login" class="texta" />
</form>
</div>
</div>
</div>
</div>
</body>
</html>
checklogin.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "test";
$tbl_name = "members";
mysql_connect("$host", "$username", "$password")or die("Cannot connect.");
mysql_select_db("$db_name")or die("Cannot select DB.");
$myusername=$_POST["myusername"];
$mypassword=$_POST["mypassword"];
if ($myusername&&$mypassword)
{
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else
{
echo "Wrong Username or Password";
}
}
else
echo "You have left one or more fields blank.";
?>
login_success.php
<?
session_start();
if( !isset( $_SESSION['myusername'] ) ){
header("location:account.html");
}
echo "Welcome, ".$_SESSION['myusername']." - You are now logged in.<br>";
echo "<a href=logout.php>Logout</a>"
?>
<html>
<body>
</body>
</html>
logout.php
<?php
session_start();
session_destroy();
echo "You have been logged out, <a href='index.php'>click here</a> to return."
?>
I have tried inserting this into index.html and changing the file name to index.php.
$submit = $_POST["login"];
if($submit)
{
}
...but it just constantly displays one of the errors ('Wrong username or password') down the bottom of the page at all times.
I want it so that if the user enters a wrong username or password, or leaves a required field blank, the error will pop up on the same page, instead of going to a new ugly, blank PHP page with the error message in the top left-hand corner.
In checklogin.php, instead of echoing an error, use this:
die(header("location:index.html?loginFailed=true&reason=password"));
or something similar, and in your index.html page, just have PHP generate the HTML message, something like this:
<input type="submit" name="login" value="Login" id="login" class="texta" /><br /><br />
<?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
</form>
Also, make sure to die() or exit() when you use header to redirect the page, otherwise the rest of your script continues to run.
What you can do is, redirect back to your page if data is invalid. Put errors into session and display them on page:
e.g.:
<?php if(isset($_SESSION['Login.Error']) { echo $_SESSION['Login.Error'];
unset($_SESSION['Login.Error']); } ?>
<form ....
and your error will be visible on page.
In your PHP
$_SESSION["Login.Error"] = 'Invalid credentials';//redirect back to your login page
In checklogin.php, if the user enters a wrong username or password, use the code like this:
echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";
It will pop up the error message at the same page (login page), instead of going to a blank PHP page.
You would want to make your index.html page a PHP page, and have the form submit to itself, i.e. to index.php. In this way, you your index page can do the login check for the form values and display the output of the page appropriately, or use headers to redirect if everything validates.
It's hard to tell the effect that your attempt may have had without seeing it in the full context, but the gist of the situation is you need the form to submit to itself and handle it's login processing.
It looks like you want/need to integrate it with jQuery or some other Javascript/AJAX library
to make things more presentable. jQuery has an plugin for form validation that's is very easy to integrate to your project (obviously jQuery library is minimum requirement).
jQuery site and
jQuery validation plugin.
You may also consider using a PHP Framework like CodeIgniter which is also has a very helpful form validation library. CodeIgniter is scary at the beginning (like all MVC based programming library/framework) but it's worth it. you can watch some tutorials on netTuts+ they've created a series of tutorials called CodeIgniter From Scratch, is not from the latest version but is easy to adapt.

PHP login not working - user still sees the login form on protected pages after logging in

------ SOLVED ------
Hi everyone, I have now solved this issue and it was my inexperience and trying to be clever that caused this issue, as you can also see from the comments below the issue was in my .htaccess file. I had put RewriteRule ^admin adminlogin.php so this was changing any page containing admin back to adminlogin.php
------ORIGINAL QUESTION------
Im trying to get a simple login script working on a website. It is coded in php and it is as follows:
adminlogin:
<div class="login">
<form name="form1" method="post" action="checklogin.php">
<table width="379px" border="0px" cellpadding="3px" cellspacing="1px">
<tr>
<td colspan="3"><strong>Admin Login</strong></td>
</tr>
<tr>
<td width="78px">Username</td>
<td width="6px">:</td>
<td width="294px"><input name="myusername" type="text"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</div>
checklogin.php:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="Logins"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die(mysql_error());
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM `$tbl_name` WHERE UN='$myusername' and PWD=md5('$mypassword')";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file “adminloginsuccess.php"
session_start();
$_SESSION['user'] = $myusername;
header('location:adminhome.php');
}
else {
header('location:adminloginretry.php');
}
?>
adminhome.php:
<?php $thisPage="Admin Home";
session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/meta.php'); ?>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="header">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/header.php'); ?>
<div id="links">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/links.php'); ?>
</div><!--close links-->
</div><!--close header-->
<div id="sidebar">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/sidebarimage.php'); ?>
</div><!--close sidebar-->
<div id="content">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/adminhomecontent.php'); ?>
</div><!--close content-->
<div id="extra" align="center">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/fblb.php'); ?>
</div><!--close extra-->
<div id="footer">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'); ?>
</div><!--close footer-->
</div><!--close container-->
</div><!--close wrapper-->
</body>
</html>
adminhomecontent.php:
You Have Successfully Logged In.<br>
Log Out
Now for some reason when I go and log in, I am redirected and the address bar says www.gemma-hyde-fashion-sketches.co.cc/adminhome.php but still shows the login form, and if I view the source I see the source for adminlogin.php.
I am new to PHP, could anybody assist, I found this code online so have tried myself to understand it as fully as I can
------EDIT------
I have created a log in for stackoverflow users. If you head over to www.gemma-hyde-fashion-sketches.co.cc/adminlogin.php and use the username stackoverflow and the password stackoverflow you should see the same results i'm getting (there isnt actually anything in the admin area at this time anyway)
------EDIT FOR JUDDA------
Yes what I mean is that if I log in, the address bar shows: http://www.gemma-hyde-fashion-sketches.co.cc/adminhome.php which is what i expected to be redirected to. However if i right click and view source I see
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gemma Hyde Fashion Sketches | Admin Login</title>
<meta name="title" content="Gemma Hyde Fashion Sketches | Admin Login" />
<meta name="keywords" content="Admin Login, gemma hyde fashion sketches, fashion, fashion design, fashion sketches, fashion design sketches, clothes design sketches" />
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
which is the same as what the adminlogin.php page would show, this makes me think that this section at the top of adminhome.php:
session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
}
Is just redirecting because it cannot pick up that it is logged in.
Does that clear things up?
It sounds to me like PHP isn't running on the file if you are able to see the actual PHP for it (which I understand from the statement "and if I view the source I see the source for adminlogin.php"). Do other PHP pages work (i.e. <?php phpinfo();?>)?
If you suspect the session is not set check that in adminhome.php
Change this code
Session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
to this
Session_start();
exit(var_dump($_SESSION));
I have now solved this issue and it was my inexperience and trying to be clever that caused this issue, as you can also see from the comments below the issue was in my .htaccess file. I had put RewriteRule ^admin adminlogin.php so this was changing any page containing admin back to adminlogin.php

Categories