session_start() creates new session every reload - php

I've read this before:
How to fix “Headers already sent” error in PHP
I have a session page, when I refresh/reload it, it creates a new session id!
<?php
$islogin=0;
$idadmin=0;
session_start();
$sid=session_id();
include("connect.php");
$result=mysql_query("select * from session_noti where sid='$sid'",$cn);
if(mysql_num_rows($result) > 0){
$row=mysql_fetch_object($result);
$islogin=$row->islogin;
$idadmin=$row->idadmin;
}else{
if(mysql_query("insert into session_noti (sid,islogin) values ('$sid',0);")){
}else{
}
}
$user_cookie=#$_COOKIE["*****"];
if($user_cookie != ''){
$user_cookie_res=mysql_query("select * from session_noti where sid='$user_cookie'");
$user_cookie_row=mysql_fetch_object($user_cookie_res);
$islogin=$user_cookie_row->islogin;
$idadmin=$user_cookie_row->idadmin;
}
?>
connect page:
<?php
$cn = mysql_connect("localhost","root","");
mysql_select_db("***");
?>
why? It works fine on localhost, when I want to upload it on server,this scenario happens.

This code seems designed very poorly. Except for the usual "PHP4-style" errors (more on that later), it doesn't really make sense to me.
If you're using PHP's sessions, why do you need to replicate a session table in your database? Y using session_start() you're already telling PHP to handle all that hassle.
Why are you accessing users' cookies directly?
I recommend that you stick with a design and follow it.
Do you want to manage sessions yourself, including passing session ids, handling cookies, etc? Then don't PHP's builtin sessions (but be careful: the possibility to write flawed code here is really high).
Do you want to use PHP's builtin sessions? Then just stick with them.
If you want to attach to each users details like "isAdmin", you can use session variables: that's what they're made for :)
<?php
session_start();
if(empty($_SESSION)) {
// Redirect to login
}
else {
if(empty($_SESSION['logged_in'])) {
// Redirect to login
}
else {
// User is logged in
// Is admin?
if(!empty($_SESSION['is_admin'])) {
// YES
}
else {
// NO
}
}
}
?>
There's plenty of guides and tutorials on using sessions with PHP. For example: http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html
Additionally, make sure that in php.ini sessions are enabled. I strongly recommend to use "cookie_only" sessions: that is, never make PHP pass the session id as GET or POST parameter. That will screw those users with cookies disabled (are there still some?), but will save all the others from being easy targets for session hijacking.
Thus said... About your "PHP4-style" code:
Don't use mysql_* functions. They're deprecated. Use MySQLi or PDO, and use prepared statements when possible. For example, the line mysql_query("select * from session_noti where sid='$user_cookie'"); is a perfect place for an SQL Injection attack.
Don't use the # operator. It's bad! Instead, just check if the variable exists with isset() or empty().

Related

Putting variable in header = PHP

So I'm trying to make the posts.php page look like this >> 'posts.php?user='.$username << for each individual user.
Here is the code on my index.php page (which after a user logs in/signs up turns into >> 'index.php?user='.$username :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
//do nothing
} else {
$_SESSION['username'] = $_GET['user'];
$username = $_GET['user'];
$_SESSION['username'] = $username;
}
Here is the code so far on my posts.php page :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
header('location: must_login.php');
} else {
//idk what to put here
}
?>
I'm trying to get my posts.php page header to look like this >> 'posts.php?user='.$username
I understand you are on day 1 of PHP learning. You are getting a lot of negative responses because your question isn't very specific. You aren't very clear about what is "not working." You should say what you expect to happen, and what is happening.
Here's my answer based on what I think you're asking.
Since the username would usually be gotten from a sign-in form, and sign-in forms usually use POST, you should probably do that. Use POST instead of GET.
included files have access to all the global variables in the file from which they are included.
File#1:
// index.php
$username = $_POST['user'];
include('header.php');
File#2:
// header.php
<div id="header">
<p>You are logged in as user "<?= $username ?>"</p>
</div>
The variable you set in index.php $username is available for use in header.php.
Ok so there's a fair few things you need to consider here, but we all had to learn once so I'll try and cover most of them.
Firstly (as #TrentonMaki has said): DO NOT USE USERNAMES IN URLs. If this site is going live, it is probably the most dangerous thing you can do, aside from printing out your passwords onto the screen.
You must read about authorisation and authentication before you continue.
Secondly, in the interests of learning: the $_SESSION super-global is not the right one to use for URL variables. We call URL variables "GET" variables and therefore they are accessible like this:
$user = mb_convert_encoding($_GET['myVar'], ‘UTF-8′, ‘UTF-8′);
$user = htmlentities($user, ENT_QUOTES, ‘UTF-8′);
These functions 'escape' the data in the variables to make them safe from XSS and SQL Injection attacks (there are alot of other precautions you need to take as well - but they are outside of the scope of this question).
In terms of Sessions, these are variables that are stored in the server memory and persist between pages. there are several considerations when using Sessions (security vulnerabilties like "Session Hijacking") and things you can do to make Sessions safer, but here is how they basically work.
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//set a session var
$_SESSION['myVar'] = "myString";
Now when a new page is loaded you can get the value of a $_SESSION var:
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//get a session var
$myVar = $_SESSION['myVar'];
Some other topics you should definitely learn before you go any further:
mysqli extension - do not use the mysql functions - this is by far the most common mistake new PHP developers make
Prepared statements - these are a MUST for live data security. You should learn them so you never use anything else.
Note :
1.Passing Variable above included file will passing variable to all included script
2.session_start(); must ONLY ONTOP of script and call only session_start(); to avoid session already started error.
<?php
session_start();
$username = $_POST['user'];
include('header.php');
?>

Is it acceptable to open and then close the session for an external module?

I'm writing a small reusable user manager for my projects that will use services as facebook, persona.org for login. From the point of view of each web, it's an include and a couple of echoes. However, it uses $_SESSION, so I need it initialized. For that I use this code in 'include.php':
<?php
if(session_id() == '') {
if (headers_sent()) {
throw new Exception ("You must include this file before sending any header.");
}
session_start();
$NoSession = 1; // Leave everything as it was before
}
// MAIN CODE HERE
if ($NoSession) {
session_destroy();
}
Is it a good idea to destroy the session with session_destroy() or is it acceptable to leave the session opened for this situation? My point at destroying it is leaving the variables environment as it was before of including the code, making the smallest possible footprint.
It's perfectly acceptable to leave it open - it's has a negligible footprint. session_destroy() doesn't actually close the session - you need to do a bit more (see the example in the docs).
It's also worth saying you need to call session_start(); to use $_SESSION variables, even if a session is left over from the last page visit.

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)){
}

