What are the differences between using sessions and cookies for storing user data in PHP?

Using sessions is generally more secure than using cookies for storing user data in PHP because session data is stored on the server side, while cookies are stored on the client side. Sessions also automatically handle the creation and management of a unique session ID for each user, making it more difficult for malicious users to manipulate. To use sessions in PHP, you can start a session using session_start() at the beginning of your script and then store data in the $_SESSION superglobal array. Here is an example:

<?php
// Start the session
session_start();

// Store data in the session
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';

// Retrieve data from the session
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// Destroy the session
session_destroy();
?>