PHP 的get、post请求小记

本文详细介绍了如何使用PHP通过GET和POST方式发送HTTP请求的方法。包括利用file_get_contents函数发送GET请求,以及使用curl库进行GET和POST请求的具体实现过程,并提供了发送XML格式POST数据的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PHP发送GET、POST请求

发送 GET 请求

1.调用 file_get_contents 函数,以 get 方式获取内容

<?php
    $url = "http://username:password@localhost:81/phpGetTest/index.php";
    $html = file_get_contents($url);
    echo $html;
?>

2.使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展

<?php
    $url = "http://username:password@localhost:81/phpGetTest/index.php";
    $ch = curl_init();
    $timeout = 5;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    echo $file_contents;
?>

发送 POST 请求

1.使用curl库,发送 xml 数据

<?php
    $postUrl = "http://username:password@localhost:81/phpPostTest/index.php";
    $xmlData = "
        <xml>
            <ToUserName>ad775b217</ToUserName>
            <FromUserName>tWy3zC3xUgQMR5coXif5SA</FromUserName>
            <CreateTime>1366181013</CreateTime>
            <MsgType>text</MsgType>
            <Content>我的测试</Content>
            <MsgId>5867702771251151243</MsgId>
        </xml>";
    $header[] = "Content-type: text/xml"; //定义content-type为xml
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_URL, $postUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
    $response = curl_exec($ch);
    if(curl_errno($ch)) {
        print curl_error($ch);
    }
    curl_close($ch);
    echo $response;
?>

参考:
http://blog.sina.com.cn/s/blog_6c971aa301018gx5.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值