The PHP code below echoes a link if the "loginid" of the logged-in user is on a list determined by getEditorList();. It works fairly well, but I think it might work better if I were to do it with Javascript instead.
How could I accomplish the same thing with Javascript?
Thanks in advance,
John
$editors = getEditorsList();
foreach($editors as $editor)
{
$editorids[] = $editor['loginid'];
}
if(in_array($_SESSION['loginid'], $editorids))
{
echo "<div class='footervote'><a href='http://www...com/.../footervote.php'>Vote</a></div>";
}
Login function:
<?php
if (!isLoggedIn())
{
if (isset($_POST['cmdlogin']))
{
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
} else
{
echo "Incorrect Login information !";
show_loginform();
}
} else
{
show_loginform();
}
} else
{
show_userbox();
}
?>
So actually, your problem is "After a user logs in, he often still gets the non-logged in version of the pages", and you propose the "Make the link appear in Javascript" as a solution. Then you ask how to do that :)
RoToRa already pointed out that the cause of your problem probably has to do with the browser cashing the pages, and not requesting a new page after the user has logged in, but showing the old page from cache. There are several solutions for this, even with Javascript.
To avoid caching:
Add a 'Pragma: No-Cache' header to your page.
Add a 'Expires: -1' header to your page.
Use the Cache-Control HTTP headers from HTTP 1.1
Check the PHP header function for more information how to do that in PHP, or read your webservers documentation.
Another possible solution is to have the page serve as static, and then use AJAX to check if the user is logged-in, and if so, load the custom content for that user. Typically you'll create an extra php-script to check if the user is logged in, and have the AJAX call this script. This is quite easy to do using a decent Javascript library like jQuery, but you can do it without libraries should you really need to do so.
Checkout PHP JSON, jQuery AJAX for more info about those solutions.
A last often (ab)used solution is to have a query string for your page - browsers will see the query string is different, and won't cache the page.
Related
Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>
I need to redirect all traffic on my WordPress site to the homepage if not requested by AJAX, but I need to use the requested path after redirect.
I have redirection working via wp_redirect php and a template_redirect hook, however I can't read the REQUEST_URI to save it via cookie or header or anything.
As soon as wp_redirect is called it seemingly prevents me from ever reading the details of the request, pre redirect. Comment out the wp_redirect and it reads just fine.
Is there something I'm missing here, or a better way to go about it? I have a one page site that is loading content via AJAX.
add_action('template_redirect', 'pass_along_request_uri', 1);
function pass_along_request_uri() {
// $_SERVER['REQUEST_URI'] is the path as expected only if the future wp_redirect is not called...
}
add_action('template_redirect', 'redirect_to_homepage', 10);
function redirect_to_homepage() {
if (!is_front_page() && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
wp_redirect(home_url(), 301);
exit;
}
}
EDIT;
Only had 2 functions for testing, since logging $_SERVER['REQUEST_URI'] wasn't making sense to me. Thinking if I put the log at priority 1, it should be logged BEFORE the redirect happens with the priority 10 function.
However it doesn't. Doesn't matter when or where it seems, calling wp_redirect seemingly clears the original request data.
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
console_log($_SERVER['REQUEST_URI']);
Logs say "/path/to/page" when not calling wp_redirect, once wp_redirect is in the chain it only spits out "/" (the redirected path).
I'm thinking it has something to do with how actions are queued up with add_action? I don't know WordPress well unfortunately.
Thanks!
Your mistake here was the way you are actually logging this.
The console.log(...) executes on the client side - but there it can't log while you are doing your redirect elsewhere (you can not send output for the browser to interpret, like your script element, and redirect at the same time.)
What you are seeing is the result of that same logging code, executed via the request after your redirect.
Easiest way to achieve what you want, would probably be to stick the REQUEST_URI value into a session. You might have to start one then for that purpose, because WP does not use a "traditional" session by default.
I have two possible sets of information to export to another PHP page whenever i click a button.
One of them is a session. It's something like this:
$_SESSION['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_SESSION['excel_array']['Main_']['Plan1'] = array();
The post data sends the same information, but doesn't save it in a session to prevent conflict between too many sessions. So what i want to try, is to check if there is a session set. If there is, i'll unset it, and send the $_POST data. When there isn't, i'll set one. I have tried doing this:
session_start();
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Main_']);
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_POST['excel_array']['Main_']['Plan1'] = array();
} else {
$_SESSION['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_SESSION['excel_array']['Main_']['Plan1'] = array();
}
The logic might seem a little weird for some of you, but i'm almost certain it would work... But. I wanted to do this in a button. Reason being, whenever i click the button, I export the information to the next PHP page. I want to check for these conditions before sending the information, not in the moment i load the page.
Is it possible?
There is several way to do it, but before reading my answer, please note that javascript verification can be edited and exploited maliciously.
You could do an AJAX request to a php page that would implement your logic and return a code 200 or 401. Then you can act before the next page loads.
Is there a way to do a one time redirect? Where it goes to an entrance page, and says enter site, then you go to the index.html page.
the best example of what I'm trying to accomplish: www.matisyahuworld.com
There's a page order.html that's the first page you see before you can go to the index.html page
thanks
Yes, you would have to check if the user is new or not. The only way I know how to do that is to use javascript cookies :)
document.cookie = 'unique_user = second time visitor;
expires = date you want; path=/'
Of course everything is made easier with jQuery:
$.cookie("example", "foo");
The logic would be, check if your cookie exists within the clients browser, if it does, don't put up splash page and redirect straight to index.html. If there is no cookie send it to splash, splash.html, and set the cookie there.
Here is a great resource on how to do that:
Javascript Cookies
setcookie is more simple to use:
$expire=time()+60*60*24*30;
setcookie(user,visited, $expire);
if(isset($_COOKIE["user"]))
{
RedirectToURL("index.html");
}
To create function RedirectToURL
function RedirectToURL($url)
{
header("Location: $url");
exit;
}
NOTE : Above code can be used for PHP scripting.Yet it is simple .Just add the above lines in
<?PHP
and end with
?>
also you must save the file with .php extension
i need to change something in my site, if some fields changed in database, but without reloading the page! but i have no idea how i can do it.
could you give me an idea? thanks
example:
for example, i have a forum, and i need to show a image, if new comment resieved! i can write all functions, but i don't understand when i must call the function?
maybe window.onload?
Then you need AJAX!
Explanation:
You need two pages, the main page which does not "reload". And a second one which returns two versions of the small image based on the database field.
Page one has this JavaScript in it:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
/* normal ajax without periodical refresh
$.ajax({
url: 'page2.php',
success: function(data) {
$('#database_status').html(data);
}
});
*/
var refreshId = setInterval(function() {
$('#database_status').load('/path/to/your.php');
}, 3000);
</script>
// Or you use the jQuery plugin Heartbeat: http://www.jasons-toolbox.com/JHeartbeat/
And a div <div id="database_status">empty</div>
The second page, returns a image tag based on the database setting for example in PHP:
<?php
// do db request
if ($request) {
echo '<img src="true.gif"> TRUE';
} else {
echo '<img src="false.gif"> FALSE';
}
Ajax
Once you've familiarized yourself with the concept, you can reference the jQuery AJAX documentation for information on how to implement it with jQuery.
You can use jQuerys load- or JSON-method to get data from your server.
In your case the following scenario is possible:
The site loads.
Your JavaScript loads the initial data from the server.
Now, every couple of seconds or minutes (Depending on your use case), the JavaScript asks the server if anything changed since it last asked (Use timestamps in your request, for example).
If so, change the website accordingly.
Goto 3.
Please keep in mind that excessive polling might but enormous strains on your server, especially if you have a lot of users. Long-polling or Comet are advanced techniques to handle the load.
The easiest way to perform an ajax request with jquery is the load method. On that page you can also see plenty of examples.
There are two basic approaches you can take:
Use setInterval to make an Ajax request periodically that ask the server if there are any updates.
Use Comet to fake server push
Try Ajax, e.g: using jquery which allows you to handle those in a high level js.
example in this site when you do the send email