I have a PHP site but a portion uses a flash upload swf to post a file and some parameters to a PHP script.
When that swf posts parameters my PHP script doesn't know any of the session variables. Must be something funky with Flash and the cookies it sends.
Anyways, I could try to fix it in flash but I thought the easier way is to simply pass the session_id in a post parameter. However, once I receive this session_id in my PHP script, I don't know how to use it to lookup the session variables I really want (such as $_SESSION['username']). I don't want to pass $_SESSION['username'] as a POST parameter because I figure that would be too much of a security risk. A long random session_id seems much better.
You can use session_id():
string session_id ([ string $id ] ) session_id() is used to get
or set the session id for the current session.
Code in vanilla PHP would roughly look like this:
<?php
if( isset($_POST['session_id']) ){
session_id($_POST['session_id']);
session_start();
}
Not sure though whether it'll be easy to integrate with CakePHP.
Related
Before marking this question as a duplicate to php session_id algorithm without session?, I need to ask this...
currently I use session_id() to retrieve a value that is assigned to a user and store it in a database.
This link has more info on session_id(): http://php.net/manual/en/function.session-id.php
Later I found out that I can create my own configuration into a single cookie of smaller size than the size of a standard PHP session cookie when I check the HTTP header response from the pages in both cases.
I also found out to use session_id(), sessions need to be started (can be called via session_start()), but every time one is started, PHP creates a session cookie along with other cookies I send, making the HTTP header response bigger.
In order to keep things consistent with the data in the database, how does PHP calculate the value returned from session_id()? I want to write my own function to replace it.
You can find the entire source for that function here. It's the latest version though, so be wary of any differences from your PHP version.
I have an application with an index page, where the user can enter a login and a password. Then they are submitted as POST variables, and if they are both correct, my script creates a session var as follows :
$_SESSION['auth'] = $login;
and the index page echoes a menu. If they are not, the login window is displayed again, as if the user went on the index page for the first time (with an error message under the required fields).
For now, I verify if the session variable is set :
<?php
include 'functions.php'; //this file contains session_start()
if (!isset($_SESSION['auth'])) {
header("Location: index.php");
exit();
}
?>
<html>
Html stuff with jquery...
</html>
Do I have to put all my html stuff in brackets within an else statement, or my page is secured enough ? Even if the user is redirected, the html part is still got by his browser, isn't it ?
I have several PHP pages on my server, and at the beginning of each one I make the same test as above. I also make this verification when the user comes on the index page (if he has already signed in, I don't want him to log-in again).
Assuming my script is safe (all the information provided by the user is checked on server side), what is the best way to work with secure sessions ?
It's great you are thinking about security, but allow me to explain a little on how sessions and session cookies work.
First of all cookies only allow a limited amount of data stored in them, I forget how much but I know it's not limitless. So how do severs allow you to store all that session data. What happens is the actual session cookie only stores the session id. On the server there is an actual physical file that has the session data in it. So when a client connects they send the session id, which in turn tells what file to use. Therefor, the session is as secure as the severs filesystem and the algorithm used to create the cookie's id. No actual session data ( besides that id ) leaves the server.
That said there are 2 settings that might help ensure sessions are safe.
These are httponly and secure, you can read more about them here
http://php.net/manual/en/session.configuration.php#ini.session.cookie-httponly
Now the short of it is, secure means to only transmit the session data ( the session id ) over Https, this only works if you have https setup on your server and website. Httponly, tells the browser that the cookie should only be sent over http ( or https ) not by client-side scripting. However as you have no control over what browser the client uses, or if their computer has been compromised in some way that will tell the browser otherwise ( although I don't know of any exploits that might do that ) you really are just making a suggestion to the client machine.
Now as far as the security of the actual data, any input from anywhere even your own database should always be treated as potentially insecure. This doesn't mean you have to check it everywhere, mainly that you escape html when outputting to the page, and that you use proper means to prevent sql injection into the database. As a general rule these should be done at the point of entry.
For example, when outputting content to a page that should not have html, simply use html_entities etc.. when outputting it. When using data in sql, use prepared statements there. You see you don't need to check the $_POST data every time you touch it, just check the data before using it for something that could be exploited, such as saving it in the database.
Lets take a small example function ( assume its in a user class )
public function getUser( $id ){
$sql = "Select * from user where id = $id"
//execute sql
}
We would never do this using PDO but lets assume this is old school stuff, you filter the data from a login form elsewhere, so when you set this up you assume its always a clean a id, because you filter it at the login form. Then latter you need a user from the session. Well you have the id there too, so you use it. Now is that id from the session clean, who knows right. Maybe it's an id from a file, or some other obscure place. Who knows where an Id can come from ( when we make the user class ). So what we do now-a-days is check that or use a prepared statement "at the point we use" the data, the point of entry. Then we don't care where the data came from. Because, it is always being cleared at the prepared statement, just before we use it in the database. That way it is always 100%, no question asked, clean. We can see it right there where we run the query from. We don't need to worry if we make a new login form latter. Maybe you add a pop-up login form somewhere? Dosn't matter, your sql will always be clean. Now, I am not saying not to check it at the login form. Never hurts to be safe, not to mention you might want to validate other things there, email format, uniqueness of a username etc. But, the critical point, is covered.
Make sense?
To address your comment about not using cookies ( I should have explained this at the beginning ). By it's very nature the internet is stateless. What this means is that every page reload is essentially a new connection. The only way to maintain a login ( or any data across reloads ) is to pass some data between requests. There is generally only a few ways to do this, they are
$_POST, $_GET, $_FILE, $_COOKIES. Notice how they are formatted, that's a hint, they are called super globals.
http://php.net/manual/en/language.variables.superglobals.php
By the way we have Netscape to thank for both Cookies and Javascript, both of which IE "borrowed", to me it's sad I don't see Netscape Navigator anymore. I remember that from the AOL 3.0 days, that was before you could embed images in email. You old timers know what I am talking about... Churr.Beep.bong.Cherrrk (various analog modem noises )... streaming video what's that, it's like 1.5 days to download a song. & Pr#y 2 teh GodZ of de inTerWeBz MomZ do4't g3t a [ call .... L33t BaBy >:-)~ ^v^
Is it good way to pass variable between pages using $_GET method with url:
<a href="input_obj.php?id='$id'&method=plain
and take it in file input_obj.php with such code:
$id = $_GET['id'];
$method = $_GET['method'];
OR
using session - has someone idea how?
It depends on your needs, really, If you are passing search arguments between pages, for example, and the variables should be both persistent and be available to the end user (via bookmarking, for example), then pass them in the URL (but don't usually use quotes like you have around $id in "input_obj.php?id='$id'&method=plain)
If you are truly passing internal variables between scripts, this is better done via $_SESSION variables. Remember that end users can easily modify variables passed through URLs. Unless they are intended for use by the end user, that may be a real problem. By using $_SESSION, you insulate your script's variables from tampering by the end user when it's necessary to insulate them. (unless, of course, the variables are produced by other user input via GET/POST/COOKIE)
//page1.php
session_start();
$_SESSION['id'] = $id;
//page2.php
session_start();
echo $_SESSION['id'];
GET variables are a much better way to go. When you start dropping variables into the session, it can have side effects like copy/pasting a URL from browser to browser or trying to bookmark can bring up different pages (which consequently is a nightmare for SEO). Also, it can have complications if you ever start clustering your servers b/c you'll need to deal with session failover.
IMHO, the best solution is to use mod_rewrite to implement path-based variables...you get pretty URLs with all the benefits of GET vars.
GET is a reasonable way to pass variables to another page.
$_SESSION and cookies is another way, but it won't allow a user to bookmark a page.
POST is another way, but it requires form submission which would either need user intervention or javascript.
It depends on the what the data is for, its type and its length. Usually, passing variables in the query string is fine.
Be aware that when accepting mutable parameters, you need to verify they are what you expect them to be. For example, I could change ?id=5 to ?id=hello and possibly break your application. To remedy this, we could typecast the ID to an integer: $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
You could also use cookies. These are sent like this:
setcookie(name, value, expire, path, domain);
you can ommit the path and domain variables. This has to be declared before the tag. The name is just the name with which you will get it. The value is what wil be returned and expire is the time at which the cookie expires (it is writen in the form of time() + $timeTillExpire where timetillexpire is a variable or constant value you set). This of course has the limitation of if the person has cookies of it will not work.
You get a cookie with:
$_COOKIE["name"];
and returns value
the way you did works fine.
If you're just using variables in your PHP script, you don't really need to 'pass' them. You can create a variable globally and access it from another page.
the question is really simple, but i searched it many different ways and the results were not related to my question.
so if i have a session variable in a php file if i open an html page after that and then a php file again, will i be able to retrieve the data ? or do they all have to be adjacent?
I tried php->html->php but i couldn't get the variables on the other side. maybe Im doing something wrong.
Thanks in advance
Not 100% sure what you mean, but if by "open" you mean in the browser, the calls do not need to be adjacent. You just need to do a session_start() in every PHP script in which you want to use session data.
Adjacency is not something that is really relevant for this question.
in PHP way of things, sessions are essentially files that contain serialized data on the server. The browser that called a script containing session_start() call receives a special token that identifies the session on the server, and it is normally (though not necessarily) stored as a cookie.
This effectively means that any php script that uses session_start() and receives a session id (via cookie or otherwise) will read and could use session data, unless it was removed from the server file system between the calls, or the session has expired (frankly, I'm not sure whether PHP removes the expired sessions on the server side).
Accessing anything outside of this model with the browser (html page, or even other sites) will not affect it in any way, unless these actions change or remove session id.
yes...session variable can survive php->html->php.
But on every php page ...very first line should be session_start()
This easy way (I guess): Set a cookie storing the session ID on the first php page. This way, every other php page can access the session ID and use it to restore the stored data, not matter how many (even foreign) pages were in between.
does any body have any info/links as to how to integrate a cookie based session system? i've used file/mysql, and am currently using memcached. i wanted to play with apc sessions, but thought i'd give a go at cookies, only i don't know much about it.
i imagine i'd have to write my own session handler class?
In PHP session data is usually stored in a file. The only thing stored in the cookie is a session identifier. When sessions are enabled and a valid session cookie is found, PHP loads the users session data from the file into a super global called funnily enough SESSION.
Basic sessions are started using session_start(); called before any text is sent to the browser. then items are added to or removed from the session object using simple array indexing eg.
$_SESSION['favcolour'] = 'blue';
later...
$favcolour = $_SESSION['favcolour'];
basic cookie only sessions (no local storage) can be created with a call to
set_cookie('favcolour','blue'[,other params]);
before any text is sent to the browser, then retrieved from the cookie superglobal
$favcolour = $_COOKIE['favcolour'];
you don't need to call session_start() if doing cookie only sessions.
the optional [,other params] are more advanced and can be read about here http://www.php.net/manual/en/function.setcookie.php
Sessions can become a very complex discussion, I'd suggest doing some light work in them and then expand your knowledge.
DC
all you ever wanted to know about PHP sessions
http://www.php.net/manual/en/book.session.php
DC
To reuse PHP's session handling code you will need to add a write handler using session_set_save_handler and then do exactly nothing in that handler. That's because its called after the output to the browser is closed therefore you cannot send anything to the browser.
Before writing non header data to the browser use the set_cookie functions and store the contents of the $_SESSION array (after serialising and encrypting) into a cookie. when the applications start you can read the cookie unserialise it and put it into the $_SESSION array.
That's a quick hint at what to do as I have never done it, I prefer to write all my own cookie code. There may be some gotcha's but its not hard a few tests should find any gotcha's.
DC