I have this code which i'm trying to use to count the number of hits a page has had before redirecting the user to another page.
The idea is that non-logged in users can only visit profile.php 6 times before being redirected to a signup page, but it is also doing this for logged in users and i want the logged in users to be able to access profile.php as many times as they want.
Can someone please show me where i am going wrong.
so an example is if session is null then limit page access to 6 times, but if session = logged in then allow unlimited access.
<?
!session_id() ? session_start() : null;
if(!isset($_SESSION['logged_in']) && empty($_SESSION['logged_in'])){
verify_profile_visit_limit();
}
function verify_profile_visit_limit(){
$free_profiles = array(99999,99998,99997,99996,99995,99994,99993);
if(in_array($_GET["id"], $free_profiles)) return;
if(! isset($_SESSION["page_access_count"])){
$_SESSION["page_access_count"] = 1;
}
$_SESSION["page_access_count"]++;
if($_SESSION["page_access_count"] > 6){
header("Location: limit.php");
exit();
}
}
?>
The problem lies here:
if(!isset($_SESSION['logged_in']) && empty($_SESSION['logged_in']))
$_SESSION['logged_in'] can never be not set AND empty. You need to use the OR operator here.
Related
I am trying to get a certain uid number to access page if they are not in db then it redirects them to index page. Here is the code I put on top of the page. I keep getting an error this does not seem correct.
<?php
session_start();
if(!isset($_SESSION['uid'] = 12 )){
header('Location:index.php');
}
?>
You need to seperate this into two parts.
<?php
session_start();
if(!isset($_SESSION['uid']) || $_SESSION['uid'] != 12){
header('Location:index.php');
exit;
}
?>
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Errors for changing variables content depending on session status
Hello! I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if(isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISPLAY, DEPENDING ON SESSION---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISPLAY, DEPENDING ON SESSION---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
From what I can see, there are no errors.
The id just doesn't match logoptions.
Most likely, you are changing the id or logoptions somewhere between tha assignment and the final check. Try a vardump in both locations on both variables to see if they still match.
Btw, you can use intval() or simply cast as (int) instead of the regex
I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
It seams your variables don't hold the expected values when the $logOptions_id != $id runs, or you either forget to start the session. I don't see reference where $logOptions_id gets assigned. Use your IDE tool to debug the code.
i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? ยป Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.
I'm using a login system, and I'm trying to keep the user logged in for 10 days unless they specifically log out. I thought by using session_set_cookie_params('864000'); that it would make the user stay logged in for 10 days. But it's not doing that, at least in Chrome. The user only seems to be logged in for the standard 20-30 minutes before being automatically logged out. When I check the cookies in Chrome, there are two PHP Session cookies listed for my URL with expiration dates 10 days into the future. But this seems to be unrelated to the login variables. Most of the relevant code should be below.
Any idea why the user is not logged in for 10 days?
Thanks in advance,
John
In the index file, I have the following:
require_once "header.php";
//content
include "login.php";
In the header.php file, the following is included:
session_set_cookie_params('864000');
session_start();
In the login.php file, the following is included:
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
}
Here is the function "checkLogin":
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
Looks more likely that your server is discarding the sessions -- you'd need to store pertinent information in a local friendly database and load from there, based on the cookies as appropriate