All Tutorials

Your One-Stop Destination for Learning and Growth

Membuat Sessi PHP: A Way to Store Data between Requests

PHP sessions are an essential feature for maintaining application state and user information between multiple requests. In this blog post, we'll discuss how to create and use PHP sessions.

Prerequisites

Before we dive into creating a PHP session, let's ensure you have the following prerequisites:

  1. A basic understanding of HTML and PHP.
  2. An environment to test your code (e.g., XAMPP or WAMP).

Creating Sessions

To create a session in PHP, you need to first start the session using the session_start() function at the beginning of your script:

<?php
session_start();
// Your code here
?>

After initializing the session, you can assign values to it using an associative array with keys. These values will be stored in a cookie or a server-side variable and are accessible during subsequent requests:

$_SESSION['name'] = 'John Doe';
$_SESSION['age'] = 25;

Accessing Sessions

You can access session data anywhere within your script using the $_SESSION superglobal array. For example, to display a user's name:

echo "Hello, " . $_SESSION['name'];

Updating Sessions

Updating sessions works in the same way as creating them. You can simply assign new values to existing keys or create new ones:

$_SESSION['last_visited'] = date('Y-m-d H:i:s');

Destroying Sessions

You can destroy a session using the session_destroy() function, which removes all data associated with the current session:

session_destroy();

Session Lifetime

By default, PHP sessions last until the user closes their browser. However, you can set a custom lifetime and path for your sessions using the ini_set() function:

ini_set('session.gc_maxlifetime', 86400); // session will expire after 1 day (in seconds)
session_start();
// Your code here

Conclusion

In conclusion, PHP sessions provide a simple yet powerful way to maintain state and user information between multiple requests. They can be used for various applications such as login systems, shopping carts, and more. In the next blog post, we'll explore how to use sessions for implementing a login system in PHP.

Published February, 2015