Rumah  >  Artikel  >  pembangunan bahagian belakang  >  服务器端PHP生成curl命令行

服务器端PHP生成curl命令行

巴扎黑
巴扎黑asal
2017-03-23 15:25:431600semak imbas

记录请求到log,为了方便后续排查问题,在PHP里调用一个方法,实现将curl串记录下来即可方便复现请求。

<?php
/**
 * Author: xishizhaohua@qq.com
 * Date: 2015/11/2
 * 
 */
function getCurlCommand()
{
    try {
        if (php_sapi_name() == &#39;error cli&#39;){
            throw new Exception("cli");
        }
        $curlCommand = &#39;curl &#39;;
        $postData = $getData = &#39;&#39;;
        if($_GET) {
            $gets = http_build_query($_GET);
            $getData .= strpos($curlCommand, &#39;?&#39;) ? &#39;&&#39; . $gets : &#39;?&#39; . $gets;
        }
        if ($_SERVER[&#39;REQUEST_METHOD&#39;] == &#39;POST&#39; ) {
            $posts = http_build_query($_POST);
            $postData = &#39; -d "&#39; . $posts . &#39;"&#39;;
        }
        $path = isset($_SERVER[&#39;SCRIPT_NAME&#39;]) ? $_SERVER[&#39;SCRIPT_NAME&#39;] : $_SERVER[&#39;PHP_SELF&#39;];
        $curlCommand .= &#39;"&#39; . "http://{$_SERVER[&#39;HTTP_HOST&#39;]}" . $path . $getData . &#39;"&#39;;
        if ($postData) {
            $curlCommand .= $postData;
        }
        $headers = array();
        if (function_exists(&#39;getallheaders&#39;)) {
            $headers = getallheaders();
        } else {
            foreach ($_SERVER as $name => $value) {
                if (substr($name, 0, 5) == &#39;HTTP_&#39;) {
                    $headers[str_replace(&#39; &#39;, &#39;-&#39;, ucwords(strtolower(str_replace(&#39;_&#39;, &#39; &#39;, substr($name, 5)))))] = $value;
                }
            }
        }
        foreach ($headers as $key => $value) {
            if($key == &#39;Accept-Encoding&#39;)  $value = str_replace(&#39;gzip, &#39;,&#39;&#39;,$value);
            $curlCommand .= &#39; -H "&#39; . $key . &#39;:&#39; . $value . &#39;"&#39;;
        }
        return $curlCommand;
    } catch (Exception $e) {
        return $e->getMessage();
    }
}
echo getCurlCommand();

eg: 

curl “http://localhost/other/serverInfo.php?dd=ddd” -H “Host:localhost” -H “Connection:keep-alive”
 -H “Cache-Control:max-age=0” -H “Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8”
  -H “User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36”
   -H “DNT:1” -H “Accept-Encoding:deflate, sdch” -H “Accept-Language:zh-CN,zh;q=0.8,en;q=0.6” -H “Cookie:name=shikiliu; email=xishizhaohua%40qq.com”

  

相关文章:

使用Curl命令查看请求响应时间方法

服务器端PHP生成curl命令行

Linux系统curl命令

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php显示遇到乱码数据库是mysqlArtikel seterusnya:PHP字符串的连接