Set the javascript variable in php session variable - javascript

I want to set the php session $_SESSION['time'] based on user browser time
// gives time difference between utc time and current user local time
var offset = ((new Date().getTimezoneOffset()) * -1) * 60;
I want this offset value to be stored in a session variable like
$_SESSION['time'] = offset ; // something like this
Example
<script type="text/javascript">
I have to set the $SESSION['time'] variable at the beginning of page
so that i can use it down the dom
</script>
<span class="time_stamp"><?php echo $_SESSION['time'];?></span>

A php session is created at the page load on the server.
so there is no way to create the session after the page has loaded.
so you have only one/2 solution if you don't want to use ajax.
solution 1
sess.php
<?php
session_start();
$_SESSION['time']=$_GET['time'];
?>
js
head.appendChild(document.createElement('script')).src='sess.php?time='+offset;
note:head is only a reference in this case.
BUT
this is also async.
so again. there is no way to set the session after the page has loaded.
solution 2
preload a image outputted by php with gd that also set's your session. ;)
if you want to know how i can look into it.(this would cause a natural page load & would prolly work also on ie6 )i just don't remember exactly how to preload images before the body does.
I had the same problem some time ago ... i use ajax.
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function LoadThePage(){
//just some milliseconds passed.
//session is set
//load the rest of your page.
//MOST OF THE TIME this loads faster than the body does.(window.onload)
}
ajax('sess.php?time='+offset,LoadThePage);
at the other side ... now most modern browsers support localstorage.
all phones & the modern browsers.
if i store things like that. why use a php session?
localstorage is made to replace that.
window.localStorage['offset']=((new Date().getTimezoneOffset()) * -1) * 60;

Related

I'm trying to make a website load forever. How can I do this?

