I started studying PHP few weeks ago and I'm a little bit confused with conditional embed HTML between PHP code blocks and setting cookies. What I want to do is a simple code that checks your name, password and e-mail, sets cookie (if they are valid); when you have already logged in, you should see "log out" button. So, my code:
<?php
if (($_POST['name'] == 'admin') and ($_POST['pass'] == 'admin') and ($_POST['mail'] == 'admin#gmail.com')) {
setcookie("Test","Value");
echo "Success!!! <br/>";
}
if ($_POST['logout']) {
setcookie("Test", "", time() - 3600);
echo "Goodbye!";
}
?>
<?php if(isset($_COOKIE['Test'])) :
?>
<input type="submit" value="logout"/><br/>
<?php endif ?>
<?php if(!isset($_COOKIE['Test'])) :
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<form action="" method="POST">
<input type="text" name="name"/><br/>
<input type="text" name="pass"/><br/>
<input type="text" name="mail"/><br/>
<input type="submit" value="go"/><br/>
<?php endif ?>
However, I can't figure out how to make it work properly: when I enter correct username, password and mail, I don't see "logout" button, there's still a form and i need to enter username again to finally see "logout". Second problem, when I press "logout", nothing happens. I guess I can't set the cookie because headers were already sent, but I can't figure out how to rewrite it.
Has per #RowlandShaw stated in the comment, setcookie() will affect only the future requests, not the current one.
Here is your corrected code:
<?php
if($_POST)
{
if(isset($_POST['name']) && isset($_POST['pass']) && isset($_POST['mail']))
{
if (($_POST['name'] == 'admin') and ($_POST['pass'] == 'admin') and ($_POST['mail'] == 'admin#gmail.com')) {
setcookie("Test","Value");
echo "Success!!! <br/>";
echo '<form action="" method="POST">'.
'<input type="submit" value="logout" name="logout"/><br/>'.
'</form>';
}
}
if (isset($_POST['logout'])) {
setcookie("Test", "", time() - 3600);
echo "Goodbye!";
echo '<br/>';
echo 'Login back';
}
}
else
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<form action="" method="POST">
<input type="text" name="name"/><br/>
<input type="text" name="pass"/><br/>
<input type="text" name="mail"/><br/>
<input type="submit" value="go"/><br/>
<?php } ?>
You will have to create a link to the same page so the cookie modification are taken into account. Also, you didn't set up a name on your logout button nor did you specify that the logout action is a POST request by adding the <form> tag (it's GET by default) that made $_POST['logout'] never set.
Related
I am trying to redirect to a different page when a value is entered into 'username' on my login form. But a warning appear saying "cannot modify header information - headers already sent by (output started at /Users/Zach/Sites/Project2/proj2Functions.php:10) in /Users/Zach/Sites/Project2/redirect.php on line 3"
I put the code all the way at the top so I thought the redirect would work. What am I doing wrong?
Here is the code for the login:
if (isset($_POST["submit"])) {
$username = trim($_POST["username"]);
$password = trim ($_POST["password"]);
if (has_presence($username)) {
redirect_to("Homepage2.php");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Start Collay Login(beginLogin)</title>
</head>
<body>
<?php echo "This is the first login page"; ?>
<form action="beginLogin.php" method="post">
Username: <input type="text" name="username" value=""><br>
Password: <input type="text" name="password" value=""><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
And here is the code for the redirect file:
<?php
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
?>
The redirect file code should be the first thing to appear on the page so even if there is a blank space or a line break before the <?php then it will not work or you may turn output_buffering on in your php.ini file by assigning it a value (4096) is generally a good value..
Hope this helps,
Take care and Happy coding..
I have a form which has email as field name. What I am trying to do is if the email is it no equal to $emailToCheck is not equal to $_POST['email'], it should throw an error first time. The second time if the user enters wrong email id again it should always redirect to "error.htm" even if the page refreshes.
It doesn't work the form always shows even if the email id is entered wrong twice.
<?php
if (!empty($_POST['email'])) {
$email="website#test.com";
if($email!=$_POST['email'])
{
$count="1";
}
if($count=="2"){
header("Location: /error.htm");
exit(0);
}
}
if($count!="2"){
?>
<!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=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul >
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
<?
}
?>
You have two issues here:
1. You are defining $count as a string, and never incrementing it. If you look over your code, $count is getting specifically set to 1 every time there is a mismatch. How is supposed to ever get to 2?
2. Furthermore, data here is stateless. How is the script supposed to know what $count was set to on the previous call? You need to also set $count as a session variable so that the script will know what its previous value.
You should try updating your code to something similar to this:
// Check if `email` passed in POST request:
if ($_POST['email']) {
$email = "website#test.com"; //Manually define expected email address.
// Check if provided email does *not* match the expected email:
if ($email !== $_POST['email']) {
// Record the mismatch attempt in session and increment:
if (!($_SESSION['incorrectEmailCount'])) {
// If this is the first mismatch, define the session variable, and set to 1.
$_SESSION['incorrectEmailCount'] = 1;
} else {
// Session variable already set due to previous mismatch. Increment it.
$_SESSION['incorrectEmailCount']++;
}
}
// If user entered incorrect email more than once:
if ($_SESSION['incorrectEmailCount'] > 1) {
// Redirect to error page and stop execution.
header("Location: /error.htm");
exit(0);
}
}
Once the form is submitted, the page reloads, resetting the counter. In order to actually count, you need to provide that value in the form and pass it along to the PHP when the form is submitted.
<?php
// Try to get the amount of attempts from the POSTed data
$count = isset($_POST['count']) ? $_POST['count'] : 0;
if (isset($_POST['email'])) {
$email = "website#test.com";
if ($email != $_POST['email']) {
$count++;
}
if ($count == 2) {
header("Location: /error.htm");
}
}
if ($count <= 2):
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form</title>
</head>
<body id="main_body" >
<div id="form_container">
<h1><a>Form</a></h1>
<form id="form_1123848" class="appnitro" method="post" action="">
<!-- Let the POST data know this is the x attempt -->
<input type="hidden" name="count" value="<?php echo $count; ?>">
<div class="form_description">
<h2>Form</h2>
<p> <input type="text" name="email" value="" /></p>
</div>
<ul>
<li class="buttons">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
<?php endif; ?>
Also, your coding style is far from consistent. Try to work on that!
I'm trying to create a maths quiz page. The first page needs to generate a question shown as a header, that asks the user what two random numbers are multiplied together.
Then depending on the users input, it takes them to a different page.
If they are correct it displays the paragraph "You are correct!".
If they are wrong it displays the paragraph "You are incorrect" and invites the user to try again.
and if they enter a string it displays the paragraph "I don't understand your response" and invites the user to try again.
So far I have the below code, the layout is correct but the header isn't working, and I've attempted to display a new page, but again, they don't load. Anyone know where I'm going wrong?
<?php
$first = Rand(1,10);
$second = Rand(1,10);
echo <h1>"What is " . $first . "times " . $second . "?"</h1>;
if(is_int($_POST['answer']) == 1){
if($_POST['first']*$_POST['second'] == $_POST['answer']){
header("Location: correct.html");
exit();
}
else{
header("Location: incorrect.html");
exit();
}
}
else if(is_string($_POST['answer']) == 1) {
header("Location: response.html");
exit();
}
?>
<!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=utf-8" />
<title>Maths Quiz</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['file:///X|/Software Development/PHP_SELF']; ?>">
<p>Answer<br/>
<input type="text" id="answer" name="answer" /></p>
<p></p>
<button type="submit" name="submit" value="send">Submit</button>
<input type="hidden" name="answer" value="<?php echo $answer; ?>"/></p>
</form>
</body>
</html>
You must have the header() code before any output, especially that echo statement.
Apart from sending the headers before you output something, i think your form action is wrong, it should be
action="<?php echo $_SERVER['PHP_SELF']; ?>"
You are sending the POST via FILE protocol, it won't be processed by Web Server/PHP.
And also, you are not POSTing "first" and "second" fields.
I'm trying to redirect the user to another webpage depending on which radio button they have checked.
Here is the relevant code:
<form action="sample.php" method="post">
<input name="survey" type="radio" value="Yes" /> Yes
</br>
<input name="survey" type="radio" value="No" /> No
</form>
<?
if ($_POST['survey'] == "Yes")
{
header('Location: http://localhost/survey.php');
}
else if ($_POST['survey'] == "No")
{
header('Location: http://localhost/survey.php');
}
?>
For some reason or another I get an error within my if statement. That does not recognize 'survey' as a valid index. How Am I failing to do something to link my form to the php code?
Your warning is caused by the fact that when you load the page using GET (a normal request), $_POST['survey'] is not set.
You could change your conditions by adding a isset($_POST['survey'] ) && in front of every time you use it or you could put the whole code in a block that checks if a post was made like:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if ($_POST['survey'] == "Yes")
{
header('Location: http://localhost/survey.php');
}
else if ($_POST['survey'] == "No")
{
header('Location: http://localhost/survey.php');
}
}
else
{
// output html
}
Either way you would have to put this in front of your html as you cannot use header if the headers have already been sent (stuff has already been outputted to the browser).
Think about how forms work:
The first time you visit your page, the form is not submitted. Yet, your if/else is acting as though it were. That's what's causing the error - $_POST['survey'] doesn't exist the first time.
Write your scripts properly - do all potential form processing before rendering HTML:
<?php
if (isset($_POST['submit'])) {
// handle the form
}
?>
<!doctype html>
<html>
<head>
<title>Blah</title>
</head>
<body>
<!-- code -->
</body>
</html>
That will allow you to check if you've submitted the form to itself, and potentially use a header() to redirect the user without running into those pesky "Headers already sent" errors.
Try a simple print_r() statement to see if $_POST has any contents at all. Put this at the top of the page:
print_r($_POST);
Also, be sure that you're loading the results page via the form. If you just type the URL of the page it will not have any POST data sent with it.
The first time you load your file sample.php there is no POST data, therefore there's no index 'survey'.
You need to nest it in another if statement or modify it the following:
<form action="sample.php" method="post">
<input name="survey" type="radio" value="Yes" /> Yes
</br>
<input name="survey" type="radio" value="No" /> No
</form>
<?
if (isset($_POST) && $_POST['survey'] == "Yes")
{
header('Location: http://localhost/survey.php');
}
else if (isset($_POST) && $_POST['survey'] == "No")
{
header('Location: http://localhost/survey.php');
}
?>
I am using a different php file for the checking.
<html>
<body>
<form action="another.php" method="POST">
<label>You are: </label> Male <input type="radio" name="male"> Female <input type="radio" name="female"><br/><br/>
<input type="submit" name="submit" value="GO">
</body>
</html>
*****another.php******
<?php
if (isset($_POST['submit']))
{
if(empty($_POST['male']) && empty($_POST['female']))
{echo "select gender";}
elseif (empty($_POST['female'])) //means Male is checked
{
$gend="Male";
echo $gend;
}
elseif(empty($_POST['male'])) //Means Female is checked
{
$gend="Female";
echo $gend;
}
elseif(empty($_POST['male']) || empty($_POST['female'])== false) //Not required if you can disable one when another is checked
{echo"please select only one";}
}
?>
I try to login with one PHP file, without any HTML files. So when I'm successfully logged in I want to hide the HTML post button and the textboxes.
Here's my code..:
<?php
$showHTML = true;
if ($showHTML) { ?>
<h1> Bitte einloggen! </h1>
<form action="test2.php" method="POST">
<input name="user" type="test"><br>
<input name="pass" type="password"><br>
<input type="submit" value"Login">
</form>
<?php
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if ( $_POST['user'] == "test" && $_POST['pass'] == "a123" ) {
echo "user = test";
$showHTML = false;
}
}
Of course that doesn't hide the HTML code again, because its already executed I think.
Is there any way to hide the HTML output again?
Of course that doens´t hide the HTMLCode again, because its already executed I think.
Correct
Is there any way to hide the HTML output again?
Move the test so it appears before the HTML you (don't) want to output.
Short: put the HTML under the PHP.
Long: Use a decent login system. Use sessions.
You can't use a server side variable to control the already rendered html content.
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if ( $_POST['user'] == "test" && $_POST['pass'] == "a123" ) {
echo "user = test";
}
} else { ?>
<h1> Bitte einloggen! </h1>
<form action="test2.php" method="POST">
<input name="user" type="test"><br>
<input name="pass" type="password"><br>
<input type="submit" value"Login">
</form>
<?php } ?>