I have been working on a coding problem for some pages I inherited where the values of two variables are not showing up in the URL of the next page.
The code written by the author, which is probably quite old is
"completeyourorder.php?p=" . $p . "&service=" . $service;
as far as I can tell from my research there should be at least an echo in there
"completeyourorder.php?p=" echo . $p . "&service=" . $service;
or maybe I am missing much more than that.
I'd be grateful for a bit of education on this as I am a newbie and have not been able to find an answer despite many hours of tickering and reading.
Thanks
UPDATE:
PAGE 1
<form action="send-order.php" method="post">
<p>Name<br /><input name="clientname" value="<?echo $clientname;?>" type="text" style="width: 350px;" /></p>
<p><br /><input type="hidden" name="service" value="<?
echo $_GET['service'];
?>" />
<input type="hidden" name="p" value="<?
echo $_GET['p'];
?>"
/>
<input type="submit" value="Order now" /></p>
</form>
PAGE 2
$go = "completeyourorder.php?p=" . $p . "&service=" . $service;
return header("location:$go");
Let me know if you need anything more
SOLVED:
Brilliant thanks it works! I see now that my error was assuming that I could use the variable values in the location: completeyourorder..... on page 2 without having used $_POST earlier in the code on the same page. Thanks to everyone!
What you have shown here is just building part of a string. In php the period is the concatenation operator so it ties two strings together. You need an echo, print, header, or variable assignment on the whole string to make it do something. In that other script then you could get at the variables as
$p = $_REQUEST['p'];
$service = $_REQUEST['service'];
EDIT: upon seeing the update what it is doing is using the header to redirect the script to a new page
You recently asked a similar question regarding $_GET vars.
In this case, it looks like you're building a string to echo out in a link or something. So perhaps this is the what you may be experiencing: (only an example)
<?php
if(isset($_GET['p']))
{
$p = $_GET['p'];
}
if(isset($_GET['service']))
{
$service = $_GET['service'];
}
//defaults in case they are not set
$p or $p = 1; //assuming p = page
$service or $service = 'laundry'; //since I don't know what service refers to
$link = "completeyourorder.php?p=" . $p . "&service=" . $service;
?>
string to click on
Where in this example you can see that you are expecting to build the $link var based on the $_GET vars "p" and "service" and if they do not exist, default to the standard set of page 1 and service of "laundry"
Obviously you would tailor this to fit your needs, but you will need to provide more info for a better, more relevant answer.
EDIT
As per your edit, the basic answer is that your form should be populating the vars for $p and $service, so the revised code would be like this:
<?php
if(isset($_POST['p']) && isset($_POST['service']))
{
$p = $_POST['p'];
$service = $_POST['service'];
// do some kind of post processing here
// possibly do some kind of filtering to ensure the post vars are sanitized
header("location: completeyourorder.php?p=" . $p . "&service=" . $service);
exit;
}
?>
isset is not necessary on both, but you can change that to reflect your preferred choice for verifying post data. Some just do:
if(!empty($_POST))
Related
I've got a search function written in PHP/MySQL which works fine. What I want to happen is that when a user produces a search they can click a button which will submit the $id from the output to a table in my database.
I've copied my code below, the error is within the php echo in the form, it just displays the plain text of the php code.
Everything else works fine, I've tested this by setting value to "" and entering the id myself and then it works. I want it though to be a hidden input in future where the id automatically comes through from the search result. Multiple searches can be returned on the same page and this form is underneath each individual search result.
<?php
$conn = mysqli_connect("localhost","root","","users");
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$query = mysqli_query($conn, "SELECT * FROM users WHERE main LIKE '%".$search."%'") or die ("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = "There was no search results!";
}else{
while ($row = mysqli_fetch_array($query)) {
$id = $row ['id'];
$main = $row ['main'];
$postcode = $row ['postcode'];
$available = $row ['available'];
$email = $row ['email'];
$output .='<div><br><b>Player ID: </b>'.$id.'<br><b>Main:
</b>'.$main.'<br><b>Postcode: </b>'.$postcode.'<br><b>Available:
</b>'.$available.'<br>
<br>
<form action="request_player.php" action="post">
<input type="text" name="id" value="<?php echo $id ?>">
<input type="submit" value="Request Player">
</form>
</div>';
}
}
}
echo $output;
?>
<br> Back to your account
The issue Jay Blanchard highlighted and which you took a bit lightly - perhaps b/c you fear the distraction from your current problem - is actually pretty related to the issue you highlight in your question.
This btw. is nothing uncommon. In this little script you deal with at three languages: HTML, SQL and PHP. And all these are intermixed. It can happen that things jumble.
There are methods to prevent these little mistakes. What Jay highlighted was about how to encode a SQL query correctly.
The other problem is to encode a HTML string correctly. Let me highlight the part:
$output = '... <input type="text" name="id" value="<?php echo $id ?>"> ...';
In this PHP string you write "<?php echo $id ?>" verbatim, that means, this will echo'ed out then.
What you most likely meant was to write it this way:
$output = '... <input type="text" name="id" value="' . $id . '"> ...';
So this seems easy to fix. However, it's important that whether it is SQL or HTML, you need to properly encode the values if you want to use them as SQL or HTML. In the HTML case, you must ensure that the ID is properly encoded as a HTML attribute value. In PHP there is a handy function for that:
$output = '... <input type="text" name="id" value="' . htmlspecialchars($id) . '"> ...';
Or as the ID is numeric:
$output = '... <input type="text" name="id" value="' . intval($id) . '"> ...';
works similarly well.
You need to treat all user-data, that is all input - which includes what you get back from the database (!) - needs to be treated when you pass it into a different language, be it HTML, SQL or Javascript.
For the SQL Jay has linked you a good resource, for the HTML I don't have a good one at hand but it requires your own thoughtfulness and the will to learn about what you do (write) there. So sharpen your senses and imagine for each operation what happens there and how this all belongs together.
One way to keep things more apart and therefore help to concentrate on the job is to first collect all the data you want to output and then process these variables in a template for the output. That would prevent you to create large strings only to echo them later. PHP echoes automatically and a benefit of PHP is that you can use it easily for templating.
Another way is to first process the form input - again into your own variable structure - which is the programs input part and run first. Then follows the processing of the input data, in your case running and processing the database query. And after that you care about the presentation. That way you have common steps you can become more fluent in.
I hope this is understandable. It's full of further obstacles, but it pays to divide and conquer these programming problems. It will also help you to write more while you need to write less for that.
And btw., you don't need to switch to PDO, you can stick with Mysqli.
The reason it is happening is because you have put <?php echo $id ?> inside a string. You want to do the same thing you did elsewhere in your example: value="' . $id . '" It can quickly get confusing when you have single and double quotes happening together. You might be best off learning how to use PHPs multiline strings.
Also, <?= $id ?> is a useful shorthand for <?php echo $id ?> (although you don't want to use either here)
Status:
Apprentice.
My PHP knowledge:
Beginner level.
What I am trying to achieve with my PHP code:
Update the health bar input when ever the user clicks on the submit button.
<form>
<input type="submit" value="Attack">
</form>
So if the condition is true and the post has been done then I want to subtract 25 from the variable health which is then equal to another variable named input.
The problem:
I cant figure out why the health is not updating and how to save the updated value even if the user refreshes and then substracting 25 with the updated health everytime the user clicks on "attack".
What I tried:
Apart from doing some PHP research about Session_start() im not sure how to use it in this context. Im not even entirely sure why my conditional is faulty. I get no error messages what so ever but when I remove my if statement and echo the my bar variable then it doesnt work either as I dont get any number at all, which of course makes me suspect that my math is not working.
<?php
$health = 100;
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
if (isset($_POST['submit'])) {
$health - 25 == $input;
echo $bar;
}
?>
Question:
Why does'nt my value of health / input update? How can I save the session and substract from the new variable the next time an attack is made?
Your PHP is stateless so it has no record of what health was - it's simply reset to 100 every time.
You need to either use sessions, or simply pass back in the value of health each time:
<?php
$health = (isset($_REQUEST['health']) ? (int) $_REQUEST['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
<input type="hidden" name="health" value="<?php echo $health; ?>">
</form>
A couple of other points:
1) I'm not sure what the significance of $input is
2) You should really include a method in your form tag of either get or post - in the PHP I've used I have referenced $_REQUEST which features the values of both $_GET and $_POST
3) Notice I cast the value of $_REQUEST['health'] to an integer because this is output in the hidden HTML field and this helps to avoid XSS exploits.
If you want the health variable to carry over on to other pages or scripts then you might prefer to use a session. Revised code as follows:
<?php
session_start();
$health = (isset($_SESSION['health']) ? $_SESSION['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
$_SESSION['health'] = $health;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
</form>
One final comment is that using the session method a user cannot tamper with their own health score. Whereas using the hidden input method the user could potentially change the value of the field and tamper with their health score if they had the technical know-how.
change the form to the form below -
<form action='' method='POST'>
<input type="submit" name='submit1' value="Attack">
</form>
Then you can do -
if (isset($_POST['submit1']))
{
echo "button was pressed";
/// do other stuff.....
}
Define your form like:
<form method="POST">
That might do the trick. And you might need an hidden input field for the current health.
Firstly, forms default to a GET method if omitted.
Therefore, you need to specify it in your form tag
method="post"
Then your conditional statement will fail, since the submit input doesn't have the name attribute.
Add name="submit" to it.
Then this $health - 25 == $input; that doesn't make any sense and I don't know what you're trying to do here.
As stated in another answer by Mr Carrot, you'd want to use $health = $health - 25;
I'll let you look through the answers given, but this gives you a good indication as to what's going on.
Using error reporting would have signaled notices.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
I'm trying to make a simple captcha in PHP, but it does not work. The query is not currently executing. This is my current code:
<?php
$Random = rand(1, 100);
$Random2 = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
<input type="text" name="r_input"/><br />
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $Random+$Random2;
if(isset($_POST['myButton']) and trim($Var) and trim($Var2) and trim($Var3) and $Cap==$Result){
//My Query
}
When you use rand() to generate 2 values, and show those 2 values, and give the form for the user to enter the answer, ...
... the user enters the answer and submits back to the server ...
... the server gets the answer, and then GENERATES 2 NEW VALUES, that don't correspond to the answer given by the user.
Try using session variables to store the generated values in, and match against when the user submits the form!
<?php
session_start();
$captcha_id = 'captcha_' . rand();
$_SESSION['$captcha_id']['val1'] = rand(1,1000);
$_SESSION['$captcha_id']['val2'] = rand(1,1000);
echo "
<form action='' method='post'>
<p>Result: {$_SESSION['$captcha_id']['val1']} + {$_SESSION['$captcha_id']['val2']} = </p>
<input type='hidden' name='captcha_id' value='{$captcha_id}' />
<input type='text' name='captcha_answer' />
<p>?</p>
</form>
";
if (
isset($_POST['captcha_id'])
&& isset($_SESSION[$_POST['captcha_id']])
&& isset($_POST['captcha_answer'])
&& $_SESSION[$_POST['captcha_id']]['val1'] + $_SESSION[$_POST['captcha_id']]['val2'] == intval($_POST['captcha_answer'])
) {
unset($_SESSION[$_POST['captcha_id']]); // don't let this answer be reused anymore.
// do allowed stuff
}
?>
Because $Random and $Random2 have a different value each time.
When you show the form for the first time, they may have the values $Random = 12 and $Random2 = 26. The User sees those, adds them up correctly and types in 38 (which is the correct answer for those two values). The answer is sent to the script again, the values of $Random and $Random2 are generated again (this time as $Random = 23 and $Random2 = 30 which equals 53) and the answer the user has sent is not correct any more.
So you would need to store those values in hidden fields and add these up, instead of the generated ones, like so:
<input type="hidden" name="rand_1" value="<?php echo $Random; ?>">
<input type="hidden" name="rand_2" value="<?php echo $Random2; ?>">
<?php
if ($_POST['rand_1'] + $_POST['rand_2'] == $_POST['r_input']) {
// Query etc.
EDIT: As suggested by #nl-x you should use the Session variables instead of hidden fields to prevent abuse of the captcha:
<?php
$Random = $_SESSION['rand_1'] = rand(1, 100);
$Random2 = $_SESSION['rand_2'] = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
And check those values against the given result afterwards:
<?php
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $_SESSION['rand_1'] + $_SESSION['rand_2'];
if ($Result == $Cap) {
// ...
You never re-enter PHP mode after you output your form field:
<input type="text" name="r_input"/><br />
<?php // <----this is missing
$Cap = mysql_real_escape_string($_POST['r_input']);
Pardon me, but you are not making a real captcha. The purpose of the captcha is to distinguish the human from the bots. I would highly suggest you to pick a image database, and randomize a function to call a image. Internally, i would check if the text/description of the image matches with what the user typed.
The only thing you will rand() is what image to load from your image database.
That's a not-healthy way to do it, and there are plenty of better ways to do this. But it's more closer to a captcha than just your current code.
There is also a lot of libraries and engines that can do the job for you.
I'm not a pro at PHP, or even programming at all, but i think you're going to the wrong side - your code won't block any... malicious actions at all, or whatever kind of action that you will try to prevent with the captcha.
Search google for the libraries. PhpCaptcha is one of them. And here is a very simple quickstart guide for phpcaptcha.
Here's a code example, extracted from PHPCaptch that I linked above.
At the desired position in your form, add the following code to display the CAPTCHA image:
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
Next, add the following HTML code to create a text input box:
<input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
On the very first line of the form processor, add the following code:
<?php session_start(); ?>
The following php code should be integrated into the script that processes your form and should be placed where error checking is done. It is recommended to place it after any error checking and only attempt to validate the captha code if no other form errors occured. It should also be within tags.
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage source code and creates a new Securimage object that is responsible for creating, managing and validating captcha codes.
Next we will check to see if the code typed by the user was entered correctly.
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
Following the directions above should get Securimage working with minimal effort.
This code is included here as well.
Good luck!
I can't for the life of me find a form that doesn't email the results that you submit.
I'm looking to find a form that I can have users enter simple data that i can then spit back out at them in different arrangements. If they submit First and Last, I'll spit out, amongst other things, FirstLast#domain.com. I'm willing to scrounge the code manually to do this, but I cant find a simple form that would allow me to do this.
Edit: PHP or similar simple languages. I've never touched .NET before.
Form:
<form action="process.php" method="post">
First: <input type="text" name="first" />
Last: <input type="text" name="last" />
<input type="submit" />
</form>
Next page:
<?php
$first = $_POST['first'];
$last = $_POST['last']
echo $first . "." . $last . "#domain.com";
?>
See http://www.w3schools.com/php/php_forms.asp for more examples and explanation
Regardless of how you get it, always remember to never trust user input.
<?php
$sfirst = htmlentities($_POST['first']);
$slast = htmlentities($_POST['last']);
echo $first . "." . $last . "#domain.com";
?>
Also, running a validator on the final result may be helpful. But please don't write your own email address validator.
What language/platform/environment are you working in?
I guess you might be looking for a hosted script or webform (the way that people will host web-to-mail scripts I suppose) but I doubt there would be one out there that does this.
But if you have a specific framework to work in, e.g. PHP or .net, please update the question and let us know which.
Thing that simple doens't even need server-side support.
<form onsubmit="magic(this);return false">
<p><label>First <input name=first/></label>
<p><label>Last <input name=last/></label>
<input type="submit">
<div id="output"></div>
</form>
<script type="text/javascript">
var output = document.getElementById('output');
function toHTML(text)
{
return text.replace(/</g,'<');
}
function magic(form)
{
output.innerHTML = toHTML(form.first.value + form.last.value) + '#domain.com';
}
</script>
If I get your question right, sounds like this might do what you need..
Note: This PHP code doesn't require any knowledge of the fields in the form that submits to it, it just loops through all of the fields, including multiple-choice fields (like checkboxes), and spits out their values.
<?php
// loop through every form field
while( list( $field, $value ) = each( $_POST )) {
// display values
if( is_array( $value )) {
// if checkbox (or other multiple value fields)
while( list( $arrayField, $arrayValue ) = each( $value ) {
echo "<p>" . $arrayValue . "</p>\n";
}
} else {
echo "<p>" . $value . "</p>\n";
}
}
?>
how can I post back the data that are already in the text field?
example:
if I miss one of the required field an error will prompt when i click the submit button.
How can I make an post back data in that form using php or javascript and make the cursor of the mouse directly located to the field that caused an error?
There is no automated ways in PHP to write back the informations of the fields so you just have to echo it back.
Let's say you've got a "username" field ( <input type="text" name="username" /> ) you just need to add this:
value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>"
or if you like more:
value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>"
changed "" to ''
This sounds like basic form validation. I would recommend reading some of these tutorials or looking for some pre-built PHP form validation mechanisms.
Form validation using PHP
PHP/CSS Form validation
PHP Form Validation
Some frameworks such as CodeIgniter will do this for you if you use their own libraries. It's worth checking out such a framework as they provide a lot of other benefits. Of course it's not always possible to transfer an existing application but it's still useful to bear in mind for the future.
If I understand this correctly you want to keep whatever data the user has already entered, tell him what he did wrong and preferably focus on the bad field.
If so then here's a very basic example using a form with two fields where both need to be filled in to proceed.
<?php
$field1=$_POST['field1'];
$field2=$_POST['field2'];
$badField="";
if($_POST['form_action']=="submitted") {
//Check incoming data
if(empty($field1)) {
$badField="field1";
echo 'field1 is empty<br>';
}
elseif(empty($field2)) {
$badField="field2";
echo 'field2 is empty<br>';
}
else { //Everything ok - move to next page
header('Location: <next page>');
}
}
echo '<form name="mybo" action="' . $_SERVER['PHP_SELF'] . '" method="POST">
<input type="text" name="field1" value="' . $field1 . '"><br>
<input type="text" name="field2" value="' . $field2 . '"><br>
<input type="submit" name="Submit" value=" Enter ">
<input type="hidden" name="form_action" value="submitted">
</form>';
//Focus on empty field
if(!empty($badField)) {
echo '<SCRIPT language="JavaScript">
document.mybo.' . $badField . '.focus(); </SCRIPT>';
}
?>
I think the Moav's answer is "philosophically" correct however if you want do that you can:
1) pass via GET or POST the text control id;
2) on the server check that error condition;
3) fill an hidden input field with that value on the page returns
4) if error that with JS you can do:
window.onload = init; // init stuff here
function init()
{
checkForError();
}
function checkForError()
{
var h = document.getElementById("error_field");
var v = h.value;
if(v)
document.getElementById(v).focus();
}
However, if you will do that for every error field there will be a post and this is
by a user perspective very boring...so it is better to adopt other approaches...
I would take a different approach:
Validation should be in JS, and as such you never loose data, as you don't submit.
Any wrong data that was submitted and caught on the server is due to someone trying to pass over your JS validation, which means he has criminal thoughts, usually.