Does PHP session work when cookie is disabled?

Yes, PHP session works when cookie is disabled.

Relation between session and cookie

Every web visitor is assigned an unique id called session id which is either stored in cookie or propagated through URL.

The http request always sends all cookies to server end. As PHP session id is stored in cookie, the server gets the session id from cookie and detects the user.

Pass session id when cookie is disabled

The cookie can be disabled and may not available. As cookies are not always available, PHP provides an alternative way of propagating session id through URLs. As long as the session id is passed to the server through URLs, the server will be able to detect the user.

How PHP session can be used when cookie is disabled?

By modifying few settings in php.ini file we can use PHP session when cookie is disabled. Following are those settings:
session.use_cookies = 0
session.use_only_cookies = 0
session.use_trans_sid = 1
session.cache_limiter = ""

Instead of changing those in the php.ini file it is possible to use ini setting functions to change them on the fly. Following are those settings:
ini_set("session.use_cookies", 0);
ini_set("session.use_only_cookies", 0);
ini_set("session.use_trans_sid", 1);
ini_set("session.cache_limiter", "");
If we have done either of the above, then we are set with disabled cookie and ready to see how the PHP session id is propagated through URLs.

In this case PHP will do two things:

Rewrite all links

On every http request when a page is shown PHP will look for all the links and will add PHPSESSID with a value (similar to phq9dv6b8jbc48edqlrv5qs100) as an extra GET parameter with the links. Lets consider the following link:
<a href="/php-interview-questions">PHP interview questions</a> The above link will add PHPSESSID with a value as an extra GET parameter with it like below: <a href="/php-interview-questions?PHPSESSID=35cp2s8ien3jng3poje8hhiib2">PHP interview questions</a>

Add hidden input to form element

PHP will add a hidden element with the name PHPSESSID and the value will be the session id (similar to phq9dv6b8jbc48edqlrv5qs100). Lets consider the following form element:
<form> <input type="input" name="username"> </form>
The above form will add an hidden element called PHPSESSID with a value like below:
<form> <input type="hidden" name="PHPSESSID" value="q0l8g05i8gs5n7msmuvb91n1n1"> <input type="input" name="username"> </form>

Risks of URL based session

URL based session is not good and has greater security risk in compare to cookie based session.
Following is the scenario where URL based session is very risky:
1. Users may share an URL that contains an active session id to others. In that case multiple users will end up using the same session id which is a greater security risk. An hacker can get the session id and can impersonate as user and can do all the damage.

Comments