I have website where I am using login and logout functionality using php.
So, for login, first I call following function :
function sec_session_start() {
$session_name = 'happiechef_session_ids'; // Set a custom session name
$secure = false;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location:index");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
and then I call following function to check user login information from mysql database :
function admin_login($email, $pass) {
global $conn;
$query = mysqli_query($conn, "SELECT a_email, a_pass, a_id FROM admin_profile WHERE a_email = '$email' LIMIT 1");
$query_result = mysqli_fetch_array($query);
$a_id = (int) $query_result['a_id'];
$db_hash = htmlspecialchars($query_result['a_pass']);
$num = mysqli_num_rows($query);
if($num == 1) {
if (checkbrute($email) == true) {
// if true account is locked
return false;
} else {
if(verify($pass, $db_hash)) {
$a_id = preg_replace("/[^0-9]+/", "", $a_id);
$email = validate_data($email);
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['logged_admin_user'] = $email;
$_SESSION['logged_admin_id'] = $a_id;
$_SESSION['login_string'] = hash('sha512', $db_hash . $user_browser);
return true;
} else {
$time = time();
$query = mysqli_query($conn, "INSERT INTO login_attempt VALUES('', '$email', '$time')");
return false;
}
}
} else {
return false;
}
}
Well, when I refresh the page multiple time using F5 key from Keyboard it's automatically logged out and sometime when I visit other page it's asking me to login! Somehow it's destroyed the PHP session.
Can anyone tell me what is the problem in my code ?
Thanks In advance.
Update :
Here is the function to check if user is logged or not :
function admin_login_check() {
// Check if all session variables are set
if (isset($_SESSION['logged_admin_user'], $_SESSION['logged_admin_id'], $_SESSION['login_string'])) {
global $conn;
$user_id = $_SESSION['logged_admin_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['logged_admin_user'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if($query = mysqli_query($conn, "SELECT a_pass FROM admin_profile WHERE a_email = '$username' ")) {
$num = mysqli_num_rows($query);
if($num == 1) {
$result = mysqli_fetch_array($query);
$password = htmlspecialchars($result['a_pass']);
// if hash equals function is not exist
if(!function_exists('hash_equals')){
function hash_equals($str1, $str2){
if(strlen($str1) != strlen($str2)){
return false;
} else {
$res = $str1 ^ $str2;
$ret = 0;
for($i = strlen($res) - 1; $i >= 0; $i--) {
$ret |= ord($res[$i]);
}
return !$ret;
}
}
}
$login_check = hash('sha512', $password.$user_browser);
if (hash_equals($login_check, $login_string) ){
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
If you remove the session_regenerate_id(true) the session should not destroyed anymore.
Why is this happening?
session_regenerate_id() replace the current session ID with a new one. The session information will be kept. When you use this function to often (reload, AJAX, etc.) you can see this effect on your session. PHP has a restriction for access to the session for only one running task. If you run session_regenerate_id() to often / fast the task get into queue. So the following is happening:
The first call changes the session ID and delete the old session (if parameter is true).
The second call has still the old session ID and tries to do some operations on it.
As the old session doesn't exists anymore, a new session would be created. The user is logged out now (session is invalid now).
Whenever i run this code, i recieve a blank screen on submission. The code does not seem to work and i'm unsure why. Can anyone see an issue? I've checked it for syntax already mutliple times.
Controller:
public function changepwd(){
$this->form_validation->set_rules('oldpassword','Old Password','required|trim|xss_clean|callback_change');
$this->form_validation->set_rules('password1','New Password','required|trim');
$this->form_validation->set_rules('password2','Confirm Password','required|trim|matches[password1]');
if($this->form_validation->run()= true){
redirect('admin');
}else{
$this->form_validation->set_message('change','info is wrong');
redirect('admin');
}
}
public function change(){
$this->load->view('error_display');
$oldpass = $this->input->post('oldpassword');
if(isset($oldpass)){
if($this->input->post('password1') == $this->input->post('password2')){
$session=$this->session->userdata("logged_in");
$username= $session['username'];
$query = "SELECT * FROM database where username='$username'";
$result = $this->db->query($query);
$row=$result->row();
$pass = $row->password;
$s= $row->salt;
$user_old_pass = sha1($s.$oldpass);
if($pass == $user_old_pass){
$new = substr(uniqid(rand(), true), 0, 20);
$users_password = $this->input->post('pass1');
$new_password = sha1($new.$user_password);
$data = array($new,$new_password);
$this->update_model->insert_model($data);
$this->form_validation->set_message('change','saved');
$this->load->view('admin');
}else{
$this->form_validation->set_message('change','<p class="error">Incorrect Password</p>');
return false;
redirect('admin');
}
}else{
$this->form_validation->set_message('change','passwords dont match');
return false;
redirect('admin');
};
}else{
$this->form_validation->set_message('change','old password is not entered');
return false;
redirect('admin');
}
model:
function login($data)
{
$this->db->update('database', $data);
}
your
if($this->form_validation->run()= true){
should be
if($this->form_validation->run() == FALSE) {
because you are redirecting every time to 'admin'
I'm using php codeigniter for my project. In my login page if username and password is invalid just load the login page, else load the home. if invalid, First time it loads the login page again given the wrong details for login one controller name is added in url like local turns like localhost/project name/administrator/administrator/login_authentication
my code is
function index()
{
if($this->session->userdata('usertype') != '')
{
redirect('administrator/administrator_view');
}
else
{
$this->load->view('login');
}
}
function login_authentication()
{
$username=$this->input->post('username');
$password=$this->input->post('password');
$user = $this->administrator->admin_authentication($username,$password);
if(count($user) == 1)
{
foreach($user as $admin_value)
{
$user_name=$admin_value['UserName'];
$usertype=$admin_value['UserType'];
}
$session_data = array(
'username' => $user_name,
'usertype' => $usertype,
);
$this->session->set_userdata($session_data);
if($usertype == 1)
{
redirect('administrator/administrator_view');
}
}
else
{
$data['Invalid_Login']="Invalid Username and Password";
$this->load->view('login',$data);
}
}
function administrator_view()
{
if($this->session->userdata('usertype') == '')
{
redirect('administrator');
}
else
{
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('dashboard', $data);
$this->load->view('footer');
}
}
Admin authentication function
function admin_authentication($username, $password)
{
$this->db->select('*');
$this->db->from('user');
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
$query = $this->db->get();
return $query->result_array();
}
I'm trying more than one time given not correct information for login everytime one controller name added in url. Please help me.
Thanks in advance.
change
$this->session->set_userdata($session_data);
to
$this->session->set_userdata(('some_name', $session_data);
and change
if($this->session->userdata('usertype') == '')
in all area to
$ses = $this->session->userdata('some_name');
if($ses['usertype'] == '')
and try....
first of all check if there is an post request in your function login_authentication() like this:
function login_authentication()
{
if( $this->input->post(null) ){
//your authentication code here
}else{
//load the login view here
}
}
Here is your function:
function login_authentication(){
if( $this->input->post(null) ){ //check if there is an post request
$username=$this->input->post('username');
$password=$this->input->post('password');
$user = $this->administrator->admin_authentication($username,$password);
print_r( $user );die(); //the user array as returned from the model see if its correct or not
if(count($user) == 1)
{
foreach($user as $admin_value)
{
$user_name=$admin_value['UserName'];
$usertype=$admin_value['UserType'];
}
$session_data = array(
'username' => $user_name,
'usertype' => $usertype,
);
print_r( $session_data );die; //see if it builds the correct array or not
//$this->session->set_userdata($session_data);
$this->session->set_userdata('user_info',$session_data); //to read the username use like $this->session->userdata['user_info']['username'];
if($usertype == 1)
{
redirect('administrator/administrator_view');
}
}else{ //invalid credentials load the login view
$this->session->set_flashdata('Invalid_Login', 'Invalid username or password!'); //to echo in view use $this->session->flashdata('Invalid_Login');
redirect('administrator', 'refresh');
}
}else{ //redirect to index function now
redirect('administrator', 'refresh');
}
}
In your function administrator_view(),
function administrator_view(){
if( !$this->session->userdata('user_info') ){
print_r( $this->session->all_userdata() );die('no session set redirecting'); //the session is not set here
redirect('administrator');
}
else{
$data['heading'] = '';
$this->load->view('header', $data);
$this->load->view('dashboard', $data);
$this->load->view('footer');
}
}
So, I have 3 forms on the same page and same controller action, when I click on one of the submit button, it validates all forms instead of the one I clicked.
how can I separate it from validation??
here my code:
public function signUpAction()
{
$firstName = $this->getRequest()->getParam('firstName');
$lastName = $this->getRequest()->getParam('lastName');
$email = $this->getRequest()->getParam('email');
$emailAdrress = $this->getRequest()->getParam('Email_Address');
$password = $this->getRequest()->getParam('password');
$signupForm = new Application_Form_UserSignUp();
$loginForm = new Application_Form_UserLogin();
$retreivePasswordForm = new Application_Form_UserRetreivePassword();
if ($this->getRequest()->isPost('signupForm'))
{
/*********** Sign Up Form ***********/
if ($signupForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($signupForm->getValues());
if ($user->save())
{
Zend_Session::rememberMe(186400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendSignUpEmail();
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else
{
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('loginForm'))
{
/************ Login Form ************/
if ($loginForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($loginForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $email, 'hash' => $password));
if($user)
{
Zend_Session::rememberMe(86400 * 14);
Zend_Auth::getInstance()->getStorage()->write($user);
$this->getHelper('redirector')->gotoRoute(array(), 'invite');
return;
}
else {
// Error message
$this->view->errorMsg = "<b>password</b> - invalid, please try again! *";
}
}
else
{
// something
}
}
if ($this->getRequest()->isPost('retreivePasswordForm'))
{
/****** Retreive Password Form ******/
if ($retreivePasswordForm->isValid($this->getRequest()->getParams()))
{
$user = $this->_helper->model('Users')->createRow($retreivePasswordForm->getValues());
$user = $this->_helper->model('Users')->fetchRowByFields(array('email' => $emailAdrress));
if($user)
{
Zend_Auth::getInstance()->getStorage()->write($user);
$user->sendRetreiveEmail();
$_SESSION['email'] = $emailAdrress;
$redirector = $this->_helper->getHelper('redirector');
$redirector->setCode(301)->setUseAbsoluteUri();
$newPath = 'http://refer.lavasoft.com/#retreive_sent';
$redirector->gotoUrl($newPath);
//$this->view->assign('sendEmail', $emailAddress);
}
else
{
}
}
else
{
// something
}
}
$this->view->retreivePasswordForm = $retreivePasswordForm;
$this->view->loginForm = $loginForm;
$this->view->signupForm = $signupForm;
}
This is not how it works in ZF. You cannot pass the form name to isPost() unless you override isPost() in your code.
What you could do is Define all your fields like:
loginForm[name]
loginForm[password]
and
signupForm[name]
etc
then just check for isset($_POST['loginFom'])
This should work fine.
Or use a hidden field named formName and check in your code what's its value is.
You can also use a different action for each form and in the end redirect to the signUpAction wich would yeld the same result without the hassle.
I'm trying to protect page by making a member only area the code I use in this case is
<?php
include 'dbc.php';
page_protect();
?>
there is no error by using this code and also it just working fine
but the problem is that whenever I place the below code in the same page
the problem will happen with the iPhone, only with this device but the rest still ok, like PCs, laptop and tablet (iPad) they are all no problem
But the iPhone the problem will be that you can access to the page after login but whenever you refresh it will redirect you to the login page and ask for login again.
<?php
if(!isset($_GET['link'])){
$link = 1;
} else {
$link = $_GET['link'];
}
if ($link == 1) {
echo "";
} elseif ($link == 23) {
echo "";
} else {
echo "";
}
?>
There is no error show or anything.
my question is that is there anyway to protect the page because I need this to be member only area and the above code is very important and need to be in the page.
Thanks in advance.
here is the dbc.php sorry about that but I copied the whole script and placed here
<?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 ;
}
}
?>
An alternative to your current protect script, ive made it without cookies:
<?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');
}
?>
This is a comment posted here for better formatting.
You have to read the man pages on session_ functions work! Doing so will save you time and aggravation. Many here have given you hints on the possible source of your problem. For one, you cannot have ANY output whatsoever before session_start(). For 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 "";
}
This snippet at the top of your post will always make your script fail if you try to echo anything whatsoever. Again, friendly advice, take 15 minutes of your time and read the manual. You will have access to much more valuable first-hand information on those aspects of your work than by posting here out of laziness to get a quick fix. Then again, I probably am not the first one to tell you this.