This is correct. This is the way generally used by most websites using PHP.
The $_SESSION is a super global variable that is only managed by your server.
What happens:
- You call
session_start()
- A cookie named
PHPSESSID (or anything that you name it in php.ini) with a cryptographically secure value will be generated.
- PHP declares a variable called
$_SESSION, which is internally stored with association to the generated cookie value.
Why it cannot be changed by other websites:
- The value of
$_SESSION is only stored internally. Not even the client knows its value. It only holds a cookie for session ID, but it doesn't even know what that session ID means, nor what other people's session ID should be.
- This session ID cookie cannot be stolen or modified by other websites. By default, the cookie path is set to your own domain, and the client should only send it to you. (If the client wants to send to other websites, it's leaking its own credentials and it is none of your responsibility but the bug of the client browser)
Unless you are running other websites on the same server, this won't be a problem (under normal circumstances).
As a side note, please be reminded that you should add a return; statement after using header("Location: index.php");. This is a common source of bugs, and in this context, it may expose your server to danger, because even though your browser won't display the content after it received the Location header, your server is actually still sending the data that should be generated for the user as if he has logged in.
TL;DR: if you have a script that should not send any data if client is not logged in, not adding the return; statement after header("Location: ..."); will make the server still send the data, but normal browsers will not display it (because it redirects), but if there is someone who tries to view the data sent (using methods as simple as curl without adding the -L option) will easily see them.