I am trying to change the page when the user hits the login button. When the login button is hit currently the page just refreshed the user is not redirected to the new page. I created the session before any of the code for the page. I am wondering if it has to do with the location of my header command.
<?php
session_start();
?>
<!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>
<title>Login</title>
</head>
<body>
<form action="" method="post">
<br>Name: <input type="text" name="NameTextBox"><br>
<br>What grade are you currently in?: <input type="number" name="GradeTextBox"><br>
<br><button name="Login" type="submit">Login</button></br>
</form>
<?php
if (isset($_POST["Login"])) {
$_SESSION["start"] = $_SERVER['REQUEST_TIME'];
//echo "This session is beginning at ".$_SESSION["start"]."<br /><br />";
}
if(isset($_POST["Login"])){
if($NameTextBox = "Phydeaux"){
//echo"Good Name!";
PassLogin();
}
elseif($NameTextBox = "Rover"){
//echo"Good Name!";
PassLogin();
}
elseif($NameTextBox = "Spot"){
//echo"Good Name!";
PassLogin();
}
else{
echo"You cannot login!";
}
}
function PassLogin()
{
//print '<script type="text/javascript">';
//print 'alert("Running PassLogin Function")';
//print '</script>';
$_SESSION["ReadingGrade"] = "Fail";
$_SESSION["WritingGrade"] = "Fail";
$_SESSION["MathGrade"] = "Fail";
$_SESSION["Grade"] = $GradeTextBox;
$_SESSION["Name"] = $NameTextBox;
Header('Location: Reading.php');
}
if (isset($_POST["Login"])){
//echo "Login has been pressed";
}
?>
</body>
</html>
There are several synthax and technical problems with this code. In addition to what AlexP said, you must observe that you cannot send the headers when you have already sent some output. The headers must be sent before any output, what is the same reason you had to put your session_start() in the beginning.
That being said, you should also make the login script before the HTML part, where your session_start() is, so your redirect header to Reading.php can work too. Or you can workaround that by placing a ob_start() in the beginning of the page, it will buffer the output preventing it from being sent before the script ends, this way you can call a header() wherever you like.
And talking about the header, the function is header(), not Header(). There is no native function named Header() in PHP. Function names are case sensitive.
In addition, you shouldn't use action="" in your <form>. Just suppress this attribute to make it post to the same page, it will make your code work don't matter what your php file name is. If you use action="" it will post to the index.php instead of login.php.
I also noticed you are using Reading.php (with capital letter) and login.php. I suggest you normalize all your file names to lower case, because if not you can have problems when porting this code to other systems. To Windows, Reading, reading, READING and ReAdInG are the same thing, to Linux it is not.
You cannot modify the header information having already output your HTML. Move your HTML underneath the PHP header call.
The documentation says:
header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
Also, you are assigning the string value when you use $NameTextBox = "Phydeaux", rather than conditionally checking it.
You should use the == double equals instead
if(isset($_POST["Login"])){
$NameTextBox = $_POST['NameTextBox']; // $NameTextBox is now the posted value
if($NameTextBox == "Phydeaux"){ // double equals checks the value of the variable
<form action="" method="post">
Where will go your posts?
I will offer you this:
1- Write your PHP codes another page and named is "login.php"
2- Write your form action: <form action="login.php" method="post">
Related
i am facing a problem using the php header() function. I am trying to redirect to another page after form submission. The main thing is, that it works fine on my local XAMPP server, but not on my web server hosted by strato..
I have already searched the web for solutions but not a single one applies to my problem. So there is no whitespace before my php tag, i do not ouput anything before i call the header function and there is also nothing included that can cause any problems. I've also tried to use absolute pathes to state the page i would like to redirect to. No result..
Here is the whole content of my file redirect.php
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
if (isset($_POST["submit"])) {
// redirect
header("Location: register.php"); exit;
//echo "<script language='javascript'>window.location.href='register.php';</script>";
}
?>
<!doctype html>
<html>
<head>
<title>Redirect</title>
</head>
<body>
<form action="redirect.php" method="post">
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
There is no error output on the page, instead it will stay completly blank after form submission..
The redirection via javascript is working, but is just a workaround since it will not work if javascript is disabled.. But it shows that the if-statement will be reached!
Any suggestions?
I have Opera 12.15 on XP with cookies enabled running on XAMPP and localhost. There is no .htaccess.
1) I can't understand why the following session variable does not persist in Opera whilst it does in the other mainstream browsers. With Opera only, if you revisit the page (via a link) after the Form has been accepted, the session variable has gone and the Form is displayed again. It's okay (i.e. the variable persists) if I just refresh the page.
2) I also have a secondary question, as you can see below I have opened a php tag and started an 'if' statement, then closed the php tag, entered some html, opened a new php tag, closed the 'if' and finally closed the second php tag. Is this valid code, I was originally taught to echo the html within the 'if' and just have one set of php tags? The former is easier and works, I saw it used elsewhere.
Thanks in advance.
<?php
// Turn on error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Opera Session Variable</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
// create a test variable to confirm other session variables outside of Form are persisting
$_SESSION['test'] = 'Test';
// function to print session variables
function print_array( $_SESSION )
{
echo '<pre>$_SESSION<br />' . "\n";
print_r($_SESSION);
echo "</pre>\n";
}
// process the submitted form
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if (isset($_POST['formaccept'])) {
$_SESSION['formaccepted'] = $_POST['formaccept'];
}
}
// print the session variables
print_array( $_SESSION );
// only display the form if it has not previously been accepted in this session
if (!isset($_SESSION['formaccepted'])) {
?>
<p><b>This parargraph should only display if the form has not been accepted in the current session.</b></p>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="formaccept" value="Accept" />
</form>
<?php
}
?>
</body>
</html>
Must be the way opera handles the cache, I can't see any error with your code.
As for your second question, that syntax works but is not usually recommended, since it makes the layout dirty being full of snippets.
I have a page with simple form. when I click on Submit button, i have some sql codes and at the end I need to redirect page to another page(contact.php).My sql codes are working fine and it stores in database, however it does not redirect to another page(to index.php) and shows the same page which has form(contact.php).
I use the following code to redirect my page:
header('Location: index.php');
my form and php codes are as below:
<form name="contact" action="contact.php" id="contact_form" method="post" >
<input type="hidden" id="ID" name="ID" value="<?php echo $yid ?>" />
<textarea id="Reason" name="Remark" placeholder="Write your Reason here" class="required" cols="10" rows="10"></textarea>
<input class="button altbutton" type="submit" name="submit" value="submit" />
</form>
if (isset($_POST['submit'])) {
$Remark = #$_POST ['Remark'];
$ID= #$_POST ['ID'];
$query=" my sql code";
$result = mysql_query($query);
header('Location: index.php');
}
what should I do?or what I have missed? Thank you
I'd imagine it's cause you have put it after output on the page, but without seeing your code this is just a stab in the dark.
To redirect to a new page you should use:
header("Location: index.php");
exit();
Also, make sure the above is placed before any output on the page, otherwise it won't work.
Doing the above, if you get an empty page, something has went wrong (check your error log or make sure error reporting is turned on).
is there some html sent before the header? even whitespace?
also try this (from here)
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
if(isset($your_set_values)
{
header("Location:index.php");
}
if it doest seem to work :-
First try to find is there any error ?
using --
error_reporting(E_ALL & ~E_NOTICE);
if you didn't found any error .... try to print your query and what..
The HTTP header "Location" don't seem to work properly always on all browsers (as per my experience). And if you have already 'echo'-ed some HTML (or text, whatever) before echoing the 'Location' header, the PHP function 'header' won't work.
Use this code:
<?php
$Js_Redirect =
"<script>"+
"top.location = 'index.php';"+
"</script>";
echo $Js_Redirect;
exit();
?>
instead of
<?php
header('Location: index.php');
?>
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. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
?>
[reference]
Solution 1: In your file, move the PHP code to the begining (i.e. above <html> tag), and also do not echo anything before using header() function.
Solution2:
If you're having trouble to refactor your code, then you need to use Output buffering. Put ob_start() as the very first line of your php page, and use ob_end_flush() or ob_end_clean() after use of the header(). This effectively buffers all output, which allows you to call the header function before any output is actually printed.
Note: remember to always exit or die() after setting a Location header.
I basically have:
<form action="index.php" method="post">
<input name="text" type="text" value="Insert text here" size="20"/>
<input name="submit" type="submit" value="Submit" />
</form>
My PHP code then checks if submit is pressed:
if(isset($_POST['submit'])) {
$newDbValue = $_POST['text'];
$sql = ("
UPDATE `pseudo_tableName`
SET TEXT = '".$newDbValue."'
WHERE name = 'pseudo_fieldName' LIMIT 1
");
//SQL-query run by php function in separate class.
}
And as I understand it, if the form data is submitted it sends the user back to index.php?
But what mine does is it fails to update with new values and sends me back to index.php as if there was nothing wrong!
If I leave action="<?php $PHP_SELF; ?>" or action="" in the form, it updates when I reload the page (not F5 - click in address-line and hit enter).
What I want this to be:
I hit submit, and it updates the DB, sends me to index.php.
How can this be achieved?
Remove action="" (making you reload the page and using same file you have you if in) in your form and change your if to this:
if(isset($_POST['submit'])) {
$newDbValue = $_POST['text'];
$sql = ("
UPDATE `pseudo_tableName`
SET TEXT = '".$newDbValue."'
WHERE name = 'pseudo_fieldName' LIMIT 1
");
header("Location: index.php");
exit;
}
All <form> elements require the action attribute. What you're describing probably means your PHP script isn't detecting the form data and thus isn't making the necessary changes to your MySQL database. The reasons behind this may depend on the browser you're using; to my understanding, if you press Enter (keyboard) the submit button value isn't included in the form (this is said to allow multiple submit buttons with different value and perform the correct function).
If I were you, I'd check for the actual text input in the form, not the button.
<?php
// check 'text' exists and make sure it isn't blank.
if(isset($_POST['text']) && $_POST['text']!='') {
// do MySQL updating here.
header("Location: index.php"); // send back to index.php after updating.
}
?>
Because the most efficient method to redirect is to use header(); you're required to write your PHP form-checking script before the HTML form (because headers can't be send half-way through the actual document) so maybe at the top of the page before sending the HTML, additionally that way you can control what HTML is sent based on the processed data.
Have you tried setting:
<?php
if (isset($_POST['text']) AND !empty($_POST['text'])) {
// ...
}
?>
Instead of the other input?
The action='index.php' will send you back to index.php, so be sure that your PHP is above the form (and your HTML, for that matter). I also gues that you have set up your mysql_connect and you mysql_query functions.
Do you have error_reporting in php.ini on? What does the MySQL query result set say when you var_dump() the variable?
<?php
$sql = mysql_query($newDbValue));
var_dump($sql);
?>
That could really help you out.
The "cannot send header information - headers alredy sent" is because you have characters sent to the browser before the redirect() function - nothing can be sent to the browser (even whitespace!) if you're gonna use that, so be sure that the first thing in the document is your ?> tag, and your file encoding is UTF-8, not UTF-16 BOM or something crazy like that.
<?php
(E_ALL & ~E_NOTICE);
session_start();
// is the one accessing this page logged in or not?
if (!isset($_SESSION['db_is_logged_in']) || $_SESSION['db_is_logged_in'] !== true) {
// not logged in, move to login page
header('Location: login.php');
exit;
}
else {
echo "Welcome To The Test Page:";
echo $_SESSION['logname'];
}
if (isset($_POST['submit'])) {
test();
}
function test()
{
$var = rand(1, 5);
header("Location:{$var}.html");
exit;
}
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="submit" value="Take Test">
</form>
</body>
</html>
When the "take test " button is clicked i need 1 of the 5 html pages i.e (Question papers in this case ) to be displayed to the user.
for that i have created the random number from 1 to 5.
The pages have been names 1.html , 2.html and so on...
Could anyone debug this code ??
Other comments have addressed two problems: output before changing headers, and the invalid formatting around the quotes.
Another problem is that $_POST['submit'] is never specified from the HTML. You have:
<input type="submit" value="Take Test" />
But nowhere is a name for the field specified. This should read:
<input type="submit" name="submit" value="Take Test" />
You have extra quotes in
header('"Location:".$var.".html"');
It should be
header('Location:'.$var.'.html');
or if you prefer double quotes as mentioned in the comment to this answer you can use the php double quote variable interpolation:
header("Location: {$var}.html");
The string your would set the header to would be:
"Location:".$var.".html"
instead of what you actually wanted
You need to exit; after you send Location header. Otherwise the redirect will not happen.
header("Location:".$var.".html");
exit;
You can't call header() after your wrote something in your page.
Here, when you're successfully logged on, you echo a message and then try to change the header. But it's too late.
From the php doc :
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. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
If you want instead to include some page content, then include it, don't change the Location in the header.
Plus, as others pointed out, your string for the header is wrong, "Location:".$var.".html" will be enough.
It appears you declared test function after the call, so you must it's better practice to move it before the call, I would put it before session_start();
You also have to avoid output, in order to get header to do what you want. You can do this by putting an exit(); after the header instruction.
Also you have extra quotes as GWW said in his answer.
Update
Well, I didn't notice this before, in PHP you can call functions before the declaration, although this is currently confusing me a little.
You can check if form is sent by
if($_SERVER['REQUEST_METHOD'] == 'POST') {
test();
}
try pointing the form to the page manually instead of using the server var.
from
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
to
<form action="test.php" method="post">
or even
<form action="<? echo $_SERVER['PHP_SELF'];?>" method="post">