我正在尝试通过仅使用一个成员区来保护页面,在这种情况下我使用的代码是
<?php
include 'dbc.php';
page_protect();
?>
使用此代码没有错误,它只是工作正常 但问题是每当我将下面的代码放在同一页面中时 问题会发生在iPhone上,只有这个设备,但其余的仍然没问题,如PC,笔记本电脑和平板电脑(iPad),他们都没有问题
但iPhone的问题在于您可以在登录后访问该页面,但无论何时刷新它都会将您重定向到登录页面并再次请求登录。
<?php
if(!isset($_GET['link'])){
$link = 1;
} else {
$link = $_GET['link'];
}
if ($link == 1) {
echo "";
} elseif ($link == 23) {
echo "";
} else {
echo "";
}
?>
没有错误显示或任何内容。
我的问题是,无论如何都要保护页面,因为我需要将它作为仅限成员的区域,上面的代码非常重要,需要在页面中。
提前致谢。
这是dbc.php对不起,但我复制了整个脚本并放在这里
<?php
/*************** PHP LOGIN SCRIPT V 2.3*********************
(c) Balakrishnan 2010. All Rights Reserved
Usage: This script can be used FREE of charge for any commercial or personal projects. Enjoy!
Limitations:
- This script cannot be sold.
- This script should have copyright notice intact. Dont remove it please...
- This script may not be provided for download except from its original site.
For further usage, please contact me.
/******************** MAIN SETTINGS - PHP LOGIN SCRIPT V2.1 **********************
Please complete wherever marked xxxxxxxxx
/************* MYSQL DATABASE SETTINGS *****************
1. Specify Database name in $dbname
2. MySQL host (localhost or remotehost)
3. MySQL user name with ALL previleges assigned.
4. MySQL password
Note: If you use cpanel, the name will be like account_database
*************************************************************/
define ("DB_HOST", "xxxxxx"); // set database host
define ("DB_USER", "xxxxxx"); // set database user
define ("DB_PASS","xxxxxxx"); // set database password
define ("DB_NAME","xxxxxx"); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
/* Registration Type (Automatic or Manual)
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1; // set 0 or 1
define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password
//define ("ADMIN_NAME", "admin"); // sp
/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);
/*************** reCAPTCHA KEYS****************/
$publickey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
/**** PAGE PROTECT CODE ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/
function page_protect() {
session_start();
global $db;
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
logout();
exit;
}
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) )
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
/* we double check cookie expiry time against stored in database */
$cookie_user_id = filter($_COOKIE['user_id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {
logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/
if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey) ) {
session_regenerate_id(); //against session fixation attacks.
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_name'] = $_COOKIE['user_name'];
/* query user level from database instead of storing in cookies */
list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
} else {
logout();
}
} else {
header("Location: login.php");
exit();
}
}
}
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}
function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}
function ChopStr($str, $len)
{
if (strlen($str) < $len)
return $str;
$str = substr($str,0,$len);
if ($spc_pos = strrpos($str," "))
$str = substr($str,0,$spc_pos);
return $str . "...";
}
function isEmail($email){
return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
function isUserID($username)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
return true;
} else {
return false;
}
}
function isURL($url)
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}
}
function checkPwd($x,$y)
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }
if (strcmp($x,$y) != 0) {
return false;
}
return true;
}
function GenPwd($length = 7)
{
$password = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function GenKey($length = 7)
{
$password = "";
$possible = "0123456789abcdefghijkmnopqrstuvwxyz";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function logout()
{
global $db;
session_start();
if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
mysql_query("update `users`
set `ckey`= '', `ctime`= ''
where `id`='$_SESSION[user_id]' OR `id` = '$_COOKIE[user_id]'") or die(mysql_error());
}
/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();
/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
header("Location: login.php");
}
// Password and salt generation
function PwdHash($pwd, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($pwd . $salt);
}
function checkAdmin() {
if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}
}
?>
答案 0 :(得分:2)
这是为了更好的格式而在此处发布的评论。
你必须阅读man pages on session_函数的工作!这样做可以节省您的时间和精力。这里的许多人已经给出了关于问题可能来源的提示。首先,在session_start()之前,您无法获得任何输出。 2,make sure you have error reporting turned on in your environnement。
if(!isset($_GET['link'])){
$link = 1;
} else {
$link = $_GET['link'];
}
if ($link == 1) {
echo "";
} elseif ($link == 23) {
echo "";
} else {
echo "";
}
如果您尝试回复任何内容,则帖子顶部的此代码段将始终使您的脚本失败。再次,友好的建议,花15分钟的时间阅读手册。您可以获得有关工作这些方面的更有价值的第一手资料,而不是通过在这里发布懒惰来快速解决问题。再说一遍,我可能不是第一个告诉你的人。
答案 1 :(得分:2)
当前保护脚本的替代方案,我没有使用Cookie:
<?php
//A basic login and session script I just whacked up
session_start();
/**
* cleanit cleans unwanted chars
*
* @param string $input
* @return clean string containing only a-zA-Z0-9.,_ -
*/
function cleanit($input){
return preg_replace('/[^a-zA-Z0-9\.,_ -]/s', '', $input);
}
/**
* auth function called on each page you want protected
*
* @param $_SESSION['user_name'] $logged_in_user
* @param $_SESSION['user_hash'] $hash
* @param $_POST['user'] (when logging in) $username
* @param $_POST['pass'] (when logging in) $password
* @param [login|check|logout] function control $exe
* @return $_SESSION gets set returns LOGGED_IN|ERROR:MULTI:USERS|ACCESS_DENIDE|ACCESS_TIMEOUT|ACCESS_LOGGED_OUT
*/
function auth($logged_in_user,$hash,$username,$password,$exe) {
global $db;
if ($exe=='login') {
//LOGIN////////////////////////////////////////////////
$result = mysql_query('SELECT * from users where username="'.cleanit(mysql_real_escape_string($username)).'" and password="'.cleanit(mysql_real_escape_string(sha1($password))).'"',$db);
$num = mysql_num_rows($result);
if($num=='1') {
session_regenerate_id();
$_SESSION['user_status']='LOGGED_IN';
while ($row = mysql_fetch_array($result)) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = $row['username'];
$_SESSION['user_hash'] = md5($_SERVER['REMOTE_ADDR']);
$_SESSION['user_ip'] = cleanit($_SERVER['REMOTE_ADDR']);
$_SESSION['user_date'] = time();
$_SESSION['user_level'] = cleanit($row['user_level']);
}
$result2 = mysql_query('REPLACE into users values ("'.mysql_real_escape_string($_SESSION['user_id']).'","'.mysql_real_escape_string($_SESSION['user_name']).'","'.mysql_real_escape_string(sha1($password)).'","'.mysql_real_escape_string($_SESSION['user_hash']).'","'.mysql_real_escape_string($_SESSION['user_ip']).'","'.mysql_real_escape_string($_SESSION['user_date']).'","'.mysql_real_escape_string($_SESSION['user_level']).'")',$db);
$return = 'LOGGED_IN';
return $return;
}elseif($num >='2') {
$result = mysql_query('DELETE from users where username="'.mysql_real_escape_string($username).'" and password="'.mysql_real_escape_string(sha1($password)).'"');
$error = 'ERROR:MULTI:USERS';
return $error;
}else {
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_hash']);
unset($_SESSION['user_ip']);
unset($_SESSION['user_date']);
unset($_SESSION['user_level']);
$_SESSION['user_status']=='';
session_destroy();
$return = 'ACCESS_DENIDE';
return $return;
}
return $return;
}
if($exe=='check') {
//CHECK////////////////////////////////////////////
$result = mysql_query('SELECT hash,ip,user_date from users where username="'.mysql_real_escape_string($logged_in_user).'" and hash="'.mysql_real_escape_string($hash).'"',$db);
if(mysql_num_rows($result)==1) {
$rows = mysql_fetch_row($result);
$timeout = (time()-1800);
if($rows[2]<=$timeout){auth("","","","","logout");
return'ACCESS_TIMEOUT';
}
if($hash==$rows[0] && $_SERVER['REMOTE_ADDR']==$rows[1]) {
$return = 'LOGGED_IN';
mysql_query('UPDATE users set user_date="'.time().'"',$db);
return $return;
}else {
session_regenerate_id();
$return = 'ACCESS_DENIDE';
return $return;
}
}else{
session_regenerate_id();
$return = $_SESSION['user_status'];
return $return;
}
}
if($exe=='logout') {
//LOGOUT///////////////////////////////////////////
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_hash']);
unset($_SESSION['user_ip']);
unset($_SESSION['user_date']);
unset($_SESSION['user_level']);
unset($_SESSION['user_status']);
session_destroy();
session_regenerate_id();
$return = 'ACCESS_LOGGED_OUT';
return $return;
}
if($exe=='') {
//BLANK////////////////////////////////////////////
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_hash']);
unset($_SESSION['user_ip']);
unset($_SESSION['user_date']);
unset($_SESSION['user_level']);
unset($_SESSION['user_status']);
session_destroy();
session_regenerate_id();
$return = 'FUNCTION.ERROR:DO.MISSING';
return $return;
}
return $return;
}
/*
SQL
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL DEFAULT '',
`password` varchar(45) NOT NULL DEFAULT '',
`hash` varchar(45) NOT NULL DEFAULT '',
`ip` varchar(45) NOT NULL DEFAULT '',
`user_date` varchar(45) NOT NULL DEFAULT '',
`user_level` varchar(45) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `username`, `password`, `hash`, `ip`, `user_date`, `user_level`) VALUES
(1, 'admin', '6c7ca345f63f835cb353ff15bd6c5e052ec08e7a', 'f528764d624db129b32c21fbca0cb8d6', '127.0.0.1', '1306757011', '1');
admin/admin1
*/
//Usage
/*--------------------------------*/
//login page
session_start();
if(isset($_REQUEST['user']) && isset($_REQUEST['pass'])){
$user=cleanit($_REQUEST['user']);
$pass=cleanit($_REQUEST['pass']);
$_SESSION['user_status'] = auth("","",$user,$pass,"login");
header('members.php');
}else{
//Show login form
}
/*--------------------------------*/
/*--------------------------------*/
//Members page
session_start();
//Checks login on each page request put this on all pages you want to protect
$_SESSION['session_status'] = @auth($_SESSION['user_name'],$_SESSION['user_hash'],"","","check");
if($_SESSION['session_status']=='LOGGED_IN'){
//Logged in norm user
}elseif($_SESSION['session_status']=='LOGGED_IN' && $_SESSION['user_level']==1){
//Logged in as admin
}else{
//Logged out
}
/*--------------------------------*/
//Logout
if($_REQUEST['do']=='logout'){
auth("","","","","logout");
header('Location: index.php');
}
?>