PHP doesn't see a cookie unless I refresh the page again - javascript

I know there are other questions like this on here, but I've read through the answers and I'm still not finding a solution to my issue.
All of these scripts are on the same page, search-results.
It shows results in data-tables, and lets the user select records to save to a list, which they can then print. The IDs of the selected records are stored in a records cookie. I can see that this works.
There's a link at the bottom of the page that fires this JS function:
function resultsPage(){
window.location = "/search-results/?printqueue=true";
}
As you can see, this is the same page, but with a different parameter. This tells the page to display their saved results.
On the initial load with ?printqueue=true PHP cannot read the cookie, even tho the page has refreshed. I have to refresh (or click the link) AGAIN before PHP picks up the cookie. Why?
I'm getting the cookie data like this:
if( $_GET['printqueue'] == 'true' && $_COOKIE['records'] !== 'undefined' ) {
$posts_to_show = explode(',',$_COOKIE['records']);
}
If that's just because of the order of operations, that's cool, nothing to do about it then. But any clean ways to "double refresh" the page without adding an extra parameter and refreshing again if it's present? I'd really hate to do that...

I beleieve its becouse $_COOKIE['records'] is not set yet..
Try:
if( $_GET['printqueue'] == 'true' && isset($_COOKIE['records']) ) {
// your code
}

Related

Conceal URL in javascript code ( URL generated by PHP )

I am looking for a solution to the following:
I have a piece of JS code, that performs a redirection to a URL that is constructed with PHP, and that redirection is only done when the user presses a button on a confirmation dialog.
The code is, as follows:
function one() {
window.location.replace("<?php
if($new_redir == "1") {
echo "$new_second_redirect_URL/?token=$hash";
}
else {
echo "$second_redirect_URL/?token=$hash";
}
?>");
}
It works perfectly fine. What I wanna do is conceal the URL that is displayed in the source code when a user opens the page.
What would be the best way to do that?
You're thinking too much into this to be honest.
If they want to avoid the confirmation screen and get the URL from the source, there's not really much you could do.
The best really is possibly performing an AJAX request on confirmation and getting a CSRF token based URL from the response and using that, but that could end up being overkill as well.
You could also make it into an actual <form></form> form with a few hidden fields (again, such as a CSRF token), and perform the post validation onclick. If it a success - redirect them.
UPDATE:
Use robots.txt to stop bots
Build the QS with JS to stop most bots, something like:
var csrftoken='XJIWHEOU324uipHFOFUHR';
var url="http://url.com/page.php?token=";
url=url+csrftoken;
What you could also do, is something like us actually, although for your use case it could be too much.
Log every single page load into the DB, and check if if they're a first time visitor to the page after confirmation.
AJAX call (jQuery example):
$.post( "url_to_backend_page_to_get_url", {hasSubmittedForm:"true"}, function( data ) {
window.location.href = data;
});

Use URL to jump to a page in AJAX

My website structure is as follows:
public_html/
- index.php
- students.php
The user loads the site (index.php) which contains a button. When this button is clicked AJAX is used to load "students.php" and it is displayed to the user (As if they just went to a different page seamlessly). When doing so the following JavaScript is run:
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
This adds a state to the browsers history and causes the browsers URL to display "example.com/students" instead of "example.com". However if a user was to refresh at this point, nothing would load (404 Not Found) due to the folder "students" not actually existing.
My question is, how can I get the users browser to actually display "index.php" and automatically take them to the students page. In other words, the user refreshes "example.com/students" and what actually happens is the user is taken to the index.php file and the AJAX automatically takes them to the students page (As though they actually refreshed the page)
Note: I am aware I can pass null to the url parameter in "pushState()" however this URL behaviour is desired as it would allow users to quickly jump to a page (If I can get it working)
The full code to show the students page via AJAX is as follows:
/**
* Display students screen.
*/
function displayStudents(createState) {
if(typeof(createState)==='undefined') {
createState = true;
}
$("#container").css("width", $( window ).width());
$("#container").css("position", "fixed");
$("#container").animate({marginLeft: "-100%"}, ANIMATION_SPEED);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#container").css("margin-left", "100%");
$("#container").html(xmlhttp.responseText);
$("#container").animate({marginLeft: "0"}, ANIMATION_SPEED, null, function reset() {
$("#container").css("width", "100%");
$("#container").css("position", "relative");
});
if(createState) {
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
}
}
};
xmlhttp.open("GET", "students.php", true);
setTimeout(function() { xmlhttp.send(); }, ANIMATION_SPEED);
}
Most of the code here is for animation.
In other words, the user refreshes "example.com/students" and what actually happens is the user is taken to the index.php file and the AJAX automatically takes them to the students page (As though they actually refreshed the page)
The point of pushState is that when you use JavaScript to transform the state of the page, you provide a URL which the server can use to deliver some HTML that will provide the page in that state.
If you are always going to serve up the homepage and then transform it with JavaScript, then just use hashbangs. pushState is entirely the wrong tool for the job.
If you were to use pushState, then a pseudocode implementation of a possible approach would be along the lines of:
GET data needed for the page
IF `Accept` header prefers `application/json`
Output `Content-Type: application/json` header
Output data in JSON format
ELSE
Output `Content-Type: text/html` header
Pass data through the template for the page
Output template as HTML
And you would use students.php in the URL instead of students (or you would make students resolve to the PHP code you wanted to run instead).
Since you are using raw XMLHttpRequest, you will need to use setRequestHeader to set the Accept header. You are using jQuery though, so you could just use $.ajax and pass it dataType: "json".

