I was trying to run a code that inserts new data in my DB but I've noticed that data was inputted twice each time I was running the code.
I've completely changed the code, It's just a Variable Session that increments each time I reloading the PHP page.
But each time I reload the page the incrementation goes by 2 instead of one 1.
Here is the code (It's really simple):
session_start();
echo "test";
echo strval($_SESSION["testCount"]);
if(isset($_SESSION["testCount"])){
$_SESSION["testCount"] = $_SESSION["testCount"] + 1;
}
else{
echo "TESSESSION";
$_SESSION["testCount"] = 0;
}
NOTE: When I run it into privacy mod is working perfectly.
Related
In my site there's a JS script, This script contact with external site to load some values related with captcha challenge, After this script loads variables and their values, This script will make a hidden input and this input has a name and id and token value!
The problem is that the script takes time to load, sometimes 6 to 10 seconds! depends on server speed! I made a php function, This function has the ability to check if that script loaded or not, Here is my code
The function check the value of this element $_POST["fc-token"];, If its value wasn't empty that means the script is already loaded
function check_s(){
$session_token = $_POST["fc-token"];
if(!empty($session_token)){
echo "Loaded";
}else{
$counter = 1;
while($counter !== 10){
sleep(1);
$session_token = $_POST["fc-token"];
if(!empty($session_token)){
$counter = 5;
break;
}else{
$counter = $counter + 1;
}
}
}
}
I don't know why this function stopped my whole site! everything won't load like js script and other scripts, And after 10 seconds the script will start loading! Idk why this function didn't allow anything to load!
So Is there a way to solve this matter?
I need to set a dynamic id for every document load. This ID should be set in PHP. Now, when i set a session_start(), the php code would be executed twice because the ID-code in generated document source differs from the same code in the alerted script variable. There are no runtime errors.
What's wrong with this code and how can i prevent the session to re-execute my code after session_start() ?
And when the code would be executed twice (var idvar contains a different value) why the heck is alert executed only once?
I simplified the script so you can try for your self:
<?php
// Session start generates two different ID's
session_start();
// Create ID
$time = microtime(1);
$parts = explode('.', (string)$time);
$idvar = strtoupper(strrev(dechex($parts[0]) . dechex($parts[1]))) . dechex(rand());
?>
<script>
// Contains a new generated ID after session_start()
var IDvr = '<?php print $idvr; ?>';
alert(IDvr);
</script>
Screenshots:
Try move the id initialization just before session_start() i suspect it related on how things executed in php after session_start().
Edit
still unable to reproduce it
I found this:
PHP Session storing behavior into variables?
But even when i add a favicon to the page it don't works. Also the page is standalone and not included as require in another page.
Even this is not working!
// Session start generates two different ID's
if(!isset($_SESSION) && !isset($idvr)) {
session_start();
// Create ID
$time = microtime(1);
$parts = explode('.', (string)$time);
$idvr = strtoupper(strrev(dechex($parts[0]) . dechex($parts[1]))) . dechex(rand());
}
Update:
Now corrected:
With view-source:pgname and session initialized the code would be executed again in source view!
I'm using a code that generate a random word from a database using ORDER BY RAND() LIMIT 1 (not many rows so it runs okay) . Is it possible, using php, to only allow the user to refresh the page a few limited times (either by clicking refresh manually or using a form['submit'] button) and then stopping the random function so it sets to the last value?
I know I can count page visits/refreshes by using sessions/cookies but I'm not sure how to stop the code running.
Barely constitutes an answer but too long for a comment - what is it exactly that you don't get?
<?php session_start();
// ...
if(!isset($_SESSION['myCounter']))
$_SESSION['myCounter'] = 0;
if($_SESSION['myCounter'] < $myLimit){
$_SESSION['myCounter']++;
// Do random DB query
$_SESSION['lastResult'] = $dbResult;
}
// Do something with result
echo $_SESSION['lastResult'];
// ...
There are even examples on the manual pages...
A IF statement would suffice
IF ( pagecount < 3 )
{
Execute code
}
ELSE
{
Don't execute code
}
Set a flag on your PHP Script using a session say, $_SESSION['runRand'] = 1;
Run the random word db code only when the above variable is set to 1.
So when the user runs this script first time...
Store the first random word which was generated from DB into a session variable say $_SESSION['firstRand']=$randNum;
So when the user clicks the refresh button or submit, the PHP script gonna load again and a new random word will be generated, now don't store that word, just compare it to the one with the session variable $_SESSION['firstRand'];
When the user keeps clicking refresh and do the same process again, at some point the random word will match with the $_SESSION['firstRand']; , at that time set the session variable $_SESSION['runRand'] = 0; . Now , eventhough the user presses the refresh button the random code from DB will not be generated.
I'm once again asking for the SO community for a little help.
I'm modifying a Joomla "quiz" component to make it behave the way I need it to.
What I'm trying to do now is to change the "refresh" behavior of the component. Basically, every quiz has a timeout, i.e., a time when the quiz is no longer accessible to the user so when the timer gets to 0, the quiz is submitted and so on, but the default behavior of this component makes it that whenever the page is refreshed the timer will reset to the initial set time (let's say, 10 minutes)
The thing is I want to be able to have the timer continue from where it left of in case of a refresh.
I haven't used PHP since 3 or 4 years ago so I'm kinda lost.
To be able to achieve the desired behavior I'm setting up a cookie that will store (via implode) the initial time (when the quiz was opened) and the "now" time (on load it's set to 0 but upon refresh I want to "update" the cookie to store the reload time).
With the initial time and the now time, I'll be able to calculate how much time has passed and place the timer from where it left off.
The thing is, I'm trying to "update" the cookie with a javascript 'onbeforeunload' so that I can manage to get the refresh time into the cookie. But for some reason, it's not doing anything at all. When I go to see the cookie contents everything is still the same from when the cookie was set.
I know that in order to update the cookie I'll have to delete it and then set it again, but I'm being unsuccessful.
Heres the sample code:
//This is responsible for setting the cookie (via PHP):
<?php
$name = "progress";
$now = 0;
$time_diff = 0;
$expire = time() + 3600;
$data = array(time(), $now, $time_diff, $this->quiz->time_limit);
//$var = implode(',', $data);
if(isset($_COOKIE[$name])) {
/* If defined, update the timer */
} else {
setcookie($name, implode(',',$data), $expire);
}
echo $_COOKIE[$name];
echo "<br />";
echo $this->quiz->time_limit;
?>
And this is to detect the "refresh" event (with Javascript that will run PHP):
window.onbeforeunload = function() {
<?php
$name = "progress";
$list = explode($_COOKIE[$name]);
//delete cookie
setcookie($name, "", time() - 3600);
//Update the fields
$list['1'] = time(); //now - refresh time
$list['2'] = $list['1'] - $list['0']; //time_diff
//Set the cookie again
setcookie($name, implode(',', $list), time() + 3600);
?>
}
Can anyone point out what is wrong with this code?
As has been said in the comments, JavaScript cannot run PHP code like that... but if you use AJAX then you can. Now with the code you posted for us to see, if you load up your page in the browser and view the code your function will look like this:
window.onbeforeunload(){
}
So it's no surprise that nothing is happening with your cookies when you are closing your browser. Now, without seeing your other functions it's hard to tell exactly what is happening but you can use PHP and JavaScript intertwined but in a different fashion. Let me explain this with an example.
window.onbeforeunload(){
var name = <?php $name='Steve'; echo($name); ?>;
console.log(name);
}
If you had this code and loaded the page in the browser you would no longer see the PHP code, but instead would see this:
window.onbeforeunload(){
var name = 'Steve';
console.log(name);
}
With that being said, here are a few links you might find helpful.
JavaScript Cookies
Set/Get Cookie using PHP and JavaScript
Simple AJAX - PHP and JavaScript
I was trying to make a little report management system recently. Everything was going well till I encountered this weird problem. Since the code contains lots of html, I'll only include the important parts.
Basically this is a login page. I am storing the information in SESSION variable.
When the username and pass doesn't match, the error message is given to this below function for further processing.
Edit: Every page in my project includes a config.php with following contents
// Start of config.php
session_start();
error_reporting(E_ERROR);
// ********************* Database Config **********************//
$dbHost = "localhost"; // MySQL host
$dbUser = ""; // MySQL username
$dbPass = ""; // MySQL password
$dbDatabase = ""; // MySQL main database name
A part of login.php is shown below.
//START OF PHP CODE//
include("config.php");
function gotError($msg)
{
$_SESSION['err'] = $msg;
header("Location: login.php");
die();
}
//CODE FOR EVALUATION OF DATA//
// END OF THE PHP CODE & BELOW THE HTML WILL START //
And on the same page, below the starting php code, there is the html code of page. Between the html, there are some bits of php code for using the data set above.
----------- SOME HTML CODE HERE----
<?php
if(isset($_SESSION['err']))
{
$html.= "<script type='text/javascript'>";
$html.= '$.alert("'.$_SESSION['err'].'");';
$html.= "</script>";
print $html;
}
?>
----------------- SOME HTML CODE HERE--------
Now here's the weird behavior comes in. The page post the login data to itself & if error occurs, the error is set in session variable { $_SESSION['err'] } and then redirected to itself again which displays a jquery message box if $_SESSION[ 'err' ] is not empty.
The above code doesn't work in the original form, however, if I do like code shown below, the code works. I mean the whole code including the conditional components which didn't worked previously. As soon as I remove that particular line, the conditional evaluation doesn't work.
<?php
print($_SESSION['err']);
if(isset($_SESSION['err']))
{
$html.= "<script type='text/javascript'>";
$html.= '$.alert("'.$_SESSION['err'].'");';
$html.= "</script>";
print $html;
}
?>
Does anyone have a clue about this? I am using PHP Version 5.3.8.
Thank You.
Are you calling session_start() to actually enable the session? Without that, you'll just be wasting your time. Unless you start the session, php will NOT save any data your write to $_SESSION, not will it load any data that was previously saved elsewhere.
I resolved this problem. Comes out that changing the position of the php script between the HTML from head to body did the trick.