What exactly is a resource in PHP and how does it relate to accessing external entities like MySQL or programs with functions like fsockopen()?

A resource in PHP is a special variable that holds a reference to an external entity such as a file, database connection, or network socket. When accessing external entities like MySQL or programs with functions like fsockopen(), PHP returns a resource that represents the connection or communication channel. To properly interact with these external entities, you need to use functions specific to the type of resource being handled.

// Example of using fsockopen() to open a network socket
$socket = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$socket) {
    echo "Error: $errstr ($errno)";
} else {
    fwrite($socket, "GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n");
    while (!feof($socket)) {
        echo fgets($socket, 1024);
    }
    fclose($socket);
}