在 PHP 中使用 javascript 设置会话变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3590293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Session variable using javascript in PHP
提问by Sanjay Khatri
Is it possible to set PHP session variables using Javascript?
是否可以使用 Javascript 设置 PHP 会话变量?
采纳答案by BGabesz
In JavaScript:
在 JavaScript 中:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
在 session_write.php 文件中:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
在 HTML 中:
<div id='div_session_write'> </div>
回答by Darin Dimitrov
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:
会话存储在服务器端,因此您无法从 JavaScript 向其添加值。您在客户端获得的只是包含 id 的会话 cookie。一种可能性是将 AJAX 请求发送到将设置会话变量的服务器端脚本。jQuery.post()方法的示例:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
当然,您应该小心暴露此类脚本。
回答by Lèse majesté
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.
如果您希望允许客户端对持久数据进行操作,那么最好只使用 cookie。这就是cookies的设计目的。
回答by dako
or by pure js, see also on StackOverflow : JavaScript post request like a form submit
或者通过纯 js,也可以在 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.
但是为什么要尝试用 js 设置 $_session 呢?任何 JS 变量都可以由玩家使用一些 3rd 方工具(firebug)修改,因此任何玩家都可以修改 $_session[]! 而且 PHP 不能给 js 任何秘密代码(甚至[滚动]加密)返回,它都是可见的。jquery或者AJAX都帮不上忙,到头来都是js。
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.
这在网络游戏设计中经常发生。(也许有点博弈论?原谅我,我有一个大师并且喜欢使用理论:))就像在crimegameonline.com中一样,我用PHP初始化了一个小游戏拼图,将初始板保存在$_SESSION['foo'中]。然后,我使用 php [make html that] 显示初始拼图开始。然后,js 接管,在玩家移动时观察按钮和修改元素 xy。我不想玩客户端 - 服务器(如 WOW)并询问服务器“嘿,我的玩家想要移动到 xy,我该怎么办?”。这是很多带宽,我不想要涉及的服务器。
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.
每次玩家出错(或死亡)时,我都可以发送 POST。播放器可以阻止传出 POST(并更改本地 JS 变量以使其忘记输出计数)或简单地修改传出 POST 数据。是的,人们会这样做,特别是如果涉及真钱。
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.
如果游戏很小,您可以发送每个移动(按钮单击)的后更新,单向,以及最后两个移动的后变量。然后,服务器完整性检查最后并在 $_SESSION['allMoves'] 中添加新内容。如果游戏很大,您可以发送所有先前移动的“中途”更新,并查看它是否与最终更新列表中的匹配。
Then, after a js thinks we have a win, add or mod a button to change pages:
然后,在 js 认为我们赢了之后,添加或修改一个按钮来更改页面:
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).
然后新页面的 PHP 查看 $_SESSION['init'] 并通过每个 $_SESSION['allMoves'] 播放,看看它是否真的是赢家。服务器(PHP)必须决定它是否真的是赢家,而不是客户端(js)。
回答by Paul Dixon
You can't directly manipulate a session value from Javascript - they only exist on the server.
您不能直接从 Javascript 操作会话值 - 它们只存在于服务器上。
You could let your Javascript get and set values in the session by using AJAX calls though.
您可以让您的 Javascript 通过使用 AJAX 调用在会话中获取和设置值。
See also
也可以看看
回答by Shashidhara
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.
设置会话变量的一种简单方法是将请求发送到另一个 PHP 文件。这里不需要使用 Jquery 或任何其他库。
Consider I have index.phpfile where I am creating SESSIONvariable (say $_SESSION['v']=0) if SESSIONis not created otherwise I will load other file.
考虑我有index.php文件,我在其中创建SESSION变量(比如$_SESSION['v']=0),如果SESSION没有创建,否则我将加载其他文件。
Code is like this:
代码是这样的:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.htmlI want to set this session variable to 1.
现在在count.html 中,我想将此会话变量设置为 1。
Content in count.html
count.html 中的内容
function doneHandler(result) {
window.location="setSession.php";
}
In count.htmljavascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
在count.htmljavascript 部分,将请求发送到另一个 PHP 文件(比如setSession.php),我可以在其中访问会话变量。
So in setSession.phpwill write
所以在setSession.php中会写
session_start();
$_SESSION['v']=1;
header('Location:index.php');
回答by Payam Azadi
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!
现在攻击者只需更改 putIntoSession 的值并提交表单十亿次即可。繁荣!
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.
如果您采用创建 AJAX 服务的方法来执行此操作,您需要确保强制执行安全性以确保无法发出重复请求、截断接收到的值并进行一些基本的数据验证.
回答by Joacer
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.
我使用Ajax解决了这个问题。我所做的是对 PHP 页面进行 ajax 调用,其中传递的值将保存在会话中。
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.phpis as following:
而GuardarNumElems.php是如下:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>
回答by Lucky13
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.
不可能。因为 JavaScript 是客户端,而 session 是服务器端。要执行与 PHP 会话相关的任何操作,您必须转到服务器。

