Else statement to return to previous function - php

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>

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.

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

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.

stop preventing HTML code rendering with Return and Die function in php

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.

Having Issue with PHP Session

Can you please let me know why my session setting is not working correctly? I have a simple Form in index.php file as:
<?php
session_start();
$_SESSION['uid'] = 'test';
?>
<!DOCTYPE HTML>
<html>
<body>
<form method="POST" action="validate.php">
Password: <input type="text" name="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I also have a validate.php file which is like this:
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if(($_POST['name']) == $_SESSION['uid']){
header ("Location: target.php");}
else{ echo $err; }
?>
and finally the target.php page is like this
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>
Now my problem is when ever I run the validate.php or target.php URLs directly from the browser address bar like (..localhost/PHP/Session_3/validate.php) I still get access to the target page!
Can you please let me know why this is happening? and how I can set a better isset() function to prevent this?
Thanks for you time and comments
You have to check for session on every page you load,
Adding
if(!isset($_SESSION['uid'])){
header ("Location: index.php");
}
may help on each page. And dont forget to delete the session on every logout.
//Four Steps to close a session
//i.e. logging out
//1. Find the Session
session_start();
//2. Unset all the session variables
$_SESSION=array();
//3. Destroy the session cookie
if(isset($_COOKIE[session_name()])){
setcookie(session_name(),'',time()-42000,'/');
}
//4. Destroy the session
session_destroy();
//redirect_to("index.php?logout=1");
You have code to validate a password but that's all you've written so far. You are neither storing the result of the validation, nor preventing access to protected pages.
To store validation result:
if ($_POST['name']==$_SESSION['uid']) {
$_SESSION['validated'] = true;
}
To protect a page:
if (!isset($_SESSION['validated'])) {
header('Location: http://example.com/');
exit;
}
($_POST['name']) will return a Boolean value, its an if statement on his self ( because of the ( and ) you put around it. It will give you a true value when the $_POST is available.
So what you get is if ((True) == $_SESSION['uid']). Because the code sees the True value it will not run the code after it, its allready true in it.
Thats why it always comes the the header line
So this should do the trick in your case ( there are better ways to do it btw )
if($_POST['name'] == $_SESSION['uid']){
header ("Location: target.php");
}
else
{
echo $err;
}
You have almost done it. There is no need of validate.php. just copy below code in index.php,
<?php
session_start();
if(!empty($_POST['name']) and ($_POST['name']=='test') ){
$_SESSION['uid']='test';
header ("Location: target.php");
}
?>
and update form action to
<form method="POST" action="**index.php**">
and in index.php form, use below code.
<?php
session_start();
if(empty($_SESSION['uid'])){
header ("Location: index.php");
}
?>
You can access target.php if you close and reopen browser. Because at the start there is no value in session and post
So this line,
if(($_POST['name']) == $_SESSION['uid'])
equals
if ( "" == "" ) //true
You should use isset(),
validate.php
<?php
session_start();
$err="You Have to Insert The Password to Get into Page";
if (isset($_POST['name']) && isset($_SESSION['uid'])) {
if ($_POST['name'] == $_SESSION['uid']) {
$_SESSION["logged"] = "logged";
header ("Location: target.php");
} else {
echo $err;
}
} else {
header ("Location: index.php");
}
?>
And If you want to make target.php inaccessible directly if not logged, That would be like this,
target.php
<?php
session_start();
if (!isset($_SESSION["logged"])) {
//No access directly if not logged
header ("Location: index.php");
}
?>
<!DOCTYPE HTML>
<html>
<body>
<img src="session.jpg">
</body>
</html>

Categories