单击更改 PHP 会话值


change php session value by click

我想通过单击为会话提供一个值

我试图这样做,但它不起作用:

<?php session_start(); 
$_SESSION['role']="";?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
<title></title>
<link href="auth-buttons.css" rel="stylesheet" />
<link href="StyleSheet.css" rel="stylesheet" />
   </head>
<body>
<div id="wrap">
<div id="wrapHome">
<p><a class="btn-auth btn-facebook large" href="redirect.php" onclick="<?php $_SESSION['role']="facebook" ?>" > Sign in with <b>Facebook</b> </a></p>
<p><a class="btn-auth btn-twitter large" href="redirect.php" onclick="<?php $_SESSION['role']="twitter" ?>" > Sign in with <b>Twitter</b> </a></p>
<p><a class="btn-auth btn-google large" href="redirect.php" onclick="<?php $_SESSION['role']="google" ?>" > Sign in with <b>Google</b> </a></p>
</div>
</div>
</body>
</html>

一个可能的解决方案是在重定向中添加一个 GET 参数.php并在重定向.php中更改 SESSION 变量。

更改以下内容:

<p><a class="btn-auth btn-facebook large" href="redirect.php" onclick="<?php $_SESSION['role']="facebook" ?>" > Sign in with <b>Facebook</b> </a></p>
<p><a class="btn-auth btn-twitter large" href="redirect.php" onclick="<?php $_SESSION['role']="twitter" ?>" > Sign in with <b>Twitter</b> </a></p>
<p><a class="btn-auth btn-google large" href="redirect.php" onclick="<?php $_SESSION['role']="google" ?>" > Sign in with <b>Google</b> </a></p>

自:

<p><a class="btn-auth btn-facebook large" href="redirect.php?role=facebook"> Sign in with <b>Facebook</b> </a></p>
<p><a class="btn-auth btn-twitter large" href="redirect.php?role=twitter"> Sign in with <b>Twitter</b> </a></p>
<p><a class="btn-auth btn-google large" href="redirect.php?role=google"> Sign in with <b>Google</b> </a></p>

并将其添加到重定向的顶部.php

<?
session_start(); 
$_SESSION['role']=$_GET['role'];
?>

'onclick' 不会触发 PHP 代码。不过它会触发javascript。您可以使用javascript对php页面进行AJAX调用,该页面又能够设置会话值(ajax将帮助您这样做,而无需在单击按钮时刷新页面。

#('.btn-auth btn-facebook large').click(function(){
// fire off the request to /redirect.php
request = $.ajax({
    url: "/redirect.php",
    type: "post",
    data: 'facebook'
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
    // log a message to the console
    console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
    // log the error to the console
    console.error(
        "The following error occured: "+
        textStatus, errorThrown
    );
    });
});

在您的重定向中.php

<?php
$_SESSION['role'] = $_POST['data'];
?>

您还可以添加另一个 php 文件来更改会话变量。

喜欢这个:

<p><a class="btn-auth btn-facebook large" href="pass.php"> Sign in with <b>Facebook</b> </a></p>

pass.php中,您必须添加以下代码:

<?php
    session_start();
    $_SESSION['role']="facebook"; 
    header("Location: your_first_php.php");
?>