I'm working with a .html and a .php. In the default.html the user must enter some info and when the button is clicked the html does a post to the default2.php.
In default2.php the data is checked and if it's correct it redirects the user to another page. The problem I'm having is when the data entered is wrong.
I'm having two issues here:
When the data is wrong I'm redirecting the user to the default.html, because if I don't do that, it will stay in default2.php and default2.php has nothing important for the user to see. I don't know if this is the best way to do this.
When the data entered is wrong, I want an echo message to the user in default.html. But I don't know how to trigger this from default2.php.
How can I solve these two issues?
Thanks...
default.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>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP4</title>
<style type="text/css">
body {
background-color: #CCC;
}
</style>
</head>
<body>
<p> </p>
<form id="form1" name="form1" method="post" action="default2.php">
<p>
<label for="textfield1">User Name</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield2">Password</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="button1" id="button1" value="Submit" />
<br />
<br />
<label id="label1">
</label></p>
<p> </p>
</form>
<p> </p>
</body>
</html>
default2.php:
<?php
require 'connection.php';
if (isset($_POST['button1'])) {
$username_v = $_POST['username'];
$password_v = $_POST['password'];
// Then you can prepare a statement and execute it.
$stmt = $dbh->prepare("CALL login(?, ?)");
$stmt->bindParam(1, $username_v, PDO::PARAM_STR);
$stmt->bindParam(2, $password_v, PDO::PARAM_STR);
// call the stored procedure
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
}
else
{
header("Location: default.html");
}
}
?>
Just add some parameter to
header("Location: default.html?test=failed");
And in html use Javascript to display something sensible when variable test is set to failed. You can find a tutorial how to get value of url parameter with javascript here.
Hope that helps.
Other than that you can use PHP in your default.html and perhaps even AJAX request to do validation without leaving the page and highlighting validation errors.
Personally, I don't like to expose states like "error" and "invalid" to the user using a query string. In this situation, I would merge the two files in one single PHP file, with the PHP code at the top and the HTML code at the bottom.
The if statement in the PHP code would be:
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
exit;
}
else
{
$error = true;
}
And down in the HTML where you want to display the message:
<?php
if( isset( $error ) && $error )
echo 'You have entered the wrong data!';
?>
Ofcourse, in the form element, you would have to remove action="default2.php".
If you prefer separating the logic and the markup, you could change default.html to for example template.php and include it at the end of your controller php file.
I just don't like the idea of an extra page without any content that only acts as a redirector.
If you made default.html a PHP file, you could pass a variable via the URL, this would then allow you check if this variable has been passed using $_GET[]and show the user a message.
So for example, if you forwarded the user to
default.php?error=1
On the default page, you could have a segment of code such as
if (isset($_GET['error'])) {
echo "Show user a message here";
}
Related
At the moment i'm preventing a resubmit with a redirect header location. But I imagine that the page loads slower because it's a waste of time to go to one place just to be redirected to another. It adds one extra step to the process.
What other options do I have with PHP?
Is there a way maybe to send form data to another file/page on submit without getting "redirected" to that page as well? And is it possible to do that without the need for redirect, because you where never sent there from the beginning. Just passing on the "form data" to the other page.
Open to other solutions as well, as long it's PHP.
Take care
Use include to include the PHP in your other page it will process the form without a redirect.
include 'YourFile.php';
here is a structural example of this.
<?php
include 'functions/db.php';// your db connection to process the form
$error['last'] = '';
$error['first'] = '';
$error['user'] = '';
if(isset($_POST['addUser'])){ // Check if form is submitted
$LastImp = $_POST['LastImp'];
$FirstImp = $_POST['FirstImp'];
$UserImp = $_POST['UserImp'];
if($LastImp == '' || $FirstImp == '' || $UserImp == ''){// Check if inputs are empty.
if($streetImp == ''){$error['street'] = 'Must enter a Street';}
if($LastImp == ''){$error['last'] = 'Must enter a Last Name';}
if($FirstImp == ''){$error['first'] = 'Must enter a First Name';}
if($UserImp == ''){$error['user'] = 'Must enter a Username';}
$error['alert'] = "All Fields are Required.";
include 'views/employee_front.php';
exit();
} else {
//Process the Form.
}}
include 'YourFile.php';// the php reads this first because all the other code is conditional upon submit.
This is YourFile Page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Untitled 1</title>
<body>
<form method="post">
<div class="rowContainer">
<label class="User">Username</label>
<input class="Userimp" name="UserImp" type="text"></div>
<div class="error"><?php echo $error['user']; ?></div>
<div class="rowContainer">
<label class="First">First Name</label>
<input class="Firstimp" name="FirstImp" type="text"></div>
<div class="error"><?php echo $error['first']; ?></div>
<div class="rowContainer">
<label class="Last">Last Name</label>
<input class="Lastimp" name="LastImp" type="text"></div>
<div class="error"><?php echo $error['last']; ?></div>
<button class="addSubmitA" type="submit" name="addUser">Add User</button>
</form>
give the php file in action attribute of form tag <form method="POST" action="submit-data.php"> and in the submit-data.php,after successful data submission give header('Location:form.php') . It works fine for me without resubmission of data on browser reload. It is one way to prevent resubmission of data on page reload. Second way is use Ajax Jquery method to submit data.
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'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 have written a very very very simple!! script in php. header redirection not working.
1- encoding : UTF-8 without BOM
2- with adding ob_start() the problem is countiueing.
What is wrong in my code;
login.php:
<?php session_start();
require_once("funcs.php");
db_connection();
$username = $_POST['username'];
$password = $_POST['pwd'];
$submit = $_POST['login'];
if($submit){
if (!filled_out($_POST)) {
echo "please fill all fields";
}
else{
$query = "SELECT * FROM *** WHERE username ='{$username}' AND password ='{$password}'";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1){
$found_user = mysql_fetch_array($result);
$_SESSION['id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];
$_SESSION['password'] = $found_user['password'];
setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php");
}
else{
echo "incorrect username or password";
}
}
}
?>
<!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>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="username">
Username:
</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield">
Password
</label>
<input type="password" name="pwd" id="pwd" />
</p>
<p>
<input name="login" type="submit" id="login" value="Log in" />
</p>
</form>
</body>
</html>
<?php
db_disconnect();
?>
and tst.php:
<?php session_start();
require_once("funcs.php");
if (!isset($_SESSION['id'])){
header("Location : login.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table id="structure">
<tr>
<td id="navigation"> </td>
<td id="page"><?php echo "welcome"."". $_SESSION['username']; ?></td>
</tr>
</table>
</body>
</html>
wthit oppening tst.php directly, header() doesnot redirect to login.php
Try adding die():
header("Location: tst.php");
die();
You should always add a die() because a location header is just a request to the browser to change the page. If you don't die(), the rest of the page will still reach the browser, including possibly sensitive data the user is not meant to see.
Try removing the space after "Location":
header("Location: login.php");
Please heed my comment about formatting your code correctly as it's extremely difficult to spot anything else that may be amiss.
Check for white space before your opening <?php tags. It's hard to tell from your formatting here whether there is any, but the whitespace will be sent before your code executes, preventing headers. Also check for white space after any closing tags in included files. (better practice is to omit closing tags altogether)
old answer
You're using setcookie() which will send headers, then trying to redirect. You cannot redirect once headers have been sent. (sorry, this was incorrect)
I guess the redirect works, but you overwrite the Session-Cookie with an empty value. So the tst.php creates a new empty Session and redirects back to login.php.
Try:
// DELETE this line: setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php?".SID);
Importent: header+session always need SID for not loosing the session!
Corrected: Thanks to #Pekka.
header is not just a php function. It really modifies a part of http header, so it is impossible to have a part of header, then html data, then another header. To make it work, you should put your header at the beginning of the file, before any html output is done.
The redirection can take a relative or absolute URL. The problem is with the space BEFORE the colon. Try it like this:
header("Location: whatever.php");
As well as the other answers, the Location: header should contain an absolute URL, example header("Location: http://example.com/");
you need to put an exit() or die() after the header function - otherwise the rest of the script will continue to execute.
I am having a bit of trouble. It does not seem to be a big deal, but I have created a page that the user can edit a MySQL database. Once they click submit it should process the php within the if statement and echo 1 record updated. The problem is that it does not wait to echo the statement. It just seems to ignore the way I wrote my if and display the whole page. Can anyone see where I went wrong.
<!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></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php require("serverInfo.php"); ?>
<?php
$res = mysql_query("SELECT * FROM cardLists order by cardID") or die(mysql_error());
echo "<select name = 'Cards'>";
while($row=mysql_fetch_assoc($res)) {
echo "<option value=\"$row[cardID]\">$row[cardID]</option>";
}
echo "</select>";
?>
Amount to Add: <input type="text" name="Add" />
<input type="submit" />
</form>
<?php
if(isset($_POST['submit']));
{
require("serverInfo.php");
mysql_query("UPDATE `cardLists` SET `AmountLeft` = `AmountLeft` + ".mysql_real_escape_string($_POST['Add'])." WHERE `cardID` = '".mysql_real_escape_string($_POST['Cards'])."'");
mysql_close($link);
echo "1 record Updated";
}
?>
<br />
<input type="submit" name="main" id="main" value="Return To Main" />
</body>
</html>
if(isset($_POST['submit']));
1) Should not have a semicolon after it.
2) $_POST['submit'] is not set. You have to set a name on your submit button and give it a value. Just setting the type to 'submit' does not return a value for $_POST['submit'] in PHP.
You've got a ; after your if statement.
I noticed that you have two submit buttons and I assume that you are using the first one.
Try giving it a name="submit" and a value too.
Of course it doesnt. PHP runs in the server side, not in browser!
Open your page source. There is no PHP. Nothing to wait.
You need another page to send your form to.
And it is a big deal. It's a cornestone of understanding how the web does work.