简体   繁体   中英

Use of session_id() and session_name

I am new to PHP. What I do for managing sessions in my code is, simply start session using session_start() . Reading around on web, I came across, session_id and session_name .

What is the use of session_id and session_name . Application based, where can we use session_name and session_id in Php.

How I write my code is:

<?php
   session_start();
   if(isset($_SESSION['name']))
   {
       //Render the page.
   }
   else
   {
       session_destroy();
       //redirect to some simple page.
   }
?>

As per my code, where can I use session_id or session_name . Is this a good style to write the code, or should I choose to use session_id and session_name ?

Thank you.

The Session name is the name of the cookie/url param stores the session_id. By default when you create a session, a special cookie will be created normally with the name PHPSESSID, the session_id, is the value of that cookie that later identifies you. You can change the default session name by using session_name, but you must call session_name, before session_start. Hope that helps.

EDITED.

Session will send a cookie, to your browser, remember PHP is configured to use COOKIES as session management.

Once the cookie has been created and sent to the browser, then you can access it like any other cookie, if you print_R($_COOKIE), you will see the php session cookie and its value.

The the very minimum, all you need is a call to session_start() , this will start a session for you, it must be called, before any output data is sent to the browser.

For example, this will cause error.

echo "Hello";
session_start();

This is because session_start() must be called before any output to is sent to the browser. So, why do you need session_name(), simply because it allows you to rename the cookie, as mentioned by default session name is PHPSESSID. Renaming the session lessens the chances of a hacker trying to find a cookie with the name PHPSESSID. Every php developer knows what the default session cookie name is, if I was a hacker, what cookie do you think I will look for first? But this is not a prevention mechanism.

The session_id(), is just to get the id of the session, it is not always used, it is there for convenience but also used if you trying to implement your own session management as PHP does allow you to do this.

In a nutshell, session_name or session_id, is not necessary to start a session. If you have further questions, you can follow me on my google page,

https://plus.google.com/113820735365251703271

and I will be happy to explain further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM