Im trying to make an online concert ticket system and this is my problem..
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= "<?php $action; ?>" method="post">
And it doesn't work. Thank you in advance!
heres the full codes for the particular file that has a problem.
<html>
<head>
<title>Ariana Grande Concert</title>
</head>
<body>
<br>
<table>
<tr>
<td><img src="ariana2.jpg" height="300" width="260"></td>
<td></td><td></td><td></td>
<td>
<h2>ARIANA GRANDE THE HONEYMOON TOUR</h2><br>
<font face="Lucida Sans Unicode"> March 11, 2017<br>
Grand Ballroom, Solaire Resort & Casino<br>
Due to peoples demand, Ariana Grande is back in the Philippines<br>
Ariana Grande Live in the Philippines on <b> March 11, 2017!</b></font>
<br><br><br><br><br><br><br><br>
</td>
</tr>
</table>
<br><br>
<hr>
<br>
<center>
<table cellspacing="10" cellpadding="10" bgcolor="gray">
<tr>
<td><font face=""><b>TICKET PRICES:</b></font></td>
<td><b>VVIP:</b> <u>Php 25,000.00</u></td>
<td><b>VIP:</b> <u>Php 20,000.00</u></td>
<td><b>Upper Box A:</b> <u>Php 15,000.00</u></td>
<td><b>Upper Box B:</b> <u>Php 15,000.00</u></td>
<td><b>Lower Box A:</b> <u>Php 10,000.00</u></td>
<td><b>Lower Box B:</b> <u>Php 10,000.00</u></td>
<td><b>General Ad:</b> <u>Php 5,000.00</u></td>
</tr>
</table>
</center>
<br><br>
<font face="Lucida Sans Unicode" size="2"><b>Ticket Type: </b></font>
<?php
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
echo '<font face="Lucida Sans Unicode" size="2"><b> Quantity: </b></font>';
$Quantity = range (1, 30);
echo '<select name="Quantity">';
foreach ($Quantity as $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
?>
<form action="<?php echo $action; ?>" method="post">
<br><br><br>
<button class="btnExample" type="submit" value="Submit"/>Next</button>
<style>
.btnExample {
color: #0000;
background: white;
font-weight: bold;
border: 1px solid #0000;
border-radius: 10px 10px 10px;
}
</style>
</form>
</body>
</html>
Heres the full codes of the webpage that has a problem.
You did not echo the variable to show the output:
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= "<?php echo $action; ?>" method="post">
Notice the <?php echo $action; ?>
Note: This is not the answer, and you should not accept this as answer, I am posting it here instead of posting in the comment section, because it's to long.
Note - You can solve your problem by your self, but for other it is impossible, as your code is just not making any sense at the moment, but I am pretty sure it will if you are able to read and understood what I am trying to say here in the solution.
First thing first,
Access Denied problem –
Note - you don’t have to fix this problem it will get fix by it self, but you should know why you have this problem, so in the future if you get the problem, you will know what to correct.
The reason it denying the access is this, that you are not allow to give special character for form action so after adding the echo in the form you are going to have this problem, because as soon as you add the echo in our form action you unknowingly giving special character to the action, because you never set the value for your variable $action so value for variable $action is equal to error message. So after adding the echo you are displaying that error message.
before doing any thing run your file in the browser and check the source code,
and see the value in the form action, it will be some thing like this
<br /><b>Notice</b>: Undefined variable: action in <b>C:\in here you are going to have file path\form.php</b> on line <b>1</b><br />
notice how many angle brackets colon you got in the here, you are not even allowed one angle brackets, so browser is thinking you are trying to do some thing malicious and that's why its blocking your access.
If you don’t know how to check source code, just type how to see source code and give your browser name (don’t ask me it just one click away)
so your code is basically generating error message and displaying it for the action after adding the echo and that's why browser is blocking the access
so why it was not doing the same thing before adding the echo, because in php, if you don’t use echo you are not displaying any thing, so before adding the echo, your action was empty, just remove the echo from the form action and check the source code again, you will understand what I am trying to say.
Again you don’t have to fix it, it will get fix by it self, remember this.
Now the solution start from here
First I have to be right about my assumption, that what you are trying to do,
So these are my assumption, what you want to do,
People should be able to buy different different types of ticket, and they can choose the number of ticket from 1 to 30,
Than you want to run different file according to the TicketType, in one case you want to run seat.php and in one case you want to run index.php,
And to achieve your goal, you created a form, use the if statement to set your action value in the form, as I can see you are using variable $action in the form for action, and you set this value through your if statement.
If I am wrong about any thing up until now, don’t read further it will be waste of time.
basically to achieve your goal, you are using form, array and some logic,
in your case you seems to know array and logic, but you lack pre basic knowledge about the form, and that's why your code is not working.
To be honest. In my opinion you know nothing about the form. That's why it is impossible to give you solution(at least for me). But I am quite sure, if you read this fully you will be able to solve your problem by your self,
so give a quick read to the points, and you will be surprised how easy it is to solve your problem for you, and you will also realized why it is impossible for other to solve it for you, at the moment.
Now Start from here
I am dividing the problem in Four part
Some important Notes about the form.
$Ticket_Type is not equal $TicketType - an you can not even use $TiccketType here
Select option only passes the value from the value tag-- Two part solution
Your logic is at the wrong place,
1. Some important point about the form.
When you use form, you have to tell php, that you are submitting the form, and if you want to do it only with php, you have to use submit button for it(I already mention this in my comment other day),
second you need to know, what happened when you click on the submit button in the form, form will run the action file and also will pass the data from. opening form tag <form> to closing form tag </form> to that file
but any data which is out of these opening and closing form tag, form will not pass that data, so point is it only passes the data which is inside the opening form and closing form tag.
Look at the code below to understand it better, and please also run this code, so you can understand it better,
Few points about the code
in the below code, we have two input field location and name, location input field is out of the form tag and name input field is inside the form tag.
and our form action is seat.php, and name for form file is form.php for this example.
as our action is seat.php, so if you click on the submit button, it will pass the data to seat.php, and will run that file.
in seat php, we are just using echo to display both value,
see the code below for form.php and for seat.php,
form.php
Location<input type="text" name="location"/><br><br>//out side of the form tag
<form action="seat.php" method="post">
Name <input type="text" name="name"/><br><br>
Location <input type="text" name="location"/><br><br>
<input type="submit" value="Hot Air">
</form>
seat.php
<?php
$name = $_POST['name'];
echo $name.'<br>';
$location = $_POST['location'];
echo $location;
Now go and run form.php and type some thing in the location and name box, and click on the submit button, and if you do that, it will only display you the value for name but for location value it will display you the undefined index location error.
And the reason is, because your form never passed that value for location to seat.php1, becauselocationis out ofform` opening and closing tag,
Now put this Location field inside the form tag
now put that location inside the opening and closing form tag,
after doing that our code should look like this
<form action="seat.php" method="post">
Name <input type="text" name="name"/><br><br>
Location <input type="text" name="location"/><br><br>//Now location is inside of the form
<input type="submit" value="Hot Air">
</form>
Now again run your form.php type some thing for name and for location and click on submit button, this time it will display you both the value, as this time both values are inside the form tag so both value get passed.
Note – If you can understand the difference between the first result and second result, you will be able to understand, why you need to have your select tag inside the opening and closing form tag, you can not have them out side of,
$Ticket_Type is not equal to $TicketType – and you can not even use $TicketType in here as it is equal to array you want value from the select option
For Second mistake, pay attention to this portion of your code
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
in here if you read this line echo ' <select name="Ticket_Type">' you give name for select Ticket_Type and than in the if statement You use the variable $TicketType, I am assuming you are checking the value for $TicketType, This problem you can solve it by changing the variable name $TicketType to $Ticket_Type In the if statement.
you have to correct this as well at the same place
So even after apply the above fix, your code wont work, cause you have second problem in this code
Now comes to the second problem, which you made in your if statement , in your if statement in here you checking $TicketType value, but you don’t have value for variable $TicketType because when you use the form php don’t set the variable it set the index so first you have to set the value for $TicketType than only you can use the if statement,
After applying both fixes your code should look like this
Note – (I am changing the name for select to TicketType )
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
$Ticket_Type = $_POST['Ticket_Type']; // Now you set the value for variable
// as your value is set, now you can type your if statement below.
if($Ticket_Type == 'VIP'){
$action = "index.php";
}else if ($Ticket_Type == 'VVIP') {
$action = "seats.php";
}
3. Select option, pass value only from the value tag
Third mistake you make and this one you will not notice with this code, but if you don’t learn, you will likely to make that mistake in the future, so correct this mistake as well,
Just pay attention to this code
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
In here you have array, and than you are creating select option from your array which is fine, but you are making one fundamental mistakes in here, form will only passes the value form the value tag
so come to this line in your code
echo "<option value=\"$key\">$value</option>";
now change variable to $key to variable $value as well, because when you click on the submit button, again form only passes the value from value.
echo "<option value=\"$key\">$value</option>"; to echo "<option value=\"$value\">$value</option>";
it wont change the out come, for this code, as in your array key and values are same, but you should know what value you are passing for the future.
To Understand what I am trying to say here, run these two code from below, you will understand what I am trying to say.
form.php
<form action="seat.php" method="post">
<select name="Ticket_Type">
<option value="key1">First</option>
<option value="key2">Second</option>
</select>
<input type="submit" value="Hot Air">
</form>
seat.php
<?php
$value = $_POST['Ticket_Type'];
echo $value;
run this file in the browser and than select the option, and click on the submit button, it will display you key1 or key2 depending on the option you choose, not the first or second, as form only submit the value from value tag
now change value tag value to One and two, and run your code again,
<form action="seat.php" method="post">
<select name="Ticket_Type">;
<option value="One">First</option>
<option value="Two">Second</option>
</select>
<input type="submit" value="Hot Air">
</form>
Now again run the file in the browser, and chose the option and click on the submit, and see the outcome, and try to understand what is happening.
4 Your logic is at the wrong place
see this code
if($Ticket_Type == 'VIP'){
$action = "index.php";
}else if ($Ticket_Type == 'VVIP') {
$action = "seats.php";
}
What your are trying to do here, in your head it make sense, that you will run the different different file,
according the ticket type, but in reality it does not make any sense, because when you click on the submit button, than only form will pass the value, to the action file,
this one is hard to explain
ok listen you have this variable $TicketType in this code, it only get set after you click on the submit button, and the action file it never going get set in this files, so you can not have these lines in this file. (and that's why it was showing to access forbidden after adding the echo)
Ok let's say you move this line to the different file, but still what you are trying to do with these lines is still silly, just don’t use these silly lines, and don’t try to run different different file, run single file, means give single action, and lets say action in the form is book.php
so our file name is book.php,
so starting shell for your book.php should look like this
if(!empty($_POST['Ticket_Type'])){
// what you are basically saying that if TicketType is not empty run this code,
// if it is empty run the else statement so the user will know that he did not select any ticket,
//now we are going to add some more code In here
}else 'Hey you did not select any ticket';
After adding the code in the middle our code will look like this
if(!empty($_POST['Ticket_Type'])){
$Ticket_Type = $_POST['Ticket_Type']; // set the value
if($Ticket_Type == 'VIP'){ //
// Copy and paste the index.php file code here
}else if ($Ticket_Type == 'VVIP') {
//copy and paste the seat.php file code here
echo $action;
}// if you have another Ticket_Type just add another else if here,
//Note: you can add as many else if you like,
}else 'Hey you did not select any ticket';
so just run single file action
i am still alive, after typing all this, if you have any confusion let me know.
Your Proble is here:
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
And your condition for if statment is
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
$TicketType is an array and you can't check it with a string, so your $action variable is not setting. and you have to provide index to check.
I had a similar problem where my error read "Object not found!
The requested URL was not found on this server. The link on the referr..."
Going off of aria_suhail_123's answer, you simply need to remove any php code surrounding your $action variable in your html like so:
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= $action method="post">
The reason why is explained by aria_suhail_123, but since his/her response is very long... maybe this will help someone else!
Consider this :
<?php
if(!empty($_POST['tickettype'])){
if($tickettype == "VIP"){
?>
<script type="text/javascript">
window.location = "./seats.php";
</script>
<?php
}else if ($tickettype == "VVIP") {
?>
<script type="text/javascript">
window.location = "./seats1.php";
</script>
<?php
}
}else 'Hey you did not select any ticket';
?>
I'm trying to write a web application in which students enter their timetable. For example: First period of Monday is math, second period of Monday is English,... first period of Tuesday is history, second period of Tuesday is biology,... etc.
So I write a form like this:
<form method="post" action="timetable_handling.php">
<?php
for ($period=1;$period<=9;$period++)
{
echo "<tr>";
for ($day=1;$day<=7;$day++)
{
echo "<td><input name="the_subject_of_the_nth_$period_on_$day" type="text"></td></tr>";
//the problem is here
}
}
?>
</form>
So my question is, are there any ways to pass the many variables to another php file to handle without having to manually write its name explicitly?
Edit 1: I mean is there anyway to encode the period and day information in the name, so that when it sends to timetable_handling.php I can just loop through it to save it into sql database. Something like an array $subject[day][period].
I would be grateful if someone could help me.
Start with the following on your timetable data entry page:
<form method="post" action="timetable_handling.php">
<table>
<?php
for ($period=1; $period<=9; $period++)
{
echo '<tr>';
for ($day=1; $day<=7; $day++)
{
echo '<td><input name="subject_of_period_'.$period.'_on_day_'.$day.'" type="text"></td>';
//the problem is here
}
echo '</tr>';
}
?>
</table>
<input type="submit" value="Submit Form" />
</form>
Then follow up with this script on your timetable_handling.php:
<?php
for ($day=1; $day<=7; $day++)
{
for ($period=1; $period<=9; $period++ )
{
${'subject_of_period_'.$period.'_on_day_'.$day} = htmlspecialchars($_POST['subject_of_period_'.$period.'_on_day_'.$day],ENT_QUOTES);
echo '<p>Subject of Period '.$period.' on Day '.$day.' is '.${'subject_of_period_'.$period.'_on_day_'.$day}.'</p>';
}
}
?>
It's secure and it works.
Yes. If you format a variable name something like
for ($day=1;$day<=7;$day++)
{ ?>
<td><input name="subject['<?= $period ?>'][<?= $day ?>]" type="text"></td></tr>
//the problem is here
<?php }
PHP will turn $_POST['subject'] into a 2D array for you. (Note I make no promise this is free of syntax errors.)
In the form handler you can loop through all the posted fields like this:
foreach($_POST as $field => $value)
{
}
Where $field would be the input-tag name and $value it's value.
If you have other form elements you can check which ones you need with some kind of prefix, like if the fieldname starts with 'the_subject', you know it's one of the fields that were dynamically added.
sure, you already did part of the answer :)
first issue: you are not escaping your string properly:
Here is 1 another way
echo '<td><input name="'.$period.'_on_'.$day.'" type="text"></td></tr>';
As for handling the post here is what you can do. You might need to tweak it around to get the exact desired result. But you are talking about multidimentional array.
if (isset($_POST)){
$something=array();
foreach ($_POST as $single=>$value)
{
array_push($something, array('period_'.substr($single,0,1) => array('day_'.substr($single,-1)=>$value)));
}
}
echo '<pre>'.print_r($something,true).'</pre>';
Good Luck.
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!
Hi I am a newbie learning PHP ( & on stackoverflow too)- I am trying to solve a simple problem but unable to do. I hae already searched on google and stackoverflow before posting a question as I didnt want to waste other time but for a week now am unable to solve this issue.
I am writing a simple program in php that lets user input a number and checks if the value entered is 5. If true it echo's "you win" else "try again". I am able to do this
The tricky part for me is I want to give him only 10 chances and try as I might using basic PHP am unable to do this. Have tried using if, for, do while but am unable to "loop the html"..I dont know jquery etc and am trying to accomplish this with PHP only. I havent yet progessed to learning sessions etc. Thanks in advance
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="hidden" name="cnt" value=<?php $cnt=0 ?>>
<input type="submit" name="go">
</body>
</html>
<?php
$i=0;
if ($_POST['num']!=5)
{
$i++;
echo $i;
echo " Please try again";
}
else
echo "You win the game";
?>'
You need to store the variable in some manner such that it persists. in your script, you are setting $i to 0 each time it runs. Plus you are setting the value incorrectly in your hidden input.
One way of doing this is using a Session variable, such as $_SESSION['cnt']
My PHP is a bit rusty, but here's an example using Session variables:
$max_guesses = 10;
if( !isset($_SESSION['cnt']) ){
$_SESSION['cnt'] = 0;
}
if( $_SESSION['cnt']++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
If you don't want to, or can't use a session variable, you could use the hidden input field, like you tried to:
<?php
if( !isset($_POST['cnt']) ){
$cnt = 0;
} else {
$cnt = $_POST['cnt'];
}
if( $cnt++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
?>
<input type='hidden' name='cnt' value='<?php echo $cnt ?>' />
(Note if your form uses GET instead, just replace $_POST with $_GET or you can use $_REQUEST if you're not sure, but probably better not to.
After successful login of the user set the chances variable to 10 like this.
$_SESSION['nofchances']=10;
After setting this flag on the successful authentication page. Redirect to your PLAIN html code.
EDITED :
question.html
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="submit" name="go">
</body>
</html>
gullible.php
<?php
if($_SESSION['nofchances']!=0)
{
if ($_POST['num']!=5)
{
$_SESSION['nofchances'] = $_SESSION['nofchances'] - 1;
echo "You have ".$_SESSION['nofchances']." no of chances to try";
echo "<br>Please try again";
header("location:question.html");
}
else
{
echo "You won the game";
$_SESSION['nofchances']=10; // resetting back
}
}
else
{
echo "Your chances expired";
}
?>
You can call a function in onBlur/onChange
<script>
function test()
{
var count=<?php echo $count;?>;
var guess=parseInt($('#hid_num').val())+1;
if(guess>count)
{
alert('Your chances over!');
}
else
{
$('#hid_num').val(guess);
}
}
</script>
<input type="text" onblur="test();" id="chk_estimate" />
<input type="hidden" value="0" id="hid_num" /></body>
If you dont want to use sessions yet you could define a hidden input field which stores the current try then incriment "+1" it whenever the submit is pressed / the site is reloaded. Something like:
if( isset($_POST['try']) ) {
$try = $_POST['try'];
$try += 1;
} else {
$try = 0;
}
add the hidden field in your form like:
$hiddenTry = '<input type="hidden" value="'. $try .'" name="try"/>';
and add a if clause to when to show the form like:
if ( $try <= 10 ) {
//your form
}
i made this for you i hope it can help you learn something new (i edited it a couple of times to make variable names easier to understand make sure you check it again - i added a cheat also :) )
<?php
session_start(); // with this we can use the array $_SESSION to store values across page views of a user.
mt_srand(time()); // this is to ensure mt_rand function will produce random values. just ignore it for now. it's another story :)
$max_tries = 10; // limit of guesses
$_SESSION['the_magic_number']=!isset($_SESSION['the_magic_number'])?mt_rand(0,100):$_SESSION['the_magic_number'];
// the previous line is a one-liner if then else statement. one-liners works like this:
// $my_name_will_be=($isBoy==true)?"George":"Mary";
if(isset($_POST['num'])) // if this pageview is from a valid POST then...
{
$_SESSION['current_try']=isset($_SESSION['current_try'])?$_SESSION['current_try']+1:1;
// one-line if then else again. This increases the try user is now, or resets it to one
}
?>
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<?php
if ($_SESSION['current_try']<=$max_tries) // if user has more tries available
{
if(intval($_POST['num'])==$_SESSION['the_magic_number']) // did he found it?
{
echo "You found it! Gongratulations! Click <a href=''>here</a> to try again!";
// oh and do not forget to reset the variables (you found this bug, well done!)
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
else
{
// if he didn't found it, display the status of tries left, and the form to try again
echo "This is your try ".($_SESSION['current_try'])." of ".$max_tries." Good Luck!";
?>
<form method="POST" action="mygame.php">
Please enter any number :
<input type="text" name="num"/>
<input type="hidden" name="tries" value="<?php echo (isset($_POST['tries']))?$_POST['tries']-1:$max_tries; ?>"/>
<input type="submit" name="go"/>
</form>
<span style="color:white;background-color:white;"><?php echo "You bloody cheater! The magic number is ".$_SESSION['the_magic_number'];?></span>
<?php
}
}
else
{
// here we are if no tries left! An empty href to reload the page, and we resetting our variables.
// the_magic_number gets NULL so at the start of script it will be "not set" and will get a mt_rand(0,100) value again
echo "You lost! Sorry! Click <a href=''>here</a> to try again!";
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
?>
</body>
</html>
the span at the end is a cheat ;) press ctrl+a to use it !!!
After the user hits the submit button, how do I reset the drop down menu to the "blank" option of the the menu? I am using a MVC set up with php and HTML, and the concrete5 library. THANKS IN ADVANCE! Here is what I have so far:
Controller code:
public function authorize() {
$selectHost = array('' => '');
foreach ($this->host->getHostInfo() as $row) {
if (isset($row['HARDWARE_id'])) {
$selectHost[$row['id']] = $row['host'];
}
}
$this->set('selectHost',$selectHost);
$postCheck=array(array('param' => 'host',
'check' => '^[0-9]{1,50}$',
'error_msg' => 'Invalid Host ID'),
);
$post = scrub($_POST,$postCheck);
if (isset($post['host'])) {
$this->host->authorize($post['host']);
$this->set('test', "<p> The host has successfully been authorized.</p>");
}
else{
$this->set('failed', "<p>Invalid Host ID</p>");
}
}
view code:
<form method="post" enctype="multipart/form-data" action="<?=$this->action('authorize')?>">
<?php
$form = Loader::helper('form');
print $form->label('host', 'Host: ');
print $form->select('host', $selectHost);
?>
<?php
print $form->submit('Submit','Submit');
echo $test;
echo $failed;
?>
</form>
I'm pretty positive that there's no way to override C5's desire to take the POSTed value and use that as the default. Even if, as TWR suggested, you specify a value. (This is typically a good thing, because if the page is POSTed to and there's an error, you don't want to show the value from the database; you want to show what was in the POST).
You can override the form helper pretty easily.
However, I'd suggest that you do a redirect after successful submission (don't redirect after an error -- then the POSTed value will be useful) to a page. You can redirect to another page, or the same one, ideally with a confirmation message. See https://github.com/concrete5/concrete5/blob/master/web/concrete/core/controllers/single_pages/dashboard/blocks/stacks.php#L23 for an example of using redirect.
This is the best practice for your problem but also because, with your current code, if somebody hits refresh, it'll rePOST the data and reauthorize the host.
i think you could extend the form tag with a (javascript) onsubmit action which does the reset.
Since it's a form submit, you just want to change the value of the "drop box"/select in your view. After a submit, you'll have a fresh page load; so, in every case you'll want to display the default value, and not the current value of $selectHost
In your view, change this
print $form->select('host', $selectHost);
to this
print $form->select('host', $selectHost, null);
According to http://www.concrete5.org/documentation/developers/forms/standard-widgets
If the problem is that the Concrete5 form helpers are not behaving as you want, then just don't use them -- instead just use regular HTML form inputs instead.
<form method="post" enctype="multipart/form-data" action="<?=$this->action('authorize')?>">
<label for="host">Host: </label>
<select id="host" name="host">
<?php foreach ($selectHost as $value => $text): ?>
<option value="<?php echo htmlentities($value); ?>"><?php echo htmlentities($text); ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Submit" />
<?php
echo $test;
echo $failed;
?>
</form>