On page load redirect to the same page with querystring

Hi so i am getting a cookie passed in from another website which brings in some data i need to put in the query string.. i know how to put it in the query string that's not my questions.
My question is what jquery function can i use onpage load which will redirect to the query string.. now i don't want to page to load twice i want this to happen and look like it has only loaded once. I have tried to use a .one jquery but that's not needed anymore as the if statement will validate if the query string needs to change. Also that function is not working correctly anyway.
$(document).one('load', function() {
if (window.location.pathname == '/items.aspx'){
window.location.replace("items.aspx?item1=a80af972-4f78-de11");
}
});
any ideas would be great.
Thanks
You could use window.location.href="items.aspx?item1=a80af972-4f78-de11"but that will also reload the page. Depending on your users internet connection it could seem like one page load.
Another thing worth noting: You are waiting for $(document).on("load") which gets fired when the page is loaded which is exactly what you don't want.
Try this for speed increase:
$(document).ready(function() {
if (window.location.pathname == '/items.aspx'){
window.location.href = "items.aspx?item1=a80af972-4f78-de11";
}
});
Still - this is a thing to do on the server side. Something in the backend like "if item1 is undefined load item a80af972-4f78-de11" would be best.

Is it possible to delete an entire Webpage when the user navigates away?

If the user navigates off the webpage, is it possible to execute a php script?
I know that Javascript can be executed..
$(window).bind('beforeunload', function(){
return 'DataTest';
});
Cookies might work, but I am not sure how a listener could track an expired cookie, and then delete the correct webpage.
A sample file system is like this:
user0814HIFA9032RHBFAP3RU.php
user9IB83BFI19Y298RYBFWOF.php
index.php
listener.py
data.txt
Typically, to create the website, php writes to the data.txt and the Python listener picks up this change, and creates the file (user[numbers]). As you might think, these files stack up overtime and they need to be deleted.
The http protocol is stateless, therefore users simply can not "navigate away".
The browser requires a page, the server returns it, and the communication stops.
The server doesn't have reliable methods to know what the client will do with that page.
Disclaimer: I'm not sure, as Fox pointed out, that this is the right way to go in your case. I actuallly upvoted Fox's answer.
However, if you absolutely need to delete each page right after the user left it, use this:
$(window).bind('beforeunload', function() {
$.ajax('yourscript.php?currentUser=0814HIFA9032RHBFAP3RU');
});
Then in yourscript.php, put something like the following:
<?php
// load your userId (for example, with $_SESSION, but do what you want here)
$actualUser = $_SESSION['userId'];
// checks if the requested id to delete fits your actual current user's id
if (isset($_GET['currentUser'] && $_GET['currentUser'] == $actualUser)
{
$user = $_GET['currentUser'];
$file = 'user'.$user.'.php';
unlink($file);
}

How Can I Insert A Value With Javascript (or PHP) Into a Form Depending On Visitor Referral

I'm not sure if the way to do this is check Google Analytics cookies or otherwise track where a user came to my site from. Basically I have a form with a hidden field code="XY1" Now I need to be able to insert a different preset code for say people who came from Facebook, so the script would have to check where the visitor came from and then assign a code XF1 to any from FB, and a code XT1 to any from Twitter, etc.
Would something like this PHP work for the capture?:
$referringPage = parse_url( $_SERVER['HTTP_REFERER'] );
if ( stristr( $referringPage['host'], 'facebook.com' ) )
Or this JS
var ref = document.referrer;
if (!ref.indexOf("facebook.com") != -1) {
document.write(...)
}
I'm not sure what is the best way to do it and what kind of methods can reliably check the source of a visitor, so any help would be greatly appreciated.
You can use $_SERVER['HTTP_REFERER'], but it's not guaranteed to be accurate, or even present. Not all browsers will necessarily set it, and some allow you to set it yourself. Google cookies won't contain any site history, and you can't examine the browser history, so there's no guaranteed way to do what you're asking.
You can try this option using jquery $.test() method.
$(function(){
var referer=document.referrer, //option 1
//referer="<?php echo $_SERVER['HTTP_REFERER'];?>",//optional 2
XFB=/facebook.com/g,
XFT=/twitter.com/g,
checkF1=XFB.test(referer),
checkF2=XFT.test(referer);
if(checkF1){
var code= "XF1";
$('#hiddenInput').attr('value','ref: '+referer)
}
else if(checkF2){
var code= "XT1";
$('#hiddenInput').attr('value','ref: '+referer)
}
});

Categories