I want to make a simple website on a local server that would be accessed by only one device at a time. I've found user management scripts but they are more more complex than what I am searching for. I don't need it to be password protected or have different kind of users and/or rights. Juste a page where only one person at a time can connect.
Is there a way to make it in PHP ?
I've first searched for an option in my server (lighttpd) then for some kind of htaccess but I think PHP is the only way to do it right.
Thank you for your consideration.
According to my comment above:
<?php
$minInterval = 5 * 60; // 5 minutes
$access = true;
if (file_exists('visitor')) {
$visitor = unserialize(file_get_contents('visitor'));
if ($visitor['addr'] != $_SERVER['REMOTE_ADDR']) {
if ($visitor['time'] + $minInterval >= time()) {
$access = false;
}
}
}
if (!$access) {
exit('Access denied.');
} else {
// Update last visitor data
file_put_contents('visitor', serialize([
'addr' => $_SERVER['REMOTE_ADDR'],
'time' => time()
]));
}
Related
I'm using this Flash Messages Script for a simple redirect and flash message system.
Everything works fine on my apache localhost, but as soon as I upload it to a server (also apache) it doesn't work. It sets the sessions and also displays the messages correctly, but it doesn't unset the messages afterwards. Now I have a whole bunch of "Flash messages" on my website and they'll get more and more unless you close your browser to unset all sessions forcefully.
I've already read the documentation like a thousand times and also searched in the Flash Messages script on the server for any errors. I couldn't find any.
Maybe you guys can help me. The host where I'll deploy my website is strato.com.
Edit: I found a cookie called PHPSESSID in my browser informations. Maybe this could be helpfull.
Constructor:
public function __construct()
{
// Generate a unique ID for this user and session
$this->msgId = sha1(uniqid());
// Create session array to hold our messages if it doesn't already exist
if (!array_key_exists('flash_messages', $_SESSION)) $_SESSION['flash_messages'] = [];
}
Clear session function:
protected function clear($types=[])
{
if ((is_array($types) && empty($types)) || is_null($types) || !$types) {
unset($_SESSION['flash_messages']);
} elseif (!is_array($types)) {
$types = [$types];
}
foreach ($types as $type) {
unset($_SESSION['flash_messages'][$type]);
}
return $this;
}
Add Sessions:
public function add($message, $type=self::defaultType, $redirectUrl=null, $sticky=false)
{
// Make sure a message and valid type was passed
if (!isset($message[0])) return false;
if (strlen(trim($type)) > 1) $type = strtolower($type[0]);
if (!array_key_exists($type, $this->msgTypes)) $type = $this->defaultType;
// Add the message to the session data
if (!array_key_exists( $type, $_SESSION['flash_messages'] )) $_SESSION['flash_messages'][$type] = array();
$_SESSION['flash_messages'][$type][] = ['sticky' => $sticky, 'message' => $message];
// Handle the redirect if needed
if (!is_null($redirectUrl)) $this->redirectUrl = $redirectUrl;
$this->doRedirect();
return $this;
}
I fixed it. It was due an change in PHP 7.1 in the php.ini file. As soon as I downgraded my PHP version to PHP 7.0 everything worked fine again.
I hope this will help a lot of people. At least you've got some starting point now.
I am trying to track the actions of all non-logged in users on my site. The aim is to store this activity so that I can add it to their profile when they do create an account.
I am using the Behaviour below to assign new users a cookie and use that cookie as the basis of a "temp user" row in my Users table. This way a user can straight away start interacting with my API.
This seems to work fine. However, I am seeing loads more "temp user" rows being created in my DB than I have visitors to the site - about 2500 compared with around 500 visits yesterday (according to Google Analytics).
Is there anything wrong with the behaviour below, or am I doing something else wrong? Is there a better way?
<?php
class ApplicationBehavior extends CBehavior
{
private $_owner;
public function events()
{
return array(
'onBeginRequest' => 'setCookies'
);
}
public function setCookies()
{
$owner = $this->getOwner();
if ($owner->user->getIsGuest() && !isset(Yii::app()->request->cookies['dc_tempusername'])):
$tempusername = genRandomString(20);
$tempuser = new User();
$tempuser->username = $tempusername;
$tempuser->email = "noemailyet#tempuser.com";
if (isset(Yii::app()->request->cookies['dc_tempusername'])) {
$tempuser->name = Yii::app()->request->cookies['dc_tempusername']->value;
} else {
$tempuser->name = "CookieBasedTempuser";
}
$tempuser->points = 1;
$tempuser->firstip = $_SERVER['REMOTE_ADDR'];
if ($tempuser->validate()) {
Yii::app()->request->cookies['dc_tempusername'] = new CHttpCookie('dc_tempusername', $tempusername);
$cookie = new CHttpCookie('dc_tempusername', $tempusername);
$cookie->expire = time() + 60 * 60 * 24 * 180;
Yii::app()->request->cookies['dc_tempusername'] = $cookie;
$tempuser->save();
} else {
echo CHtml::errorSummary($tempuser);
}
endif;
}
}
?>
Check if cookies are enabled first:
Check if cookies are enabled
If we're correct, every time you see that the user is a guest and does not have a cookie then you're creating a new temp user.
Why not check to see if a cookie is set first, if so then create the temp user?
You would end up needing to set 2 cookies: initial temp cookie to check against, and then your 'dc_tempusername' cookie.
You could even go as far as using Browscap to check against known bots:
https://github.com/browscap/browscap-php
http://browscap.org/
You'll need to be able to define browscap in your php.ini
We're using php to set some cookies for our users based on where they came from - some of these will be set based on the referrer URL, and some will be set based on a short query string in the URL.
We only set 2 cookies, and the purpose is to track where traffic is coming from and include the data in the user's submission for our product - then we are able to track which submissions come from which campaign.
It's a custom wordpress website, so the code is split across a few different files as follows:
header.php:
<?php
$origin = $_SERVER['HTTP_REFERER'];
$current = $_SERVER['PHP_SELF'];
$bestbefore = time() + 60 * 60 * 24 * 7;
if (isset($_COOKIE['ccsvissource']))
{
}
else
{
if (isset($_GET[gclid]))
{
setcookie('ccsvissource', 'Google', $bestbefore);
setcookie('ccsvismedium', 'Adwords', $bestbefore);
}
elseif (stripos($origin, 'facebook') !== false)
{
setcookie('ccsvissource', 'Advertising', $bestbefore);
setcookie('ccsvismedium', 'Facebook', $bestbefore);
}
elseif ($_GET[utm_medium] == "111")
{
setcookie('ccsvissource', 'Advertising', $bestbefore);
setcookie('ccsvismedium', 'emailcampaign', $bestbefore);
}
else
{
setcookie('ccsvissource', $origin, $bestbefore);
setcookie('ccsvismedium', 'Unknown', $bestbefore);
}
?>
footer.php:
<?php
$mktSource = $_COOKIE['ccsvissource'];
$mktMedium = $_COOKIE['ccsvismedium'];
?>
<p class="hide-me" id="mkt-source"><?php echo $mktSource; ?></p>
<p class="hide-me" id="mkt-medium"><?php echo $mktMedium; ?></p>
<script type="text/javascript">
$(document).ready(function(){
var mktSource = $('#mkt-source').text();
var mktMedium = $('#mkt-medium').text();
$('#hid-ms').val(mktSource);
$('#hid-mm').val(mktMedium);
});
</script>
The values will then get passed into the user's application form, with our lead management system doing the rest.
The problem is inconsistency - sometimes the cooks are being set, and sometimes not. Is there a certain circumstance client-side which will prevent cookies from being set?
I understand the user may have cookie tracking switched off, and have accounted for this - the volume of empty cookies is still too high so I think I'm missing something.
Please let me know if you need any further information!
Many thanks.
With new wordpress i've also face the same problem, my custom cookies wasn't set where my code was correct but somewhere i found that sometimes custom cookies does not work. So finally i found this working example with wp_head hook.
Let suppose you want to set 2 different cookies like Area and currency you need this function with wp_head, i have use this in my personal projects. it working prefectly.
add_action('wp_head', 'my_setcookie');
function my_setcookie()
{
if (!empty($_REQUEST['area'])) {
$area_set = ($_REQUEST['area']);
setcookie('area', $area_set, time() + 3600, COOKIEPATH);
}
if (!empty($_REQUEST['currency'])) {
$currency_request = ($_REQUEST['currency']);
setcookie('currency_cookie', $currency_request, time() + 3600, COOKIEPATH);
}
}
This question already has answers here:
PHP ending sessions(different ways) i dont understand
(2 answers)
Closed 9 years ago.
I have a PHP login and log out script and what I'm trying to achieve is that when the user click on the log out link he completely logs out, regardless clicking the back button of the browser, and do not want the user to access the page.they should be redirected to the login page
this is login function
function loggedin() {
if ( isset($_SESSION['user_id']) && !empty($_SESSION['user_id']) ) {
return true;
} else{
return false;
}
}
and this is my logout script
<?php
include 'includes/connect.php';
include 'includes/functions.php';
session_destroy();
header('location: index.php');
?>
how can i achieve this??
You can delete all cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
http://www.php.net/manual/en/function.setcookie.php#73484
And if you have an array of cookie names used for login authentication, you should iterate the cycle only with them.
The question was logging out a user completely from a website and not just how do I destroy a PHP session, so my answer will be somewhat more complex.
Since you're using PHP's $_SESSION functionality to handle the user sessions, you can, in particular, tie the current session IDs to the user accounts. Then you can easily force the session to expire.
For example, create a new field in the user database, and call it active_session_id or something. Every time a user logs in, save the session_id() output to it. Then inside of your loggedin() function check if the session_id() of the current request matches the one saved when the user was logging in, and if it does not match, the function will return false, so this is how you virtually end a user session. I.e. even though it will still actually be there, it will not be valid anymore.
It is worth noting that the solution above would be sort of a one-to-one relation, i.e. one user will be able to have only one active session. If you want to allow users to come from different places at the same time, you'll have to maintain a one-to-many relation there by creating a new table called e.g. users_sessions and saving the session IDs there. Please do not create another fields in the current users table like active_session_id_1, active_session_id_2 etc. because it is not considered to be a good practice.
Hope this helps
You can write a generic function that checks if a user is logged in, if not just redirect them like this
function isLoggedIn(){
if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
//do what you want
} else{
header("location:youloginpage.php");
}
}
If you do not specify more on your question, we can only procede by assumptions. Anyway, since you are using that SESSION, and it's not clear if you want to destroy the data contained or not, the function to check if user is logged in, could be modified this way:
function loggedin() {
if ( isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']) && ($_SESSION['user_id'] > 0) ) {
return true; //user is logged in
//other operations to be performed
} else{
return false; //user is NOT logged in
//other operations to be performed
}
}
The logout function could just be something like this:
function logout() {
if ( isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']) && ($_SESSION['user_id'] > 0) ) {
$_SESSION['user_id'] = -1; //"unsets" the user, while not destroyng session
} else{
return false; //user is already logged out - do nothing
}
}
I am using sfGuard as the authentication plugin in my project. I want to invoke certain client side & server side scripts on session timeout. What is the best way I can do this.
Please help!
Thanks a lot.
Well I've been reading the sfGuardSecurityUser and it extends the sfBasicSecurityUser class, which handles user authentication, profile, credentials, etc.
So, I found a function in sfBasicSecurityUser that determines whether a users sessions is timed put called isTimedOut, and also setTimedOut.
If you want to do something when user's session times out, at least on server side, you should listen to the event that is throw when this happens. Check this method:
This could be found in the symfony_core_root_dir/lib/user/sfBasicSecurityUser.class.php
public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array())
{
// initialize parent
parent::initialize($dispatcher, $storage, $options);
if (!array_key_exists('timeout', $this->options))
{
$this->options['timeout'] = 1800;
}
// force the max lifetime for session garbage collector to be greater than timeout
if (ini_get('session.gc_maxlifetime') < $this->options['timeout'])
{
ini_set('session.gc_maxlifetime', $this->options['timeout']);
}
// read data from storage
$this->authenticated = $storage->read(self::AUTH_NAMESPACE);
$this->credentials = $storage->read(self::CREDENTIAL_NAMESPACE);
$this->lastRequest = $storage->read(self::LAST_REQUEST_NAMESPACE);
if (null === $this->authenticated)
{
$this->authenticated = false;
$this->credentials = array();
}
else
{
// Automatic logout logged in user if no request within timeout parameter seconds
$timeout = $this->options['timeout'];
if (false !== $timeout && null !== $this->lastRequest && time() - $this->lastRequest >= $timeout)
{
if ($this->options['logging'])
{
$this->dispatcher->notify(new sfEvent($this, 'application.log', array('Automatic user logout due to timeout')));
}
$this->setTimedOut();
$this->setAuthenticated(false);
}
}
$this->lastRequest = time();
}
For client side, you might start thinking about HTML 5 and Javascript Workers. The idea could be setting a worker when page loads, and telling him count till session_time_out, then redirecting to a login page or something.