I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).
There is also a back, and continue button which basically subtracts or adds to another variable ($brief_page - which is pulled from my DB). The brief_string changes depending on the brief_page by using if statements. First problem I encounter is that when I hit continue (submit button) it resubmits/refreshes the page, causing my brief_page to reset back to 0.
So I'm thinking maybe I could use JS to hold the info and page variables and control the dynamic text, but then, how would I update my DB with the current page value via JS? Isn't it really easy to manually change/hack these values? I would preferably like my DB to be updated with the page number each time the use presses the back/continue button.
I would just like some advice really as I am a student trying to develop an interactive book like site (that uses a DB to save your current page).
Code:
<?
$brief_info = "brief info goes here";
$brief_page = 0; //< will soon be pulled off DB
if (isset($_GET['brief1Go'])) {
$brief_page = $brief_page + 1;
}
else if (isset($_GET['brief1Back'])) {
$brief_page = $brief_page - 1;
}
$breifController = "
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" />
</form>
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" />
</form>";
if($brief_page == 0){
$brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br />
";
}
else if($brief_page == 1){
$brief_info = "Okay, let me show you around the place ...";
}
else if($brief_page == 2){
$brief_info = "brief is on 2";
}
?>
Why not just use get vars entirely?
yes, start at 0 unless $_GET['page'] is set...
$brief_page = 0;
if(isset($_GET['page']))
$brief_page = $_GET['page'];
then only use links to your next and previous pages instead of some weird post thing.
Previous Next
where obviously the page numbers in the previous and next are just echoed from php
$prev = $brief_page - 1;
$next = $brief_page + 1;
The user specific things to store can easily be handled with sesisons, cookies or even other get vars if you want to introduce a horrible security hole. Your choice really.
I would definitely not do this via $_POST though. totally annoying. Go with all full on ajax if you want to do that. At least you won't pester the user with "are you sure you want to resubmit the form data" messages if they choose to refresh the page.
Related
im very new to PHP, so please excuse me if this is a stupid question.
So here is the scenario.
Im writing a PHP all in one page that gets a random word from an array, scrambles the word, then lets the user guess the word.
now im using the isset(), so it declares the variable, then once submit is clicked, it will get in user input via _POST().
Now the problem
I need the calculated variable to remain constant, but once the page reloads, it regenerates the variable.
is there anyway i can get pass this?
<?php
function GetShuffWord()
{
$arrayName = array('word1','word2','word3','word4','word5');
$randWordIndex = rand(0,4);
$randomWord = $arrayName[$randWordIndex];
$shuffledWord = str_shuffle($randomWord);
return $shuffledWord;
}
if(!isset($_POST['Submit']))
{
define("shuffledWord", GetShuffWord());
$tempWord = shuffledWord;
// showing the user shuffled word
echo " <h1 style='font-size: 50px' align = 'center'> {$tempWord}
</h1>";
}
else
{
$tempWord = shuffledWord;
echo " <h1 style='font-size: 50px' align = 'center'>{$tempWord} </h1>";
echo "else part";
}
?>
another problem is that if i declare the variable in the if, i cannot use variable in the else with out re-generating it.
You can just include the value as a hidden input field in your form.
<input type="hidden" name="myCalculatedValue" value="<?= $tempWord ?>" />
Then when the form is submitted you can just get it via $_POST['myCalculatedValue']
You can use session and put a check that if session has it already dont overwrite.
And when u want to overwrite you can do so as well by passing another flag to the script in your post request.
I have a small chat application for internal usage, this is light version just for example. I need few things, sorry for asking full source code but I try understand and learn from this example (I need it for few things).
Please find my source code:
<?php
if(isset($_GET['opt']))
{
if($_GET['opt'] == 'write')
{
$entry = $_POST['chat_input'];
$data = fopen("dat.txt","a+");
fwrite($data,"$entry\n");
fclose($data);
}
}
// jQuery auto refresh start
$dat = file_get_contents ("dat.txt");
if($dat == ''){echo 'You do not chat.';}else
{
$number_of_post = substr_count($dat, "\n");
$post = explode ("\n",$dat);
for($i=0 ; $i <= $number_of_post-1 ; $i++)
{
echo 'User x wrote: '.$post[$i].'<br>';
}
}
// jQuery auto refresh end
// jQuery form without refresh start
echo '<form method="post" action="index.php?opt=write">
<p><textarea rows="5" name="chat_input" cols="46"></textarea></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>';
// jQuery form withour refresh end
?>
I need two things:
- first is auto refresh iframe, when user write new post code must show this
- second is post my form without refresh, just execute action
Thank you very much for help, appreciate this.
To send post without refreshing use AJAX or method POST.
To refresh iframe do as asked here: How to refresh an IFrame using Javascript?
You can refresh iframe every second
setTimeout(function(){/*yourcodehere*/ },1000);
I have created a website in which when user logs in he specifies the year i.e. 2013-2014, or 2014-2015, and so on...Now, I am storing this value of year in a session variable which I am using it through out the site. Now, if user wants to change the year he will have to sign out and then log in with different year. I have created a dropdown menu on home page which will show all the years from database. I want to change the value of the session variable by selecting a year from home page without signing out.
Here is the code:
session_start();
if(!isset($_SESSION["myusername"])){
header("location:login.php");
}
$year = $_SESSION["year"];
Here is the code for dropdown menu:
$query = "SELECT * FROM year";
$result = mysql_query($query);
echo "<select class='innerinputstyle' id='year' name='year'><option value='$year'>$year</option>";
while($note=mysql_fetch_array($result)){
echo "<option value=$note[year]>$note[year]</option>";
}
echo "</select>";
Can anyone please tell me how to change the value of $year from home page?
I think you have plenty of choices to achieve this, and the AJAX one is one of them , but everything depends on how you want to implement the user interface. You can think to create a little form with the drop down and submit the year, you can do this via a submit button or via javascript and as for the AJAX example the solution is always the same:
$_SESSION['year']=$_GET['year'];
At the end depend all on the user interface, if you want it invisible to the user, without refreshing the page, use AJAX, otherwise just submit your input
Change
echo "<select class='innerinputstyle' id='year' name='year'>"
into
echo "<select class='innerinputstyle' id='year' name='year' onChange='doIt()'>"
and here is the ajax function
function doIt(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
}
var new_year = document.getElementById('year').value;
xmlhttp.open("GET","change_year.php?year="+new_year,true);
xmlhttp.send()
return false;
}
on change_year.php you can easily change
$_SESSION['year']=$_GET['year'];
Warning: Untested code. Used to sketch the idea.
ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.
I'm having difficulty using hidden forms with PHP data. I cannot for the life of me figure out what I'm doing wrong.
My code should
Check to see if an attack succeeded;
If it succeeded, subtract damage from health;
Rewrite the $health variable.
Use the new $health value for the next round.
The problem is, it keeps resetting the health value.
Here is my code (it's set so that the attack always succeeds):
<?php
$health = $_REQUEST["health"];
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
$health =50;
if ($attack>$defend){
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
print "<p>Jim missed.</p>";
print "<p>The robot has $health health remaining.</p>";
} // end if statement
print <<<HERE
<input type="text"
name="openMonsterHealth"
value="$health">
<input type="hidden"
name="hdnMonsterHealth"
value="$health">
<input type="submit"
value="click to continue">
HERE;
?>
If you want $health to follow you to the next page, use sessions.
PHP Manual on Sessions
Basically, you'd start your pages with
session_start();
if(isset($_SESSION['health'])) {
$health = $_SESSION['health'];
}
else {
//However you normally set health when the user is just starting
}
which would load the health value from the previous page, if you set it like this:
$_SESSION['health'] = $health;
PHP scripts automatically write and close sessions, so you don't have to worry about anything other than creating a variable in the session global array. Just don't forget to start your sessions when you want to retrieve the data in the session array from the previous page. Your users, however, will have to be able to accept cookies.
If you keep using hidden fields, a player could change that information before sending it back to you (plus, they're more trouble to keep track of).
edit:
Your bugs, however, are you're resetting your health to 50 on the 5th line of your code, you're not using the right variable name for health from the request, and you don't have any form tags.
<?php
if(isset($_REQUEST['hdnMonsterHealth']))
$health = $_REQUEST['hdnMonsterHealth'];
else
$health = 50;
$attack = rand(10,20);
$defend = rand(1,9);
$damage = rand(1,5);
if ($attack > $defend) {
print "<p>Jim hit the robot for $damage.</p>";
$health = $health - $damage;
print "<p>The robot has $health health remaining.</p>";
} else {
print "<p>Jim missed.</p>";
print "<p>The robot has $health health remaining.</p>";
} // end if statement
print <<<HERE
<form method="post">
<input type="text"
name="openMonsterHealth"
value="$health">
<input type="hidden"
name="hdnMonsterHealth"
value="$health">
<input type="submit"
value="click to continue">
</form>
HERE;
?>
Edit: Sorry for all of the weirdness, formatting is broken by this block of code, so I had to manually insert every < in the code with <. This code works now, however.
You still have a bug of negative health. I'm not writing your game for you, though.
Sorry, you haven't mentioned what scope your $health variable is. Does it belong to the session, or just for the lifetime of the request?
I'd strongly encourage using session variables, i.e.:
$_SESSION["health"] = $_SESSION["health"] - $_REQUEST["DAMAGE"];