[英]how to pass variables between 2 php files
我有两个php文件,用于对活动目录用户进行身份验证,我想从中获取属性url
,如果该函数返回true,则该值$data
从authenticate.php
传递到login.php
到header("Location: *URL*");
,如何才能做到这一点?
authenticate.php:
<?php
// Initialize session
session_start();
function authenticate($user, $password) {
if(empty($user) || empty($password)) return false;
// Active Directory server
$ldap_host = "CRAMSDCR01V.cloud4rain.local";
// connect to active directory
$ldap = ldap_connect($ldap_host);
$ldap_dn="OU=by-style,DC=cloud4rain,DC=local";
// verify user and password
if($bind = @ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
echo $data["url"];
return true;
}
else
{
// invalid name or password
return false;
}
}
?>
login.php:
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// check to see if login form has been submitted
if(isset($_POST['btn-login'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
header("Location: authenticate.php?$data");
die();
} else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br /-->";
}
}
// output logout success
if(isset($_GET['out'])) echo "Logout successful";
?>
login.php
<?php
include("authenticate.php");
从本质上讲,这就像将authenticate.php的内容粘贴到login.php中一样 ,尽管从技术上讲它是2个文件,但它的作用就像是一个文件-但是$data
是在authenticate()
函数中定义的,因此仅在该函数范围内 。
在authenticate.php中 -从函数返回数据
// verify user and password
if($bind = @ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
// echo $data["url"]; // I assume this is just for debugging...
// return $data from the function which should be "truthy"
return $data;
}
else
{
// invalid name or password
return false;
}
在login.php中 -评估authenticate()
函数的返回值-由于PHP松散地键入,因此该函数返回的任何(非空)字符串都可以被评估为“真实” -您从该函数获得的唯一其他返回值是false
...
// run information through authenticator
if($authData = authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
// renamed the variable $authData just for clarity
header("Location: authenticate.php?$authData");
die();
}
else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br />";
}
不知道为什么会有$_SESSION = array();
在login.php中,但是如果要将$ data从一个php传递到另一个php,则只需在会话中将其设置为
$_SESSION['data'] = $data;
ang在其他文件中使用它
$data = $_SESSION['data'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.