Phpsocket programming
A socket can be understood as a channel in which two computers communicate with one another.
Usage: Use the Fsockopen () function
See the previous article for specific usage. The parameters for the function are URL, port number, a variable that holds the error number, a variable that holds the error message string, and a timeout wait time. (only the first parameter is required)
Common Port tables:
|
Port number |
Main purpose |
|
21st |
Ftp |
|
22 |
Ssh |
|
23 |
Telnet |
|
25 |
Smtp |
|
80 |
Web |
|
110 |
POP |
Where several parts of the URL are: Protocol name (scheme), host, port number (port), file path (path), and query parameters.
When the URL is http://www.example.com/view.php?week=1#demo:
|
Index |
Value |
|
Scheme |
http |
|
Host |
www.example.com |
|
Port |
80 |
|
User |
|
|
Pass |
|
|
Path |
view.php |
|
Query |
Week=1 |
|
Fragment |
#demo |
Common HTTP Status codes:
|
Code |
Meaning |
|
200 |
Ok |
|
204 |
NO Content |
|
400 |
Bad Request |
|
60s |
Unauthorized |
|
403 |
Forbidden |
|
404 |
Not Found |
|
408 |
Time Out |
|
5** |
Server Error |
"Example":
<? PHP function Check_url ($url) {//parse URL $url _pieces = Parse_url ($url); Set the correct path and port number $path = (isset ($url _pieces[' path '))? $url _pieces[' path ']: '/'; $port = (isset ($url _pieces[' Port '))? $url _pieces[' Port ']: ' 80 '; Use Fsockopen () to try to connect if ($fp =fsockopen ($url _pieces[' host '), $port, $errno, $errstr, 30)) {//Established as Write data to the server $send = "HEAD $path http/1.1\r\n"; $send. = "Host: $url _pieces[' host ']\r\n"; $send. = "connection:close\r\n\r\n"; Fwrite ($fp, $send); Retrieves the HTTP status code $data = Fgets ($fp, 128); Close connection fclose ($FP); Returns the status code and class information list ($response, $code) = Explode ("', $data); if (code = =) {return Array ($code, ' good '); }else{ Return Array ($code, ' bad ');//array second element as a CSS class name}}else{ No connection to return array ($ERRSTR, ' bad '); }}//create URL list $urls = Array (' http://www.sdust.com ', ' http://www. example.com ')//Adjust the time limit for PHP scripts: set_time_limit (0);//Unlimited long time to complete the task//verification Url:foreach ($urls as $ur L) {list ($code, $class) = Check_url ($url); echo "<p><a href =\" $url \ "> $url </a> (<span class =\" $class \ "> $code </span>) </p>"; }?>
Note: The advantage of using the Fsockopen () function is greater than the fopen () function: fopen () will only be used if Allow_url_fopen is set to true in PHP, and Fsockopen () is not limited.
PHP socket programming using the Fsockopen () function