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()
Related
i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.
As you know in a php script when you call Return or Die it prevents the rest of HTML codes from rendering.
In an occasion when I just want to stop the php script but not whole the page what would I do?
Ex:
<?php
if(!isset($_POST['txt_username']))
{
echo "Please enter your username";
return;
}
?>
<i want="this html">to be rendered</i>
I want my HTML codes to be rendered afterward.
Thanks for reading.
Your question is not clear, but you need to stop the PHP code to execute, but the HTML to render? You might need output buffer or functions.
E.g.:
<form action="" method="post" >
<input type="text" name="txt_username" />
<input type="submit" />
</form>
<?php
function doSmth(&$password) {
if(!isset($_POST['txt_username']))
{
echo "Please enter your username";
return false;
}
$password .= "333";
echo "You password has been changed to $password";
}
$password = 128;
doSmth($password);
?>
<body>
<p> <b> Your password is <?= $password; ?> </b></p>
</body>
Examples:
Text field is set:
Output:
You password has been changed to 128333
Your password is 128333
Text field is not set:
Output:
Please enter your username
Your password is 128
Use the conditional statement to include more PHP is needed. The HTML can then be rendered regardless of the PHP's if/else statement. Example:
<?php
if( !isset($_POST['txt_username']) )
{
echo "Please enter your username";
}
else
{
//Some dditional PHP functions
}
?>
<i want="this html">to be rendered</i>
<?php
$stateOfRender = false;
if(!(isset($_SESSION['sessionid']))) {
echo "You have not logged yet. Now you are redirecting to Login Page";
header('Refresh: 5; URL = login.php');
} else {
$stateOfRender = true;
}
// In everywhere you can use this variable to control your statement
// for example:
if($stateOfRender) {
// Open DB connection and fetch user data and settle it to page.
}
?>
In my php code i use this method to handle process. Generally i use it in db connection. If dbconnection is success i render page with control this variable. I hope to it helps you.
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.");
}
?>
so I need to figure out how I can get my else statement to return to my previous function which is passprotect.html (the file I start on).
So I write in my password and click submit.
When I hit submit it checks with my PHP if the password is correct or not.
If the password is correct it writes "You did it!".
If it is wrong I want it to return back to the passprotect.html site with an error message saying, "Wrong password, try again!".
Here is my two codes:
<html>
<body>
<title>FriedBitz</title>
<form action="secret.php" method="post">
Password: <input type=password name=pass></input>
<input type=submit value=Enter>
</form>
</body>
</html>
and
<html>
<body>
HERE IS YOUR RESULT
<?php
if ( $_POST['pass'] === 'test')
{
echo "You did it!";
}
else
{
header('Location:www.example.com');
}
?>
</body>
</html>
So as the Marc B noted you can not use header that way.
From the php.net manual -> Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
If you have no option to change layout's of your project files (removing outputs before headers are sent) i suggest you to use ajax for this kind of work.
Or you need to place clickable link for user on a page instead of header.
Example of working header with your code:
<?php
if ( $_POST['pass'] === 'test')
{
$output = 'You did it!';
}
else
{
header('Location:www.example.com');
exit;
} ?>
<html>
<body>
<?php echo $output; ?>
</body>
</html>
OK. I have a page called plans.php, inside I have three links (Plan 1, Plan 2, Plan 3). Each link has its own page and it redirects to login page (login.php, which works fine). So if the user is not logged in when they click lets say on "Plan 2" it will force the user to login so they can see the desired page, all depends of what "Plan" the user chooses.
PROBLEM:
I'm having a hard time redirecting the user back to the "desired Plan (URL)".
Solution:
If the user chooses "Plan 1 or Plan 2 (whatever plan)" then it will force user to login (I have that working fine), after user logs in successfully the user has to be redirected to their respective "Plan page".
If any is familiar with this issue please help.
plans.php
Plan 1
Plan 2
Plan 3
plan-2.php
<?php
ob_start();
include "header.php";
if(!$current_user) {
require_login();
}
ob_end_flush();
?>
HTML code:
What the user is going to see after login page.
<p>Hello, you have been redirected to "Plan 2"</p>
login.php
<?php
ob_start();
include "header.php";
if($current_user) {
req_logout(); }
ob_end_flush();
?>
HTML code:
<form action="authenticate.php" method="POST">
<label for="email">Email</label><br/>
<input type"text" class="input" name="username" id="username" />
<label for="password">Password</label><br/>
<input name="password" type="password" class="input" id="password"/>
<input type="submit" value="Sign In" class="submit"/>
</form>
This file verifies user credentials where the login form submits to.
authenticate.php
<?php
session_start();
require_once "db.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_SESSION['redirect_to']){
header("Location: " . $_SESSION['redirect_to']);
unset($_SESSION['redirect_to']);
}else{
// Default page after user logs in.
header("Location: manage.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
I have some PHP functions in this file.
auth.php
// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `********`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
// Requires a current user (Restrict Access to Page)
function require_login(){
if(!$current_user){
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header('Location: signin.php');
exit("You must log in.");
}
}
Try to send a parameter when a user clicks on a plan link. Pass or save the parameter and after successful login, use that parameter to redirect to the proper page.
in plan-2.php
session_start();
$_SESSION['redirect_to']="plan-2.php";
EDIT:
Here is complete solution using parameter sending via GET and POST (as I have been asked for):
plans.php
Plan 1
Plan 2
Plan 3
plan.php
<?php
ob_start();
$getbackURLid=$_GET['no'];
include "header.php";
if(!$current_user) {
require_login($getbackURLid);
}
ob_end_flush();
?>
signin.php
<?php
ob_start();
include "header.php";
if($current_user) {
req_logout(); }
ob_end_flush();
?>
HTML code:
<form action="authenticate.php" method="POST">
<label for="email">Email</label><br/>
<input type"text" class="input" name="username" id="username" />
<label for="password">Password</label><br/>
<input name="password" type="password" class="input" id="password"/>
<input type"hidden" name="url" value="<?php echo $_GET['url'];?>" />
<input type="submit" value="Sign In" class="submit"/>
</form>
authenticate.php
<?php
session_start();
require_once "db.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_POST['url']){
header("Location: plan.php?no=".$_POST['url']);
unset($_SESSION['redirect_to']);
}else{
// Default page after user logs in.
header("Location: manage.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
auth.php
// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `********`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
// Requires a current user (Restrict Access to Page)
function require_login($getbackURLid){
if(!$current_user){
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header('Location: signin.php?url=$getbackURLid');
exit("You must log in.");
}
}
Since some popular browsers (like Chrome) cache server redirect responses, if you do a server redirect, the requested page will always redirect to the same page as the first redirect the browser encountered.
To solve this, you validation PHP page should contains the following redirection:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
// Check if the session's user is logged in properly
$redirect = "";
if (!$_SESSION['current_user']) {
$target_page= "http://www.myserver.com/login?sender=" + urlencode(curPageURL());
echo "<html>";
echo " <head>";
echo " <script>";
echo " window.location = '", $target_page, "';";
echo " </script>";
echo " </head>";
echo " <body></body>";
echo "</html>"
} else {
?>
<html>
<head>
</head>
<body>
<!-- put your page html here -->
</body>
</html>
<?php
}
?>
Please note that I'm not a PHP developper, my code may contains syntax errors and must be revised properly.
So... yeah, the code may look a little bit crappy but the important thing to remember is to not use the http response redirection. I tried all possible ways to disable response caching but chrome don't care at all. The only safe way I found is to do the redirection using javascript. I did not try the META http-equiv="refresh" way though. I guess it's safe as well since we see that often.
Another thing to remember is to avoid rendering your sensitive page content if the user is not logged in.
With that in mind, you should be good to go.
Hope it helps!