happy cat image

Start Web Coding

Your First step toward web coding,
Start Web Coding

change UI

Session

What is Session.

It is the period from the recognition of each other through message exchange to communicate between processes until the completion of communication.
Unlike cookies, sessions store login information on the server for security reasons, enabling users to further secure their login information.
It provides a way to use previous access information when you visit a website and stay connected.
The server assigns unique IDs to users visiting the website, stores them in a specific directory on the server, and keeps the user's login information available.
To register a session, first create a session by initializing the session, and use session_start() to activate the current session ID.
session_start(); Initialize the session.
$_SESSION ['variable name'] // register the session.
So let's initialize and register the session with the following example.
Create a session folder in the htdocs folder.

make Session Folder

/htdocs/session/session.php

<?php
    session_start();
    $_SESSION['device'] = 'MacBook Pro 16';
    $_SESSION['color'] = 'Space Gray';

    echo "Created a session <br>";
    echo "Click the link below to check your session. <br>";

    echo "<a href='session2.php'>go</a>";
?>

atom

session atom php image

Enter the above source
and save it. Save the source as session2.php.


/htdocs/session/session2.php

<?php
    session_start();
    $ssid = session_id();
    echo "session id is {$ssid} <br>";

    echo "my device is ".$_SESSION['device'].'<br>';
    echo "my color is ".$_SESSION['color'];
?>

atom

session atom php image

Run session1.php in your web browser and click the go link.

result - session.php

php image

Press to display the screen below.

result - session2.php

php image

$_SESSION is available since php4.1.
Previous versions should use the session_register() function.
And session should be declared first, otherwise ob_start() function should be used. It's like a cookie !!

/htdocs/session/session3.php

<?php
    ob_start();
    echo "Write ob_start() above because it uses the output statement first <br />";
    session_start();
    $ssid = session_id();
    echo "{$ssid} <br /><br />";
    echo "my device is ".$_SESSION['device'].'<br>';
    echo "my color is ".$_SESSION['color'];
?>

atom

php image

result - session3.php

php image

To delete a session,
unset($_SESSION['session name']);

Let's delete $_SESSION['color']

/htdocs/session/delSession.php

<?php
    session_start();
    $id = session_id();
    echo "Delete some of the registered sessions<br />";
    echo "======================================== <br />";
    unset($_SESSION['color']);
    echo "color session deleted <br />";

    echo " device ".$_SESSION['device']."<br />";
    echo " color ".$_SESSION['color']."<br />";
?>

atom

php image

result

php image

color session was deleted...

강좌로 돌아가기