<?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">
Related
This is my admin panel code:
<form action="connectdb.php" method="post">
<input type="text" name="name">
<input type="submit">
</form>
So, It so, the code in connectdb.php will only run, if the "submit" button redirects a user to it. It will not run, if a user directly open /connectdb.php page.
Do I need to start some session, something like that?
Note: I am a newbie, so please explain in detail.
Since your form is using method="post"you can place the following code at the very beginning of your connectdb.php file:
<?php
if (empty($_POST)){
exit;
}
//The rest of your code goes here
This checks to see if the $_POST variable either does not exist or does exist but is empty. If this returns true that means your form was not submitted and a user went to the page directly. The script will then exit and a blank screen will be displayed.
Instead of displaying a blank screen, you may instead want to redirect to a different page such as this:
<?php
if (empty($_POST)){
header("Location: index.html");
exit;
}
//The rest of your code goes here
Whenever you do a redirect like this, it is important to place an exit; statement directly after it, otherwise your script could still process some of the other statements and send data to the browser that shouldn't be sent. This of course could be a security risk in some cases. An exit statement prevents this kind of security risk.
Not sure if you really need it, but you can add a name attribute like the following:
<input name="submit_button" type="submit">
So when you click this button a $_POST['submit_button'] variable will be created on the PHP side, and then you can use it to check if the button was clicked:
if(isset($_POST['submit_button'])){
// your code
}
<input type="submit" name="submit_btn">
Now in your connectdb.php check,
<?php
if(isset($_POST['submit_btn']))
{
//do your code
}
else
{
//redirect to your home page
}
?>
I have used the following code for the redirect on URL, but It displaying error 500 error on the server(GoDaddy).
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="submit" class="checkout" name="btnCheckOut" value="PROCEED TO CHECKOUT" />
</form>
<?php
if(isset($_POST['btnCheckOut']))
{
if(isset($empty))
{
echo "<script>
alert('your cart has been empty plese insert some items');
</script>";
}
else
{
header("location:Billing.php");
}
}
?>
The header function must appear before anything is sent back to the browser.
See http://www.au2.php.net/manual/en/function.header.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.
This is most likely the issue (it is definitely a contributing factor, but it's hard to test if it's the only error.)
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">
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.