Problem with PHP 'PHP_SELF' - php

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.

Related

How do I pass a session variable correctly?

I'm really new to PHP, and I'm trying to use the simple captcha mentioned in this question
Numeric Captcha for PHP
What I'm trying to do is pass the $_SESSION['captcha'] to my current page, so it can compare with the input I just entered which is supposed to pass by the "form".
Here's my code:
<?php
if(isset($_POST['captcha'] ,$_SESSION['captcha'])) {
if ($_POST['captcha'] == $_SESSION['captcha'])
echo 'YES, YOU DID IT';
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>captcha test</title>
</head>
<body>
<form name="input" action="index.php" method="POST">
<img src="captcha.php">
Enter the code above: <input type="text" name="captcha">
<input type="submit" value="Submit">
</form>
</body>
</html>
What's the correct way to do this? How can I implement the captcha in my current code?
A few things fixed here:
First you did not use a session_start() to actually retrieve $_SESSION values. Added here.
Next, you should check if the values are not empty by using !empty() in addition to isset(). Added here as well.
Finally, I recommend you use === comparison operator instead of ==. While == will check if values are the same, === will check if they are the same and the same data type.
Here is the cleaned up code:
<?php
session_start();
if (isset($_POST['captcha'], $_SESSION['captcha']) &&
!empty($_POST['captcha']) && !empty($_SESSION['captcha'])) {
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo 'YES, YOU DID IT';
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>captcha test</title>
</head>
<body>
<form name="input" action="index.php" method="POST">
<img src="captcha.php">
Enter the code above: <input type="text" name="captcha">
<input type="submit" value="Submit">
</form>
</body>
</html>
If this still does not work for you, you can dump the values of $_POST and $_SESSION like this to see what you are getting:
echo '<pre>';
print_r($_POST);
echo '</pre>';
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
You didn't add session_start() at the 1st line, thus the $_SESSION is empty.
Side Note:
You mixed up XHTML and HTML. xmlns is not required for HTML.
DOCTYPE is missing
You need to start your session with
session_start();
as a first call before your script has any output.
See documentation: http://php.net/manual/en/function.session-start.php

Passing session variables to more than 3 page and back in php

The first page (inputform1test.php)
<?php require_once('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Input (Test)</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="inputdisplaytest.php">
<p>Name
<input type="text" name="name" id="textfield" />
</p>
<p>Text
<input type="text" name="text" id="textfield2" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
Second page(inputdisplaytest.php)
To test if it's working in 2nd page(inputdisplaytest.php)
<?php include('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['name']= $_POST['name'];
$_SESSION['text']= $_POST['text'];
?>
<!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>Display Input (Test)</title>
</head>
<body>
<table width="200" border="0">
<tr>
<td><?php echo $_SESSION['name']?></td>
<td><?php echo $_SESSION['text']?></td>
</tr>
</table>
inputdisplaytest_2.php
</body>
</html>
Third page(inputdisplaytest2.php)
This is the part where I got the error
<?php include('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Display Input (Test)</title>
</head>
<body>
<table width="200" border="0">
<tr>
<td><?php echo $_SESSION['name']?></td>
<td><?php echo $_SESSION['text']?></td>
</tr>
</table>
<p>inputdisplaytest.php</p>
</body>
</html>
I clicked to see if it's still working on 2nd page. (Which is not working)
I got the undefinex index problem when I go to the hyperlink and "Document Expired" when I clicked back button via browser.
How do I get the session variables back/not expire?
Any help would be appreciated.
You don't need the
if (!isset($_SESSION)) {
session_start();
}
just use session_start() at the beggining of your script. Even before those includes.
You can't print anything before the session_start. Check your logs for errors.
I believe the reason you're finding this error is because you are POSTing the form data. When you POST the form data, it is sent when you hit Submit. Going back to the form will give you the message to reload the form data. If you change it to GET, your form data should stick.
Remove if statements that you're using to check if session is set, because in your case the session_start() is never being executed, since the $_SESSION array is always set by PHP unless you perform unset($_SESSION) which is deprecated, this will unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal array. So:
if(!isset($_SESSION)){
session_start();
}
becomes:
session_start();
this resolves the problem of undefined index error.
To resolve the browser back button error when navigating back to the page processing your form, you have to put:
session_cache_limiter('private_no_expire');
before session_start() on second.php file, this line of code avoid "Page Has Expired" warnings, you can find more explanation here avoid "Page Has Expired" warnings.
Finally, after session_start() on second.php file, add the following code:
if(isset($_POST['button'])){
$_SESSION['name']= $_POST['name'];
$_SESSION['text']= $_POST['text'];
}
to check if the form was submitted or not, if yes, you can process the data and display the page, else you just display the page using the perviously stored data on your session.
I have had issues with this myself, where the session variables are not passed on, and recently came across the answer. I am sorry that I cannot credit the person who answered this in a previous post because I cannot find the post again. Simply put, sometimes, especially on shared hosting, the sessions are not stored in the right place. You can fix this by forcing the sessions to be saved in a particular spot. My solution was:
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/session'));
My session file is in the domain's root folder.
I then start the session:
session_start();
And then I make sure that the person is signed in:
if(isset($_SESSION["your_variable"])) {
$your_variable = $_SESSION["your_variable"];
//add any other session variables in the same manner
//be sure to rename "your_variable" with the name of your variable
}else{
header('Location: signin.php');
exit;
}
The header redirect at the bottom is where the person is going if they are not signed in or the session variable is not found, so that the session variables are passed to this page. Note the exit, it keeps your code safer. So altogether my first lines of code are:
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . `'/session'));`
session_start();
if(isset($_SESSION["your_variable"])) {
$your_variable = $_SESSION["your_variable"];
}else{
header('Location: signin.php');// or wherever your sign in happens to be
exit;
}
I hope this helps.

PHP simple maths quiz program

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.

JavaScript enable button not working in php

I have used Javascript to enable or disable a button, depending on the input value. I'm new to PHP, so I don't know why this isn't working. Here's the PHP code:
<?php
session_start();
include_once('header.php');
include_once('functions.php');
$_SESSION['userid'] = 1;
?>
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Microblogging Application</title>
</head>
vbody>
<?php
if (isset($_SESSION['message'])){
echo "<b>". $_SESSION['message']."</b>";
unset($_SESSION['message']);
}
?>
<form method='post' action='add.php'>
<p>Your status:</p>
<textarea name='body' rows='5' cols='40' wrap=VIRTUAL></textarea>
<input type="text" name="age" />
<input type="text" name="poscode" />
<input type="submit" name="submit" value="Post" disabled="disabled"/>
</form>
<script type="text/javascript">
$('input[name="age"], input[name="poscode"]').change(function(){
if ($(this).val())
{
$("input[name='submit']").removeAttr('disabled');
}
});
</script>
<?php
$posts = show_posts($_SESSION['userid']);
if (count($posts)){
?>
<table border='1' cellspacing='0' cellpadding='5' width='500'>
<?php
foreach ($posts as $key => $list){
echo "<tr valign='top'>\n";
echo "<td>".$list['body'] ."<br/>\n";
echo "<small>".$list['stamp'] ."</small></td>\n";
echo "</tr>\n";
}
?>
</table>
<?php
}else{
?>
<p><b>You haven't posted anything yet!</b></p>
<?php
}
?>
</body>
</html>
How do I change it so when the value of the input = "foo", the button is now clickable.
Thanks in advance
-Ben
I can't make sense of your question, but if you're asking what I think you're asking (which is "how do I enable the button if the form is populated on page load?"), change your script to the following:
$.ready(function(){
$('input[name="age"], input[name="poscode"]').change(function(){
if ($(this).val())
{
$("input[name='submit']").removeAttr('disabled');
}
}).change();
});
I added the change call to trigger the change event handler, and wrapped it in jQuery's ready handler.
Try using the attr function like below
$('#element').attr('disabled', true);
Or
$('#element').attr('disabled', false);
Because different browsers treat the disbaled attribute differently, using true and false lets jquery handle the cross browser issues

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

Categories