本文将介绍curl的使用,根据常用的场景,提供调用curl实现请求的演示代码及服务端代码,方便大家学习使用。
curl命令后加网址,就可以看到网页源码。
curl www.csdn.net
<html>
<head><title>302 Foundtitle>head>
<body bgcolor="white">
<center><h1>302 Foundh1>center>
<hr><center>nginxcenter>
body>
html>
上例中,因为网址进行了跳转,而curl默认是不跟随跳转的,因此只获取第一次页面的源码。如果我们想跟随跳转,可以使用-L参数。
curl -L www.csdn.net
加入-L参数后,curl就会跟随跳转到新页面,返回新页面的源码。
保存网页源码到文件,使用-o参数加保存路径。
curl -o csdn.viewcode www.csdn.net
执行后,网页的源码会保存在csdn.viewcode文件中。
curl -i www.csdn.net
HTTP/1.1 302 Moved Temporarily
Server: openresty
Date: Sun, 17 Dec 2017 09:18:46 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Keep-Alive: timeout=20
Location: https://www.csdn.net
<html>
<head><title>302 Foundtitle>head>
<body bgcolor="white">
<center><h1>302 Foundh1>center>
<hr><center>nginxcenter>
body>
html>
如果只需要显示http response的头信息,使用-I
curl -I www.csdn.net
HTTP/1.1 302 Moved Temporarily
Server: openresty
Date: Sun, 17 Dec 2017 09:20:25 GMT
Content-Type: text/html
Content-Length: 154
Connection: keep-alive
Keep-Alive: timeout=20
Location: https://www.csdn.net
curl -v www.csdn.net
* Rebuilt URL to: www.csdn.net/
* Trying 101.201.172.229...
* Connected to www.csdn.net (101.201.172.229) port 80 (#0)
> GET / HTTP/1.1
> Host: www.csdn.net
> User-Agent: curl/7.49.1
> Accept: */*
>
< HTTP/1.1 302 Moved Temporarily
< Server: openresty
< Date: Sun, 17 Dec 2017 09:23:06 GMT
< Content-Type: text/html
< Content-Length: 154
< Connection: keep-alive
< Keep-Alive: timeout=20
< Location: https://www.csdn.net
<
<html>
<head><title>302 Foundtitle>head>
<body bgcolor="white">
<center><h1>302 Foundh1>center>
<hr><center>nginxcenter>
body>
html>
* Connection #0 to host www.csdn.net left intact
如果想要查看更详细的通讯过程,可以使用下面两个参数。
curl --trace trace.log www.csdn.com
curl --trace-ascii trace.log www.csdn.com
执行后,打开trace.log查看。
get方式
数据直接拼接到地址后面
curl "localhost/server.php?a=1&b=2&c=3"
服务端代码:
$param = array('a','b','c');
foreach($param as $v){
echo $v.'='.(isset($_GET[$v])? $_GET[$v] : '').PHP_EOL;
}
?>
post方式
数据要与地址分开,使用–data参数
curl -X POST --data "a=1&b=2&c=3" "localhost/server.php"
也可以简化为
curl -d "a=1&b=2&c=3" "localhost/server.php"
表单编码
如果数据没有进行编码,使用–data-urlencode参数执行编码,不过需要分开一个一个参数来编码。
curl -X POST --data-urlencode "a=哈哈" --data-urlencode "b=嘿嘿" --data-urlencode "c=呵呵" "localhost/server.php"
服务端代码:
$param = array('a','b','c');
foreach($param as $v){
echo $v.'='.(isset($_POST[$v])? $_POST[$v] : '').PHP_EOL;
}
?>
例如文件上传表单如下:
<form name="form1" method="post" action="test.php" enctype="multipart/form-data">
<p>file:<input type="file" name="file">p>
<p><input type="submit" value="submit">p>
form>
使用–form 或 -F参数
只上传图片
curl --form file=@/tmp/photo.jpg localhost/server.php
上传图片及提交其他参数
curl -F upload=@/tmp/photo.jpg -F upload_field=upload -F file_path=abc.jpg localhost/server.php
服务端代码:
$upload_field = isset($_POST['upload_field'])? $_POST['upload_field'] : 'file';
$name = explode('.', $_FILES[$upload_field]['name']);
$file_ext = array_pop($name);
$file_path = isset($_POST['file_path'])? $_POST['file_path'] : time().'.'.$file_ext;
$upload_flag = move_uploaded_file($_FILES[$upload_field]['tmp_name'], dirname(__FILE__).'/'.$file_path);
echo ($upload_flag==1? 'true' : 'false').PHP_EOL;
?>
curl --referer 'www.csdn.net' localhost/server.php
服务端代码:
echo 'REFERER:'.(isset($_SERVER['HTTP_REFERER'])? $_SERVER['HTTP_REFERER'] : '').PHP_EOL;
?>
模拟iPhone访问
curl --user-agent "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25" localhost/server.php
模拟chrome访问
curl --user-agent "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" localhost/server.php
服务端代码:
function isMobile() {
$agent = $_SERVER['HTTP_USER_AGENT'];
return stripos($agent, 'iPod;') !== false || stripos($agent, 'iPhone') !== false || stripos($agent, 'Android') !== false || stripos($agent, 'iPad') !== false;
}
echo (isMobile()? 'true' : 'false').PHP_EOL;
?>
模拟iPhone访问返回true,模拟chrome访问返回false。
获取返回的cookie
curl -c cookiefile url
请求时传递的cookie
curl -b cookiefile url
服务端代码:
if(isset($_COOKIE['username'])){
echo $_COOKIE['username'].' is login'.PHP_EOL;
}else{
$username = isset($_POST['username'])? $_POST['username'] : '';
$password = isset($_POST['password'])? $_POST['password'] : '';
if($username=='fdipzone' && $password=='654321'){
setcookie('username', $username, time()+3600);
echo 'login success'.PHP_EOL;
}else{
echo 'login fail'.PHP_EOL;
}
}
?>
没有带cookie时访问
curl localhost/server.php
执行后输出:login fail
登入获取cookie
curl -c /tmp/cookie -d "username=fdipzone&password=654321" localhost/server.php
执行后输出:login success
获取的cookie保存在/tmp/cookie文件中。
使用获取的cookie访问
curl -b /tmp/cookie localhost/server.php
执行后输出:fdipzone is login
表示能获取到请求的传递的cookie。
请求时带上自定义header。
curl --header "access-token:RGV2cXgxWHFVbEdVN1o2NFVkSG40Zmo1aXE" --header "lang:zh_CN" localhost/server.php
服务端代码:
/**
* 获取自定义的header数据
*/
function get_all_headers(){
// 忽略获取的header数据
$ignore = array('host','accept','content-length','content-type');
$headers = array();
foreach($_SERVER as $key=>$value){
if(substr($key, 0, 5)==='HTTP_'){
$key = substr($key, 5);
$key = str_replace('_', ' ', $key);
$key = str_replace(' ', '-', $key);
$key = strtolower($key);
if(!in_array($key, $ignore)){
$headers[$key] = $value;
}
}
}
return $headers;
}
print_r(get_all_headers());
?>
执行后输出:
Array
(
[lang] => zh_CN
[access-token] => RGV2cXgxWHFVbEdVN1o2NFVkSG40Zmo1aXE
[user-agent] => curl/7.49.1
)
有些地址需要HTTP认证,可以使用–user参数传递验证信息。
curl --user "user:pass" url
服务端代码:
if(!isset($_SERVER['PHP_AUTH_USER']))
{
header('WWW-Authenticate: Basic realm="localhost"');
header("HTTP/1.0 401 Unauthorized");
exit('Unauthorized'.PHP_EOL);
}else{
if (($_SERVER['PHP_AUTH_USER']!= "fdipzone" || $_SERVER['PHP_AUTH_PW']!="654321")) {
header('WWW-Authenticate: Basic realm="localhost"');
header("HTTP/1.0 401 Unauthorized");
exit('Unauthorized'.PHP_EOL);
}
}
$content = isset($_POST['content'])? $_POST['content'] : '';
header('content-type:application/json');
echo $content.PHP_EOL;
?>
不带验证信息请求
curl -d "content=abc123" localhost/server.php
执行后输出:Unauthorized
带验证信息请求
curl -d "content=abc123" --user "fdipzone:654321" localhost/server.php
执行后输出:abc123