To improve login code in PHP by Sessions

Which one is the better way to handle login in PHP?
#1 PHP.net
$email = $_POST['email'];
$password = $_POST['password'];
if($user->connection($email,$password)){ // user logging validation
session_start(); //start the session
$_SESSION['user_logged'] = true; // user logged in
header('location : control_panel.php'); // go to control panel
}
else { // go back to logging page
header('location : logging.php?' . $user->error_string);
}
#2 Me after Paul Dixon's improvements and Sebasgo's improvements
if (isset($_REQUEST['email'])) {
$result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users
WHERE email=$1;");
$passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email']));
session_start();
$_SESSION['logged_in'] = false;
if ($passhash_md5 == $_REQUEST['passhash_md5']) {
$_SESSION['logged_in'] = true;
}
header('Location: index.php');
The code #2 has $_REQUEST commands because I am still trying to get it work.
You shouldn't try to manage the session ids yourself. A simple scheme like the one you propose (incrementing the session id by one for every new session) contains a serious security issue: A user with freshly generated session id can trivially guess other valid session ids by trying ids slightly smaller than its own. Thus it is very easy two acquire someone else's session.
If you let PHP manage the generation of new session ids for you, PHP uses a pseudo random generator to create the new ids, which will be hard to guess for a potential attacker. This prevents the above outlined attack scenario effectively.
Additionally, you will virtually never want to access $_SESSION before calling session_start() because before the session array will be always empty. Therefore your test of empty($_SESSION['SID']) will always raise false.
Bottom line: I strongly recommend you to stick to the simple way of managing login like PHP.net does it.
You force all new sessions to have the same ID, which means everyone will be sharing the same session! Probably not what you intended?
You can omit the call to session_id() and just let PHP take care of creating a unique id for the session.
Also, you should really call session_start before using the $_SESSION array to ensure it is populated with any current session variables.

Transfer variables between PHP pages

I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.
Try changing your session code as this is the best way to do this.
For example:
index.php
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo 'Click to continue.';
} else {
// form
}
?>
nextpage.php
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>
However I'd probably store something safer like a userid in a session rather than the user's login credentials.
I Agree with carson, sessions should work for this. Make sure you are calling session_start() before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is not intrinsically unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.
There are several ways:
use sessions (but don't forget to call session_start() on every page you'll use the session data store ($_SESSION))
append your data to the query string of the "next" page ($_GET)
post your data to the "next" page ($_POST)
The session-way is the only way on which the data does not "leave" the server as it's stored on the server itself. For all other ways mentioned above you have to take care of sanitizing and validating the data on the receiving page.
The most simple way would be
//page1.php
session_start();
$_SESSION['user']='user';
$_SESSION['password']='password';
//page2.php
session_start();
echo $_SESSION['user'] . ' ' . $_SESSION['password'];
You can try using POST and GET methods for transferring user inputs within PHP scripts.
PHP GET
PHP POST
I agree too, sessions are the best solution. See this chapter from Web Database Applications with PHP & MySQL for some examples.

Categories