I'm trying to make a website load forever. My current idea is to request a PHP file:
<?php
sleep(30);
This will delay the load by 30 seconds, which a quick Google search tells me should be within most browsers' timeouts. I was thinking of writing some JavaScript to append a new link tag after a bit less than 30 seconds to keep the page loading, but I found that this didn't keep the loading icon spinning (with Chrome at least):
window.addEventListener( 'load', () => {
var i = 0;
setInterval( () => {
i++;
var newScript = document.createElement('script');
newScript.src = 'infinite-loading.php?i=' + i;
document.querySelector('#infinite-loading').after(newScript);
console.log('The deed is done');
}, 25000)
} )
<script id="infinite-loading" src="infinite-loading.php"></script>
The code above appends a script tag every 25 seconds, and the browser loads the PHP file each time, but it doesn't show the loading icon. I added the URL parameter because I wasn't sure if browsers would cache the page.
I also want to make sure that the server with the PHP file won't be overloaded. I'm not sure if many sleep() functions running constantly at the same time will cause any issues.
Is there a better way to do this client-side? Should I use something other than PHP? Something multi-threaded?
(Edit: Sorry for the awkward title, Stack Overflow didn't like my first one.)
You need that browser will continue reading your page forever (I'm talking about HTML, not other linked objects). So you need not to break timeout and feed some data from backend to frontend.
Example of sending portion of data to client:
ob_end_flush();
# CODE THAT NEEDS IMMEDIATE FLUSHING
ob_start();
Now we need to understand the minimum data packet size that is expected by the browser. Minimal googling tells us a limit of 8-10 bytes.
So combining this together we can try to check (I did not checked, it is just my version):
<?php
while (true) {
sleep(25);
ob_end_flush();
echo " "; // 10 spaces...
ob_start();
}
Not sure why you would want to do anything like this but the simplest solution I think is an endless loop.
<?php
while(true)
{
}

Javascript on webpage not changing text

I have the following script at the bottom of my php page, it runs on pageload, but I need it running every 10 seconds. It only runs on page load.
PHP is running.
I've tested this with a countdown from ten, and the script is actually looping, but for some reason not when i integrate this PHP.
Please help.
<script>
var CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
var x = setInterval(function () {
CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
document.getElementById("CurrentTestBranch").innerHTML = CurrentBranch;
CurrentBranch = "";
}, 10000);
</script>
Edit:
The code does display the file contents the first time around. But does not refresh when I make a change and save it.
Your PHP code is run only when the page loads. It generates string literals when it runs. These do not get updated when the interval function gets called repeatedly (because the PHP does not run again).
If you want to get new data from PHP you need to make new HTTP requests.
You could either reload the entire page, or use XMLHttpRequest (or fetch) to call a web service that gives you the data you want (Ajax is a useful search term).
PHP happens before HTML hits the server.
Look up setTimeout() javascript command. What you need to do is get javascript to call another php script, which checks and echoes your value.
Something like this (could be pseudocode, from memory):
setTimeout(function(){
var CurrentBranch = $.get('/url/that/sends/value');
// do something with your value, call a function, whatever
}, 10000);

javascript function to round current time (from epoch) to nearest minute

I've been banging my head against the wall trying to get a JavaScript equivalent to this php snippet:
<?php
$id = 'uniqueID'
$now = round(time()/60);
$lock = md5($now . $id);
?>
I've been trying variations on this:
var timeInMin = new Date().getTime() / 60000;
var timestamp = Math.round(timeInMin);
var key = md5(timestamp + 'uniqueID');
utilizing an md5 script from here
I merely need lock and key to match. Seems simple to me. What am I doing wrong?
As said before me, if time not matching it will not create the same hash. What I do in situations like that is to find way to pass the time from php to the client side so they can use the same exact time.
PHP side:
<?php
$id = 'uniqueID';
$now = round(time()/60);
$lock = md5($now . $id);
print $lock;
setcookie("time",$now);
?>
Client Side:
<script type="text/javascript">
var timestamp = getCookie("time");
var key = md5(timestamp + 'uniqueID');
console.log(key);
</script>
Note that getCookie is a shortcut function
The following example is here to present the idea in a simple form. I would not use time as the name of the cookie nor give access to the vars (wrap in function). Uglify scripts goes a long way in cases like this.
To put it in concrete terms (my comment was slightly facetious):
PHP is a server-side language. When your browser fires a request for a page over the internet (or even to a listening port on your local machine), the instance of apache running on the server (or your local machine) executes the PHP on the page, then spits it back out to the browser.
The browser then executes any JavaScript on the page, we refer to this as client-side.
Because you are using Math.round, if it takes more than 30 seconds between the time your server executes the PHP (server-side) and the time your browser starts executing the relevant Javascript (client-side) then the time in minutes will be different. Using Math.floor instead would give you 59 seconds of wiggle room but that's still dicey, especially on mobile.
Even assuming the page executes the JavaScript immediately after loading and loads pretty quickly 30 seconds of latency is not totally off the table, and on mobile neither is 59.

How to append timestamp to the javascript file in <script> tag url to avoid caching

I want to append a random number or a timestamp at the end of the javascript file source path in so that every time the page reloads it should download a fresh copy.
it should be like
<script type="text/javascript" src="/js/1.js?v=1234455"/>
How can i generate and append this number? This is a simple HTML page, so cant use any PHP or JSP related code
Method 1
Lots of extensions can be added this way including Asynchronous inclusion and script deferring. Lots of ad networks and hi traffic sites use this approach.
<script type="text/javascript">
(function(){
var randomh=Math.random();
var e = document.getElementsByTagName("script")[0];
var d = document.createElement("script");
d.src = "//site.com/js.js?x="+randomh+"";
d.type = "text/javascript";
d.async = true;
d.defer = true;
e.parentNode.insertBefore(d,e);
})();
</script>
Method 2 (AJZane's comment)
Small and robust inclusion. You can see exactly where JavaScript is fired and it is less customisable (to the point) than Method 1.
<script>document.write("<script type='text/javascript' src='//site.com
/js.js?v=" + Date.now() + "'><\/script>");</script>
If you choose to use dates or a random numbers to append to your URI, you will provide opportunities for the end user to be served the same cached file and may potentially expose unintended security risks. An explicit versioning system would not. Here's why:
Why "Random" and Random Numbers are both BAD
For random numbers, you have no guarantee that same random number hasn't been generated and served to that user before. The likelihood of generating the same string is greater with smaller "random" number sets, or poor algorithms that provide the same results more often than others. In general, if you are relying on the JavaScript random method, keep in mind it's pseudo-random, and could have security implications as well if you are trying to rely on uniqueness for say a patch in one of your scripts for XSS vulnerabilities or something similar. We don't want Johnny to get served the old cached and unpatched JS file with an AJAX call to a no-longer trusted 3rd-party script the day Mr. Hacker happened to be visiting.
Why dates or timestamps are bad too, but not as bad
Regarding Dates as "unique" identifiers, JavaScript would be generating the Date object from the client's end. Depending on the date format, your chances for unintended caching may vary. Date alone (20160101) allows a full day's worth of potential caching issues because a visit in the morning results in foo.js?date=20160101, and so does a visit in the evening. Instead, if you specify down to the second (20160101000000) your odds of an end user calling the same GET parameter go down, but still exist.
A few rare but possible exceptions:
Clocks get reset (fall behind) once a year in most time zones
Computers that reset their local time on reboot for one reason or another
Automatic network time syncing causing your clock to adjust backwards a few seconds/minutes whenever your local time is off from the server time
Adjusting time zones settings when traveling (The astronauts on the IIS travel through a zone every few minutes...let's not degrade their browsing experience :P)
The user likes resetting their system clock to mess with you
Why incremental or unique versioning is good :)
For a fontend only solution, my suggestion would be to set an explicit version, which could be simply hard-coded by you or your team members every time you change the file. Manually doing exactly as you had done in your same code of your question would be a good practice.
You or your team should be the only ones editing your JS files, so the key take away isn't that your file needs to be served fresh every time, I just needs to be served fresh when it changes. Browser caching isn't a bad thing in your case, but you do need to tell the end user WHEN it should update. Essentially, when your file is updated, you want to ensure the client gets the updated copy. With this, you also have the added bonus of being able to revert to previous versions of your code without worry of client caching issues. The only drawback is you need to use due diligence to make sure you actually update the version number when you update your JS files. Keep in mind just because something isn't automated, doesn't mean it is necessarily bad practice or poor form. Make your solution work for your situation and the resources you have available.
I suggest using a form like Semantic Versioning's rules to easily identify backwards or breaking compatibility by looking at the file name (assuming nobody in the development process fudged up their version numbering) if possible. Unless you have an odd use case, there is no good reason to force a fresh copy down to the client every time.
Automated version incrementing on the client side with Local Storage
If what you were after was frontend way to automate the generation of a unique version number for you so you don't have to explicitly set it, then you would have to implement some sort of local storage method to keep track of, and auto increment your file versions. The solution I've shown below would lose the ability for Semantic versioning, and also has the potential to be reset if the user knows how to clear Local Storage. However, considering your options are limited to client-side only solutions, this may be your best bet:
<script type="text/javascript">
(function(){
/**
* Increment and return the local storage version for a given JavaScript file by name
* #param {string} scriptName Name of JavaScript file to be versioned (including .js file extension)
* #return {integer} New incremented version number of file to pass to .js GET parameter
*/
var incrementScriptVer = function(scriptName){
var version = parseInt(localStorage.getItem(scriptName));
// Simple validation that our item is an integer
if(version > 0){
version += 1;
} else {
// Default to 1
version = 1;
}
localStorage.setItem(scriptName, version);
return version;
};
// Set your scripts that you want to be versioned here
var scripts = ['foo.js', 'bar.js', 'baz.js'];
// Loop through each script name and append our new version number
scripts.map(function(script){
var currentScriptVer = incrementScriptVer(script);
document.write("<script language='text/javascript' type='text/javascript' src='http://yoursite.com/path/to/js/" + script + "?version=" + currentScriptVer + " '><\/script>");
});
})();
</script>
I'm going to mention for completeness, if you are converting from an old system of generating "random" numbered or dated GET variables, to an incrementing versioned system, be sure that you will not step over any potentially randomly generated files names with your new versioning system. If in doubt, add a prefix to your GET variable when changing methods, or simply add a new GET variable all together. Example: "foo.js?version=my_prefix_121216" or "foo.js?version=121216&version_system=incremental"
Automated versioning via AJAX calls and other methods (if backend development is a possiblity)
Personally, I like to stay away from local storage options. If the option is available, it would be the "best" solution. Try to get a backend developer make an endpoint to track JS file versions, you could always use the response to that endpoint determine your version number. If you are already using version control like Git, you could optionally have on of your Dev Ops team bind your versioning to your commit versions for some pretty sweet integration as well.
A jQuery solution to a RESTful GET endpoint might look like:
var script = "foo.js";
// Pretend this endpoint returns a valid JSON object with something like { "version": "1.12.20" }
$.ajax({
url: "//yoursite.com/path/to/your/file/version/endpoint/" + script
}).done(function(data) {
var currentScriptVer = data.version;
document.write("<script language='text/javascript' type='text/javascript' src='http://yoursite.com/path/to/js/" + script + "?version=" + currentScriptVer + " '><\/script>");
});
Insert the script dynamically via document.createElement('script'), then when you set the URL, you can use new Date().getTime() to append the extra parameter.
If you are worried about your javascript executing before the script is loaded, you can use the onload callback of the script element (note that there are a few hoops to jump for IE though)
If you can't user server side code then you can use getScript method to do the same.
$(document).ready(function(){
var randomNum = Math.ceil(Math.random() * 999999);
var jsfile = 'scripts/yourfile.js?v=' + randomNum;
$.getScript(jsfile, function(data, textStatus, jqxhr) { });
});
Reference URL: http://api.jquery.com/jQuery.getScript/
(Please don't forget to mark as answer.)
Load scripts manually or with jQuery http://api.jquery.com/jQuery.getScript/. It also provides option to prevent chaching
You can replace the source of the script doing this with pure Javascript
// get first script
var script = document.getElementsByTagName('script')[0]
var new = document.createElement("script");
// add the source with a timestamp
new.src = 'yoursource.js?' + new Date.getTime().toString();
new.type = 'text/javascript'
script.parentNode.insertBefore(new,script);
Replace regular expression if not alphanumeric
Date.prototype.toISOString()
var today = new Date();
"MyFile_" + today.toISOString().replace(/[^\w]/g, "") + ".pdf"
MyFile_20191021T173426146Z.pdf
Old post but here is a one liner:
<script src="../Scripts/source/yourjsname.js?ver<%=DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>

Using javascript for pinging a webapp to keep session open

I'm writing a greasemonkey script to keep session open on a webapp I use for work.
Which javascript command would you use to create some feedback with the server and ensure the session doesn't fall without having to bother the user making a complete refresh of the page?
I've solved the issue using:
function keepAlive() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/restricted_file_url");
httpRequest.send(null);
}
setInterval(keepAlive, 840000); //My session expires at 15 minutes
Using some tips from Jesse's answer, here's the complete code.
You will need to update the #match param with your site's domain
// ==UserScript==
// #name Auto session extender
// #namespace http://obive.net/
// #version 0.2
// #description Automatically extend server-side session
// #author Charlie Hayes
// #match http://obive.net/
// #grant GM_getValue
// #grant GM_setValue
// #noframes
// ==/UserScript==
(function() {
'use strict';
console.log('The session for this site will be extended automatically via userscript.');
var minute = 60*1000;
var refreshTime = 15 * minute;
var iframe = document.createElement("iframe");
iframe.style.width = 0;
iframe.style.height=0;
var loc = window.location;
var src = loc.protocol +'//' + loc.host + loc.pathname;
src += loc.search ? (loc.search + '&') : '?';
src += 'sessionextendercachebuster=';
var reloadIframe = function(){
var time = new Date().getTime();
var lastRefresh = GM_getValue('lastRefresh');
var timeSinceLastRefresh = time - lastRefresh;
if (!lastRefresh || timeSinceLastRefresh > refreshTime - minute) {
console.log('Auto-extending session');
iframe.src = src + time;
GM_setValue('lastRefresh',time);
setTimeout(reloadIframe, refreshTime);
setTimeout(function(){
// Unload the iframe contents since it might be taking a lot of memory
iframe.src='about:blank';
},10000);
}else{
console.log('Another tab/window probably refreshed the session, waiting a bit longer');
setTimeout(reloadIframe, refreshTime - timeSinceLastRefresh - minute);
}
};
setTimeout(reloadIframe, refreshTime);
document.body.appendChild(iframe);
})();
Second choice
If you absolutely insist on using Greasemonkey, any element.click() method on any event that submits an XMLHTTPrequest should do.
First choice
If you are willing to use a solution that does not require you to write a Greasemonkey script:
ReloadEvery 3.0.0, by Jaap Haitsma
This reloads web pages every so many seconds or minutes. The function is accessible via the context menu (the menu you get when you right click on a web page) or via a drop down menu on the reload button.
It's not what you asked for, but unless you simply want to brush up on your javascript skills, this is probably the most straight-forward method for solving your problem.
If you want to write JavaScript to solve this (the other answers are a lot easier and I would recommend going the easier route), here's what I would do:
Call document.createElement("iframe") to create an iframe
Size the iframe to 0x0, style.display = "none", set the ID to something, and set the src property to a page on the site that will extend your session
Use document.body.appendChild to add the iframe to the page
Using setTimeout refresh the iFrame using window.frames['iframeID'].location.reload(true); and also call setTimeout to refresh the page again.
See if the other answers would work because using JavaScript seems like it would be more trouble than it's worth.
I can definitely recommend the solution suggested by dreftymac!
If you don't want to worry about remembering to click the reloadevery option, your grease monkey script is simply
window.location.href = window.location.href
This is presuming you don't want to keep the page constantly refreshing, as suggested by others.
Ordinarily, if you were simply looking to ping the server, you would probably do best to do something like use an image that you know exists on the remote server, and check it's height - thus creating traffic.
However, your problem (I presume) needs to access some limited area of the website, in order to keep the session active... with this being the case (and the fact that you can't directly ping), find a page that is 'restricted' and do an Ajax call, or similar. Don't quote me on this, as I'm by no means a JavaScript expert... just throwing out a potential solution.

Categories