php利用curl登录页面并post提交数据上传文件

2015-11-26 寒川 网页编程

好久没写博客了,不知道的人或许会以为博客已经停止更新了,其实不然,确实最近比较忙。偶尔有空也只是上来删删一些垃圾留言。今天特地总结一下php的curl,显示用curl登录目标网站,接着携带cookie提交数据,用post方式提交,接着再上传一张本地图片。贴出这比较low的代码备用。闲话就不多说了,下面看招:

<?php
function login(){
	$url = 'http://xx.com/login.php';//登录地址
	$data = array(
		'username'=>'用户',//用户名,注意与原表单一致
		'password'=>'password'//用户密码,注意与原表单一致
	);
	$cookie_file = tempnam('./tmp','cookie');
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');  
	curl_setopt($ch, CURLOPT_HEADER, 0);  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
	curl_setopt($ch, CURLOPT_MAXREDIRS, 1);  
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);  
	curl_setopt($ch, CURLOPT_POST, 1);  
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
	curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);  
	curl_exec($ch);  
	curl_close($ch);
	return $cookie_file;
}

function post(){
	$data = array(
		'name'=>1,//注意与原表单一致
		'test'=>2,//注意与原表单一致
	);
	$cookie = login();
	$url="http://xx.com/xx.php";//数据提交地址
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');
	curl_setopt($ch, CURLOPT_HEADER, 0);  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);  
	$str = curl_exec($ch);  
	curl_close($ch);
	unlink($cookie);
	return $str;
}


function uploadfile(){
	$cookie = login();
	$fields['data'] = 'data';//注意与原表单一致
	$fields['file'] = '@/www/web/xx.jpg;type=image/jpeg;filename=xx.jpg';//注意与原表单一致
	$url='http://xx.com/upload.php';//数据提交地址
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36');
	curl_setopt($ch, CURLOPT_HEADER, 0);  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch,CURLOPT_REFERER,'http://59.151.121.119:8082/mss/uploadHkrtImage.jhtml');
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);  
	$str =  curl_exec($ch);  
	curl_close($ch);
	unlink($cookie);
	return $str;
}
具体使用代码的时候记得注释部分修改成自己的。

标签: php curl 模拟登陆 cookie curl上传

评论(0) 浏览(5229)

Powered by emlog 蜀ICP备12030225号

川公网安备 51042102000001号

sitemap