how to implement PHP session manually - php

I am new to PHP. I want to implement PHP session manually. On a PHP pageload, I will check if cookie is set. If yes, I will display the required information, and if not, I will ask user to enter his details and then display the information. But I am not allowed to use PHP Sessions. I can use Cookies. Also the information needed to be displayed is about all the users (browsers) who are in session (so I have to save this to some static global array). Any help is appreciated. Thanks.

try this
setcookie('cookie_name', 'cookie_value', time());
echo $_COOKIE['cookie_name'];
Now check the cookie if it exists.
if(isset($_COOKIE['cookie_name'])) {
echo "your cookie is set";
} else {
echo "return error or any thing you want";
}
This will give you all browser(s) information.
echo $_SERVER['HTTP_USER_AGENT'];

Related

Check if session is expired, then redirect (Joomla)

what I am trying to do is so simple but I can't find a clue on how to make it happen.
I have a huge form that is made of several php files and these files being called using AJAX that user has to fill, what exactly I want to achieve is:
1) test if session has expired on every page of this form.
2) if session is expired, I want to redirect him to a specific URL, let's say http://www.example.com
Thanks in advance for your help.
Regards.
You can check if the session is active by using
$session = JFactory::getSession();
if ($session->isActive()) {
}
First thing that comes to my mind is to check if session cookie exists.
If session is active then by default PHP session mechanism uses cookie with default name 'PHPSESSID'. So if cookie PHPSESSID exists, your session is active.
You can check if session cookie exists like this:
if(isset($_COOKIE['PHPSESSID'])) {
echo 'Session is active!';
} else {
echo 'Session is not active!';
}
To redirect you can use this:
header('Location: http://example.com');
And to check for session cookie name use this:
session_start();
echo 'Session cookie name is: ' . session_name();
By default its 'PHPSESSID', but you or server admin could change that so check it out!
Hope this helps!

Codeigniter & PHP check if session exist

How can i simply check if cookies are enabled and user session too in PHP?
I need the really lighter piece of code of this world to do that, can anyone show me somenthing?
I'm on Codeigniter but i'm planning to use native PHP for this control.
my code:
if(session_start()){ echo 'started'; }
as i know Codeigniter doesn't uses native PHP session, how to do so?
Check for a valid session id:
$sid = session_id();
For example:
$sid = session_id();
if($sid) {
echo "Session exists!";
} else {
session_start();
}
The first point is "Don't fight the framework" when your framework has some functions than use it. Normally in the Framework classes are functions to prevent injections.
Here is a Post when tells you how to check the cookie:
Check if cookies are enabled
And for the session
How to tell if a session is active?
I think you can simply check by doing something like:
if(isset($_SESSION)){
// tells php session is initiated
}
if(isset($_COOKIE)){
}

php cookie does not work at the first time reading

