Use PHP Socket to implement HTTP requests. Recently, HTTP remote access programs have been written much more. The main contacts are the WebHttpRequest class in the. NET class library and the general object Microsoft. XMLHTTP. with these convenient classes, we can
Recently, HTTP remote access programs have been written much more, mainly in contact. the WebHttpRequest class and Microsoft. XMLHTTP is a common object. with these convenient classes, we can simulate Web client access to other Web pages through C #, ASP, and Javascript. But today, I want to use PHP to implement similar functions, but I cannot find a direction for the moment, so I can only "enrich myself.
Currently, there are no classes similar to HttpRequest in PHP, but such an HttpRequest Class page is found in the official online document, however, this function may only exist in the CVS version...
To implement HTTP access, you only need to use a Socket to send a request and then read the returned information. So I used Socket to write an HttpRequest class. of course, I can also use the fsockopen () function. However, the difference between the two is not great. the specific code is included in the attachment, you can check it yourself.
SHostAdd = gethostbyname ($ armatchillpart [1]); if (empty ($ armatchillpart [4]) {$ this-> sUri = /;} else {$ this-> sUri = $ armatchillpart [4];} if (empty ($ armatchillpart [3]) {$ this-> iPort = 80 ;} else {$ this-> iPort = $ armatchillpart [3];} $ this-> addRequestHeader (Host :. $ armatchillpart [1]); $ this-> addRequestHeader (Connection: Close);} function addRequestHeader ($ sHeader) {$ this-> sRequestHeader. = trim ($ sHeader ). "";} func Tion sendRequest ($ sMethod = GET, $ sPostData =) {$ sRequest = $ sMethod. "". $ this-> sUri. "HTTP/1.1"; $ sRequest. = $ this-> sRequestHeader; if ($ sMethod = POST) {$ sRequest. = "Content-Type: application/x-www-form-urlencoded"; $ sRequest. = "Content-Length :". strlen ($ sPostData ). ""; $ sRequest. = ""; $ sRequest. = $ sPostData. "";} $ sRequest. = ""; $ sockHttp = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); if (! $ SockHttp) {die (socket_create () failed !);} $ ResSockHttp = socket_connect ($ sockHttp, $ this-> sHostAdd, $ this-> iPort); if (! $ ResSockHttp) {die (socket_connect () failed !);} Socket_write ($ sockHttp, $ sRequest, strlen ($ sRequest); $ this-> sResponse =; while ($ sRead = socket_read ($ sockHttp, 4096 )) {$ this-> sResponse. = $ sRead;} socket_close ($ sockHttp);} function getResponse () {return $ this-> sResponse;} function getResponseBody () {$ sPatternSeperate = //; $ arMatchResponsePart = preg_split ($ sPatternSeperate, $ this-> sResponse, 2); return $ arMatchResponsePart [1];} function getResponseHead () {$ SPatternSeperate = //; $ arMatchResponsePart = preg_split ($ sPatternSeperate, $ this-> sResponse, 2); return $ arMatchResponsePart [0];}?>
Microsoft. XMLHTTP is a common object. with these convenient classes, we can use...