How can one handle 403 errors when establishing a socket connection to a directory in PHP?

When establishing a socket connection to a directory in PHP, if you encounter a 403 error (Forbidden), you can handle it by checking the HTTP response code before proceeding with the connection. If a 403 error is detected, you can either display an error message to the user or handle it programmatically based on your requirements.

$socket = @fsockopen('example.com', 80, $errno, $errstr, 30);
if (!$socket) {
    echo "Error: $errstr ($errno)";
} else {
    // Check if HTTP response code is 403
    $header = "GET /directory HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n";
    fwrite($socket, $header);
    $response = fgets($socket);
    
    if (strpos($response, '403 Forbidden') !== false) {
        echo "403 Forbidden - Access Denied";
    } else {
        // Proceed with socket connection
    }
    
    fclose($socket);
}