I am a beginner for PHP and studying to use cookie for login. Would any body please check my code to see what is my problem, or let me how to fix this problem.
When I open the page at the first time, the cookie will not work. It will work when I repeated to open that link. However, I still could not make it work after I use function include and header One of codes is :
One code cookie.php is :
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
print_r($_COOKIE);
?>
When I run this code first time, it will does not show any thing. I can see cookie data at second time. From some website it is said that cookie would not be read at the same page.
So I moved print_r($_COOKIE) to second php file as well as added function include() or header() to above file, but both neither works.
Cookie2.php:
<?php
setcookie("cookiename",$_REQUEST['name']);
if(isset($_COOKIE['cookiename'])){
$cookieSet = ' The Cookie is ' . $_COOKIE['cookiename'];
} else {
$cookieset = ' No Cookie has been set';
}
setcookie("cookiepwd",$_REQUEST['pwd']);
include(‘printcookie.php’);
//or header("Location: printcookie.php")
?>
printcookie.php:
<?php
print_r($_COOKIE);
?>
Thank you very much for answering in advance!
Michelle
setcookie only sets up the header, that is being sent to the client. It doesn't change the $_COOKIE superglobal.
In other hand - $_COOKIE is filled up with the cookies sent from the client
So at first step - you set the cookie with setcookie and have nothing in $_COOKIE because client hasn't sent it yet, and will only on the next request.
And there is no way of doing what you want, rather than modifying $_COOKIE manually
PS: it is a bad idea to put user's password in the cookie
Give zerkms the answer, but I just want to reiterate:
Cookies are not bad for storing bits of info like the user's theme preferences or preferred start page, etc. They get their bad rep from being used for identity and authentication handling. There are cookies out there that basically have "isAdmin=0" in order to control user access. It is very easy to change that to isAdmin=1 and have a field day. Since you are new to PHP, take the time to learn about sessions now while it's all new to you.
When you set a cookie using setcookie, you are sending an HTTP header to the browser with the cookie info. The browser will then pass back that cookie in any future requests to the server. The $_COOKIE global variable holds the cookie info passed in from the browser to the server.
Since you are using $_REQUEST to get the cookie name, you don't need to check the cookie (otherwise you wouldn't have the data to set it right?). So consider going this route:
if(!isset($_COOKIE['cookiename'])) {
$name = $_POST['name']);
setcookie("cookiename",$name);
} else {
$name = $_COOKIE['cookiename']);
}
echo "Welcome back $name!";
This will also help out if they clear cookies, etc.
But really, the safer route is:
session_start();
if(!isset($_SESSION['name'])){
$_SESSION['name'] = $_POST['name']);
}
if(!isset($_SESSION['pwd'])){
$_SESSION['pwd'] = $_POST['pwd']);
}
$name = $_SESSION['name'];
$pwd = $_SESSION['pwd'];
And even this would be frowned upon for serious web security, where you should simply check the password against a stored hash and then delete it, using other global variables to confirm session integrity. But there's now a whole StackExchange for that.
As a workaround you could use location() after checking the cookie to have access to the stored data.
But be aware that location() fails, if anything (including breaks and blanks in your script) already sent to the browser.

php cookies and session variables and ip address

