Advanced cURL and PHP - javascript

I made a similar question few hours ago, but I think I asked a wrong question there. This is more exact one.
im using cURL on PHP and i want to use a site, but everytime i change my site, the browser posts a value x to server, and if you dont, you can't go to the site.
you can see that the x value changes all the time from the picture, its a FireFox Live HTTP headers addon, it shows what pages i visit with browser
i looked the source code and found out what is the x value, and it comes from javascript. can i get the value with cURL or some other way from the server?
date = new Date();
ms = (date.getHours() * 24 * 60 * 1000) + (date.getMinutes() * 60 * 1000) + (date.getSeconds() * 1000) + date.getMilliseconds();
so the main problem is that the x value changes all the time and it has to be exactly "right" value , even milliseconds must be correct. i tried finding the value myself with javascript and then putting it to php, but still does not work

The reason is simple, you mixed between $_POST and $_GET
Check your PHP make sure is refer/using $_GET['x']

All that javascript is doing is calculating the current time in milliseconds on the client and sending it to the server. You can calculate such a time in php trivially with $ms = time() * 1000;

Related

Run javascript every 25 secs in server and insert into in sql database

I need to run this javascript function one time every 25 seconds and save it into mi sql database.
Right now i can do it, but it inserts one time every 25 seconds per client, and i want just once time without care how many clients are online. So i need to run it in the server, no in each client. But i dont know how to do it.
function calc_spin_time(){
function num_rand(){
var num = Math.floor(Math.random()*((20)+20)-20);
return num;}
spinTimeTotal = Math.random() * 3 + 4 * 1000 + num_rand();
spinAngleStart = Math.random() * 10 + 10;
//I need to insert spinTimeTotal and SpinAngleStart into mi sql database
}
I think what you're looking for is going to involve a Cron job of some kind. To accurately help it seems like more information is needed on the type of database and how the function is getting fired. There is a serverless mechanism I know of called Cloud Scheduler from Firebase.

Please How can I automatically add balance to user account after waiting some minutes?

So I'm making a gaming where 2 people play a game, report their scores on the website, and the winner gets credited. Now I want to add a feature where if one person reports a result and the opponent fails to report his own result within 5 minutes, the website will automatically credit the person who reported the result.
Currently, I have coded a countdown timer in PHP and Javascript (and I prefer to do the countdown in Javascript and call the PHP function after the time elapse but it looks like I can't execute PHP code within Javascript but I would like to do this if possible).
I have equally written the countdown in PHP but it looks like PHP can't run in the background, so it's not updating the balance even after the time elapse.
Here's the PHP countdown as an example of what I want to do.
<?php
// Set the date we're counting down to
$countDownDate = strtotime('Dec 25, 2020 15:37:25') * 1000;
//Get current date
$now = time() * 1000;
// Find the distance between now an the count down date
$distance = $countDownDate - $now;
// Time calculations for days, hours, minutes and seconds
$days = floor($distance / (1000 * 60 * 60 * 24));
$hours = floor(($distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
$minutes = floor(($distance % (1000 * 60 * 60)) / (1000 * 60));
$seconds = floor(($distance % (1000 * 60)) / 1000);
// Output the result
echo days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is over, update user balance.
if ($distance < 0) {
$mysqli->query("UPDATE users SET bal=bal+50");
}
?>
The problem that this code doesn't update the balance in real-time after the time elapsed. It updates the balance each time the page is reloaded and keeps updating the balance non-stop.
WHEN I change the if the part to
if($distance ==0)
then it will not update at all because PHP is not doing a background check to know when the counter reaches zero and update the balance.
If you understand what I want to do please suggest how I can do this checking and auto-updating. I will also appreciate the sample code.
Thank you.
This is a fairly tricky concept so a few bits to put together, but common and doable. There's a better but more complex way, and an easier hack. I'll explain both.
The "running in the background" bit there are a couple of moving bits:
a) You need to have a process constantly running. While most people will say you need NodeJS or similar, there is no reason why you can't have a PHP script running constantly in the background - what you need to watch for is if the process dies, you need something to restart it (actually, exactly like NodeJS uses pm or systemd to restart - do the same thing with PHP). You script will just constantly "loop" (see below!) looking for work to do.
b) My preferred method, though, if to have a "cron" running every 5 minutes that executes a script, and that script has a timer that loops but will end the loop after 5 minutes and then exit. New process starts. If you do this, you need to factor overlap or minor gaps.
The "loop" mentioned above must not burn your CPU, so you need to handle receiving messages in the right way. Ideally this needs to be ran by a queue, but there are other options.
a) Use a queue system such as RabbitMQ + deal letter queue (although we've moves to AWS SQS as we're hosted on AWS and that allows delayed messages) that holds the message and delivers after 5 minutes. Your script above will be listening for the message.
b) If you don't want to set up a queue, as you know the minimum time is 5 minutes, you could use the "5 minute cron" method and look for messages on start. If there is a message, "sleep" until that message should be processed, process it and look for the next one. If no messages, exit and the cron will repeat in 5 minutes. (Note: sleep is not recommended in a normal PHP script as it holds open HTTP processes, but for a single running background process like this, it's perfect).
Realtime feedback is another thing you can hack, or do correctly.
a) The correct way is to have another constantly running script that accepts socket connections, and JS will connect to the socket. PHP can be used very well for sockets, but NodeJS here does have much better support and you'll find easier. Start the socket server script, use Socket.io or similar in Javascript and connect to the socket server. When you update a score, push the result to the correct client.
b) The easier way is a polling system. Have JS poll the server regularly to see if there are updates. (Socket.io has a fallback to polling as well). This adds more strain on your server, but much easier to set up.

