PHP simple maths quiz program - php

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.

Related

PHP Redirect from require_once

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..

PHP - Dont go to next page if input is wrong

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";
}

Checking if URL has been tampered with

I am trying to ensure the parameter from a GET method of page 2 (which displays the result) will not be changed by others in the URL (the variables behind the question mark) by making sure users clicked the submit button on page 1 (which contains the form).
The professor ask us to use isset() to implement this requirement
Here's the login page: (page1.php)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional ...> <html
xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Login
Page</title> </head>
<body>
<label>User ID:</label>
<input type="text" name="uid">
<br />
<input type="submit" value="SubmitCredentials" name="SubmitCredentials"/>
<br />
</form> </body> </html>
And this is the second page: (page2.php)
<?php
// get the data from the form
$uid = $_GET['uid'];
if(!isset($_GET['SubmitCredentials'])){
include('error.html');
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional
...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HELLO</title>
</head>
<body>
<label>Hello,</label>
<span><?php echo $uid; ?></span><br />
</body>
</html>
However, the if statement doesn't seem to be working. It's supposed to forward the page to error.html when I change the variable uid in the URL (e.g. when I change the URL to http://localhost/1/page2.php?uid=admin) but it's not. How can I fix it?
PS: a relevant tutorial I found on google>>>
http://www.homeandlearn.co.uk/php/php4p7.html
Try:
if(!isset($_GET['SubmitCredentials'])){
header('Location: error.html');
}
Isset is not safe on Arrays. Try comparing with the ===operator instead:
if(!($_GET['SubmitCredentials'] === 'SubmitCredentials')) {
include('error.html');
exit();
}
Page #1:
<form method="GET" action="...">
<input>
<input>
<input>
</form>
Submit URL:
http://localhost/1/page2.php?SubmitCredentials=SubmitCredentials&uid=admin&i_like_php=yes&...

header() function in php : No any redirection!

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.

Problem with PHP 'PHP_SELF'

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.

Categories