PHP using the socket method get, Post data instance _php instance

Source: Internet
Author: User
1. Get the Web content get by using PHP
Copy CodeThe code is as follows:
<?php
function Socketget ($url, & $ret)
{
$URLARR = Parse_url ($url);
$host = $URLARR [' Host '];
$port = Isset ($urlArr [' Port '])? $URLARR [' Port ']:80;
$path = Isset ($urlArr [' path '])? $URLARR [' Path ']: "/";
$fp = Fsockopen ($host, $port, $errno, $errstr, 30);
if (! $fp)
{
echo "$errstr ($errno)
\ n ";
return false;
}
Else
{
$out = "GET $path http/1.1\r\n";
$out. = "Host: $host \ r \ n";
$out. = "connection:close\r\n\r\n";
$ret = "";
Fwrite ($fp, $out);
while (!feof ($FP))
{
$ret. = Fgets ($fp, 128);
}
Fclose ($FP);
}
return true;
}
?>

2. Use PHP to POST data to the page
Copy the code code as follows:
<?php
Function Socketpost ($url, $ Data, & $ret)
{
$urlArr = Parse_url ($url),
$host = $urlArr [' host '];
$port = Isset ($urlArr [' Port '])? $ urlarr[' Port ']:80;
$path = isset ($urlArr [' path '])? $URLARR [' Path ']: "/";
$fp = Fsockopen ($host, $port, $errno, $errstr, 30);
if (! $fp)
{
echo "$errstr ($errno)
\ n";
return false;
}
Else
{
$out = "POST $path http/1.1\r\n";
$out. = "Host: $host \ r \ n";
$out. = "Content-type:applicatio N/x-www-form-urlencoded\r\n ";
$out. = "Content-length:". strlen ($data). " \ r \ n ";
$out. = "connection:keep-alive\r\n\r\n";
$out. = $data;
$ret = "";
Fwrite ($fp, $out);
while (!feof ($fp))
{
$ret. = Fgets ($fp, +);
}
Fclose ($FP);
}
return true;
}
?

If post is an error, turn $out = "connection:keep-alive\r\n\r\n"; keep-alive in to close

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.