I posted a similar question before, but never really got an answer that helped me, so I'm looking to try again. As a disclaimer, I know that a lot of the information in here doesn't follow perfect coding practices, but it is for exercise purposes only. I've tried a million things and nothing seems to be working because I'm not really sure where everything should go! I desperately need some (any!) help so thanks in advance if you can offer anything!
I'm trying to create a simple form / page that uses some basic cookie and session stuff to produce some user-specific data. I was moving along good until I came across a few problems that I can’t figure out. On my first page everything is good except for I just want the NAME of the browser the user is using. (for example, I want just the simple title: Firefox instead of the whole long version of the browser.) I've seen this be done so I think it’s possible, I just don’t know how to do it!
My real problems come up right about here, because I'm not exactly sure how to store the IP address, browser info and the current date/time (which I want shown on page 2) as session variables. Tried a few things I found, but I don’t think I was doing it right.
I also worked endlessly on trying to store the username and passwords as two separate cookies each...suggestions? Finally, what do I need to do to have a location header (used to call form_data.php) with output buffering?
(Not sure this will be that helpful, considering I probably did everything wrong! LOL) This is a totally stripped-down version of my code. Tried to post my cleanest version, even though it doesn't have much info, so that you could easily see what I was trying to do.
main file code:
<?php
header('Location: form_data.php');
setcookie('username', $_POST['username']);
setcookie('password', $_POST['password']);
//I know this isn't working.
//honestly I just left this in here as to show where I had been
//trying to save the cookie data. Pretty obvious how bad my
//trial and error with this went!
}
?>
<?php
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo " By the way, your IP address is: </b>".$_SESSION['ip']."<br />";
echo " You already know this, but the browser you are currently using
to view this page is:<br/>"; //What is the correct function that I should be using here?
echo "<form action=\"form_data.php\" method=\"post\">";
echo "username:<input type=\"text\" name=\"username\" size=\"20\" value=\"\"><br/>";
echo "password:<input type=\"password\" name=\"password\" size=\"20\" value=\"\"><br/>";
echo "<input type=\"submit\" value=\"Submit, please\" />";
echo "<br /><input type=\"hidden\" name=\"submitted\" value=\"true\" />";
?>
form_data.php
<?php
echo "Hello, ".$username;//I'm trying to get the cookie data for the username
echo "Your password is ".$password; //Samething here (want cookie data)
echo "The date and time you entered this form is: ".date("F j, Y")." -- ".date("g:i a");
echo "<br/>Your IP:".$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
echo "<br/>Your broswer:".;//I want full broswer data here...dont know how to do it.
//Overall, was this the way to get the session variables for IP, date/time and browser?
echo "Thank you for filling out this form!";
?>
To get the browser, use the get_browser() function:
$browserinfo = get_browser($_SERVER['HTTP_USER_AGENT']);
$browsername = $browserinfo['browser'];
Your session and cookie storage will never work because you are making a header("Location"); call before attempting to set cookies. You cannot send any output before setting cookies or establishing a session.
Before any output to the screen, call session_start();
// attach to your session (or create if it doesn't exist)
// You must call session_start() on every page where you intend to access or set session vars
// and it must be called before any output (including whitespace at the top)
session_start();
// Store some stuff...
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
// Store user info in session, not cookie
$_SESSION['username'] = $_POST['username'];
// Set a cookie
// Not a super secure token, but better than user/pass in cookies.
// Point here is just to show that it must be done before any output or before the redirection header.
$_SESSION['token'] = sha1(time() . rand() . $_SERVER['SERVER_NAME']);
setcookie('token', $_SESSION['token']);
// In practice, you'd want to store this token in a database with the username so it's persistent.
// Now do the redirection:
// Supposed to be an absolute URL by the HTTP spec
header("Location: http://example.com/form_data.php");
// exit right after the redirection to prevent further processing.
exit();
ADDENDUM after comments
While you work, make sure PHP displays all errors on screen. Be sure to turn off display_errors when your code goes onto a live public server.
error_reporting(E_ALL);
ini_set('display_errors', 1);
To retrieve values from cookies as you said in your question you didn't know how to do, use the $_COOKIE superglobal:
// On the page that sets it...
setcookie('somename', 'somevalue', expiry, domain);
// On the page that retrieves it...
echo $_COOKIE['somename'];
> I'm trying to create a simple form /
> page that uses some basic cookie and
> session stuff to produce some
> user-specific data.
Sessions do use cookies under the cover(only store session_id inside cookie/set_cookie) and I advice you to use only sessions because cookies can leak information(store all the information inside cookie on that user's computer) which could be dangerous while session uses the server's filesystem/database or whatever you like when you override session_set_save_handler.
> On my first page everything is good
> except for I just want the NAME of the
> browser the user is using.
Like Michael said you can use get_browser for that:
Attempts to determine the capabilities
of the user's browser, by looking up
the browser's information in the
browscap.ini file.
Like the PHP page says it tries to determine and you should NOT rely on this information for anything important because it can be wrong(you can fool the system, if you like). What I mean is you should not use it to validate/proof something.
> My real problems come up right about
> here, because I’m not exactly sure how
> to store the IP address, browser info
> and the current date/time (which I
> want shown on page 2) as session
> variables.
More information to retrieve the IP address can be read here(proxy-server could mislead you a little bit maybe?). To store that information just store it inside a session by first issuing session_start() on top of every page(before outputting anything) that wants to use sessions(only those to not set cookies on every page which makes page a little slower) and next store the current time inside a session variable by doing something along the lines of $_SESSION['time'] = date(DATE_RFC822);. You can read more about retrieving the time at date() page.
So the code on page 1 looks something like:
<?php
session_start();
$_SESSION['ip'] = getRealIpAddr(); # no php function => See http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html
$_SESSION['time'] = date(DATE_RFC822);
Then on page 2 you could retrieve this information using something like:
<?php
session_start();
echo $_SESSION['ip']; // retrieve IP
> I also worked endlessly on trying to
> store the username and passwords as
> two separate cookies
> each...suggestions?
Don't store them inside a cookie(only using set_cookie and not using sessions to store information) but store them inside a session for extra security. But sessions are also vulnerable to session fixation so after storing something critical inside your session you should regenerate session id and never output/show that information to the browser/user to prevent any leakage.
> Finally, what do I need to do to have
> a location header (used to call
> form_data.php) with output buffering?
Like Michael said you should be using header function and exit to terminate script after that
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
P.S: Never store any really sensitive information like creditcard(use paypal or something) numbers or anything in your own database. I also advice you not to store passwords inside your database but use something like openId(Google's) for example to handle your authentication for extra security.

PHP Login, Store Session Variables

Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something

Categories