What is the difference between $_GET and $_POST in PHP and when should each be used?

$_GET and $_POST are both PHP superglobals used to collect form data, but they differ in how they send data. $_GET sends data through the URL as key/value pairs, visible in the address bar, while $_POST sends data in the HTTP request body, keeping it hidden. Use $_GET for non-sensitive data that can be visible in the URL, like search queries or pagination, and use $_POST for sensitive data like passwords or personal information.

// Example of using $_GET
if(isset($_GET['search'])){
    $search_query = $_GET['search'];
    // Perform search query using $search_query
}

// Example of using $_POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $username = $_POST['username'];
    $password = $_POST['password'];
    // Validate username and password
}