Displaying username in URL with header(...); - php

I have a site that let's me login and displays a new form to post for posting an artcile once the user has logged in.
<?php
if (!empty($_POST['username']) && !empty($_POST['password'])){
if (empty($fetchedRows)) {
echo "<p>Invalid username and/or password</p>";
}
else {
echo "<p>Logged in</p>";
header ('Location: index.php?user=' . $_POST['username']);
?>
<form method="post" id="post-article">
</form>
<?php
}
}
?>
I want to have the username displayed in my URL. This works, however when I reach header ('Location: index.php?user=' . $_POST['username']);, the rest of the code won't run. It is supposed to display a new form if the user credentials are valid.
All of it works if I remove the header(...); line.

put your form code on index.php
<form method="post" id="post-article">
</form>

You are checking POST[username] and POST[password].
if everything is ok, you are redirecting it to the same location (index.php) with GET[user] (index.php?user=xxx)
It now comes to index.php, WITHOUT POST[username] and POST[password]. So it should display "Invalid username and/or password"
What you should do is, you should check $_SESSION[username] first. If it's empty it should check POST[username] and POST[password]. If all is ok you will do $_SESSION[username] = $_POST[username], then redirect.

Related

How to call an HTML file from PHP

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()

PHP Session lost/login not working

I have a question regarding sessions in php. I made a login page, and whenever I tried it, it just gave me a redirect error. So I followed the answer from this question.
So now, instead of getting the redirect error, whenever I press the login button nothing happens, the form is emptied and that is all. What am I doing wrong? This is currently how the code which is giving me issues looks like.
index.php:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$password = $_POST['password'];
$file = file_get_contents("data.txt");
if (strstr($file, "$name||$password")) {
$_SESSION["valid_user"] = $_POST["name"];
$_SESSION["valid_time"] = time();
Header("Location: welcome.php");
} elseif (empty($name) && empty($password)) {
echo "Both fields are empty. Please fill them.";
} elseif (empty($name)) {
echo "No name was entered.";
} elseif (empty($password)) {
echo "No password was entered";
} else {
echo "Wrong credentials, please try again.";
}
}
To be more specific the code which I think is the problem is this part:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
But whenever I try it I either get the redirect error:
My browser gives me "ERR_TOO_MANY_REDIRECTS" when I try to enter the page.
or the page just empties the form and nothing else happens. And the error messages which are supposed to be displayed when I don't type anything in the form is not displaying either. It's been giving me headaches the whole day today so if anyone could just point me in the right direction that would be great.
Also the form HTML I use in index.php:
<body>
<form method="post" action="index.php" >
<p>Enter name:</p>
<input type="text" name="name" />
<br/>
<br/>
<p>Enter password:</p>
<input type="password" name="password" />
<br/>
<br/>
<input type="submit" value="Login" name="submit"/>
</form>
</body>
I think there are too many errors related to code. There must be spaces between the opening PHP tag and session_start();.
Plus, the conditional statement you've given in if (isset($_SESSION['valid_user'])) is being interpreted as "if it IS set". What you should have used is the ! operator, meaning if it is "NOT" set.
That is why you are getting "too many redirects".
<?php session_start();// try putting space between here
if (!isset($_SESSION['valid_user'])) {
header("Location: login.php"); // Redirect back to your login page
exit();
}
also in } elseif (empty($name) && empty($password)) {
// all elseif should be like else if(condition)
also change file names.
You should also add an exit; after every header, otherwise your code will want to continue to execute.
Problem is here when you have a valid user then you are trying to redirect it on index.php which again check for valid user and again redirect on index.php its like INFINITE loop.
Thanx #Fred-ii-
You've got your answer but here is an explanation about "Too many redirects". You are getting that error on your browser because your code is keep redirecting to another page. Both of your statements are returning true:
if (isset($_SESSION['valid_user'])) {
} //Returning true - Redirect to index
if (strstr($file, "$name||$password")) {
} //Returning true - Redirect to welcome
As there are/were no exits after the redirects, the code carries on executing: redirect here than redirect there...
Also you should check the session validation as follows:
if(!isset($_SESSION['session']) || $_SESSION[''] == "")
This will check if the session is not set OR empty.

Redirect page when user is verified

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.

Website Redirect if not login

Here is my login form. aka index.php
<form class="form-3" action="login.php?log=ok" method="post" >
<input type="text" name="username" id="login" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="submit" name="submit" value="Submit">
</form>
And here is my login checker. aka login.php
<?php
require_once 'classes/Personel.php';
$personel = new Personel();
$personel->setUsername($_POST['username']);
$personel->setPassword($_POST['password']);
$personel->login();
header("Location: index.php");
// REDIRECT
session_start();
if (strcasecmp($personel->getRole(), "LTO") == 0 ) {
$_SESSION['role'] = "LTO";
$_SESSION['personel'] = $personel;
header("Location: LTO");
}else if(strcasecmp($personel->getRole(), "LTFRB") == 0){
$_SESSION['role'] = "LTFRB";
$_SESSION['personel'] = $personel;
header("Location: LTFRB");
}else if(strcasecmp($personel->getRole(), "LGU") == 0){
$_SESSION['role'] = "LGU";
$_SESSION['personel'] = $personel;
header("Location: LGU");
}else if(strcasecmp($personel->getRole(), "ADMIN") == 0){
$_SESSION['role'] = "ADMIN";
$_SESSION['personel'] = $personel;
header("Location: admin");
}
?>
now when i try to access any accounts from them i can easily open its index page and other pages even i'am not login. How can i prohibit that? and how can i avoid the url rewriting?
eg. the index page of admin
try to open my link the correct account is admin-admin also try a wrong one..
Big Thanks in advance.
First thing, you need to set the redirect to index.php in proper place, with some condition.
I get your problem, but are you checking the session on each and everypage?
You need to implement a check at the beginning of each page that whether the session is properly set or not. Else redirect back to index.php.
You need to implement this code before each of your pages:
session_start();
if(isset($_SESSION['role'])){
if($_SESSION['role'] != "ADMIN") { //change the "ADMIN" to your unique role per page
echo "Access denied";
exit();
}
else {
header("Location: index.php");
}
You are calling header("Location: index.php") without any condition.
That means that you are always redirecting to index.php.
Any call to login.php will result in automatic redirect to index.php.
I don't know what $personel->login() exactly does but your code should look something like:
$authorized = $personel->login();
if (!$authorized) {
header("Location: index.php");
exit();
}
Also - session_start() should be at the top of the code.
Hope this helps!
You can place a check at the top of every page, and if user not logged in redirect them to an appropriate page, for example a login page.
Here's one approach to doing this.
When you login, set a $_SESSION variable (something like user_id), like this:
//If successful login:
$_SESSION['user_id'] = $userid_from_the_db;
Note that when using sessions, you must place session_start(); at the very TOP of each page.
Then, you can check if the user is logged in before displaying any page data.
Something like:
<?php
protect_page();
Where protect page can look like this:
if (isset($_SESSION['user_id'])===false) {
echo '<p>Please log in first</p>';
echo '<meta HTTP-EQUIV="REFRESH" content="5; url=login.php">';
}
Consider viewing this (free) tutorial from phpAcademy:
Registration and Login - Procedural version
Registration and Login - OOP version
Notes:
You can use either of these methods to redirect the page:
header("Location: pagename.php");
This is the preferred way, however you cannot output any other headers before using this command or it will fail.
<meta HTTP-EQUIV="REFRESH" content="5; url=pagename.php">
As a work-around, you can use this method to redirect the page, and the bonus is that it will wait the specified number of seconds before doing so (5 in this case, or zero if you choose).

Else statement to return to previous function

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>

Categories