How to save time from a stopwatch and display that time in another html page

function runTimer() {
currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]) + ":" + leadingZero(timer[2]);
theTimer.innerHTML = currentTime;
timer[3]++;
timer[0] = Math.floor((timer[3]/100)/60);
timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60));
timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000));
}
So I am currently working on a Typing Test project in javascript and how my program currently works is that when the user first starts typing up the prompt, the stopwatch timer will start timing the user. Once the user finishes typing the prompt, the stopwatch will stop timing and then the user will be taken to an end page which should display the user's time. However I am having issues with trying to save the user's time. For example if User A finishes the test in 15 secs, the program should save the user's time and then display it in the next page which I will take them to.
I have tried using the localStorage.setItem function but just end up getting [object HTML Element] on my page instead of the score. Below I attached my code related to the timer function of my program. I basically want to save the time of it by using local storage but it won't work.
The simplest solution I have come up with is to send the user's time in the new URL as a parameter. When your timing stops, add this line:
window.location = 'your/new/page/location.html?time=' + time;
time - is the user's time. As you see, the parameter goes after '?' sign. So, on the new page you will be able to get this parameter with this line:
var usersTime = window.location.search.split('=')[1];
Here "search" method takes the part of the URL after '?' sign (including it) - it is going to be "?time=15". And then you split this line with '=' sing as a separator and take the second part, which is the number 15.
The local storage stores items as strings.
Therefor the easiest way would be to store the start time and the end time.
So, when the user starts, call:
window.localStorage.setItem("starttime", Date.now());
and when the user finishes, call:
window.localStorage.setItem("endtime", Date.now());
This will give you 2 timestamps, which you can then use to format your display.
Get the timestamps in your next page with:
starttime = window.localStorage.getItem("starttime");
endtime = window.localStorage.getItem("endtime");
totalseconds = (endtime - starttime) / 1000;
then use totalseconds to work out hours/minutes/seconds etc
If you need to display the timer on the screen as the user is typing, you can just use
totalseconds = (Date.now() - window.localStorage.getItem("starttime")) / 1000;
I've tested this in Chrome and it works fine.

Firebase - orderByChild integer not working

I have a database and I want to sort all posts by their score (an integer), I thought it would be super easy because I'm currently doing orderByChild('created') and it works perfectly, but for some reason orderByChild('score') doesn't work.
Here is my database structure:
score is an integer that can be negative, positive or 0.
The JavaScript I'm using:
this.subscription = this.database.database.ref('/posts/'+this.userData.location)
.orderByChild('score')
.startAt(new Date().getTime() - (24 * 3600 * 1000)) //last 24 hrs
.limitToFirst(10);
this.subscription.on('child_added', (snapshot) => {
this.postFeed.push(snapshot.val())
console.log(this.postFeed)
});
The weird thing is, the console.log isn't even firing so it's not even getting to that stage for some reason, but if I change .orderByChild('score') to .orderByChild('created') it works exactly as expected...
Any ideas what I'm doing wrong? Thank you!
I believe it might be something to do with this line
.startAt(new Date().getTime() - (24 * 3600 * 1000))
This will create a startAt query which would currently be 1519944842592
This means that it's trying to start at that specific number. So it's not looking for -1, it's starting the query at 1519944842592.
You would need to incorporate a createdAt object within your schema and query that first.
The reason your .orderByChild('created') works is because it's a date object which is before the startAt query so that's why it works correctly :)

Javascript Count Down - Controlled by server

My script has a countdown timer, but has to be controlled by the server since the time can change at any time.
Usually counts down from 1 hour, but as it gets closer to 0, a user fired event from PHP will reset the time on MySQL database and the timer will shoot back to what ever time.
setInterval(function() {
$('#timer').load('api/getdata.php?clock=1');
}, 600);
As you can see, currently the countdown is returned by a PHP script, which is called every 600ms (1000ms sometimes appears to skip a second).
I need to have a simple text countdown (Minutes and seconds), which synchronizes with the PHP script. But as it gets less than 30 seconds, would need to sync every second.
Is this possible with JS?
This is the code for the PHP
$from = time();
$to = strtotime($row['clock']);
$Timer = date('i:s', $to - $from);
echo("$Timer");
I think the easiest way to tackle this ( correct me if I'm wrong anyone! );
Fetch the time from the server
Return [ json ]
[server_time]
[seconds_left]
[miliseconds_left]
Set these values on a function and make sure its called as your contract requires. As soon as this starts hitting < 60 seconds shorten the interval by division of (e.g. the amount of seconds, altough this might not be optimal :-) ).
60/60 = 1
50 / 60 = .73
30 / 60 = .5
etc...
If the miliseconds are really really crucial I'm afraid you would have to provide some more insight of what it actually is you are trying to accomplish?

Categories