模拟表单提交数据php js模拟表单提交

请教用Curl 在php 里面模拟表单提交 文本+文件的写法public function curl($url, $postFields = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($this-readTimeout) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this-readTimeout);
}
if ($this-connectTimeout) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this-connectTimeout);
}
//https 请求
if(strlen($url)5strtolower(substr($url,0,5)) == "https" ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
if (is_array($postFields)0count($postFields))
{
$postBodyString = "";
$postMultipart = false;
foreach ($postFields as $k = $v)
{
if("@" != substr($v, 0, 1))//判断是不是文件上传
{
$postBodyString .= "$k=" . urlencode($v) . "";
}
else//文件上传用multipart/form-data,否则用www-form-urlencoded
{
$postMultipart = true;
}
}
unset($k, $v);
curl_setopt($ch, CURLOPT_POST, true);
if ($postMultipart)
{
foreach ($postFields as $k = $v){
if ("@" == substr($v, 0, 1)){
$tempffile = preg_replace ('/^\@/' ,'' ,$v);
$advfield[$k] = new CURLFile($tempffile);
}else {
$advfield[$k] = $v;
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $advfield);
unset($k, $v, $advfield);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); //田村改
//curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' = new CURLFile(realpath('image.png'))]);
}
else
{
curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
}
}
$reponse = curl_exec($ch);
if (curl_errno($ch))
{
throw new Exception(curl_error($ch),0);
}
else
{
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (200 !== $httpStatusCode)
{
throw new Exception($reponse,$httpStatusCode);
}
}
curl_close($ch);
return $reponse;
}
表单列表是 $postFields传入参数
数组 , 如果有文件,就在数组的值 前面加@
已经做好的 集成类 的实现 其他类字段和方法没给出,写不下了 。
但是大致的实现过程应该可以看懂了
php curl 模拟post表单向提交数据不需要抓取数据的话 , 就只要分析一下对方网站表单需要的字段,然后把action的地址改成对方网站的就提交路径就行了,但如果对方网站提交时要获取cookie的话才需要用curl
PHP curl 模拟表单数据流multipart/form-data上传文件在调用公众号接口".$token."type=".$type;
上传永久素材文件总是返回 "{\"errcode\":41005,\"errmsg\":\"media data missing\"}"
经过多次测试使用下面的方式,可以正常上传
//调用测试
protected static $url;
protected static $delimiter;
protected static $instance;
public function index()
{
static::$delimiter = uniqid();
$basename = Request::instance()-root();
if (pathinfo($basename, PATHINFO_EXTENSION) == 'php') {
$basename = dirname($basename);
}
$result=$this-wxAddMaterial($token,$basename.'/upload/images/gnlog.jpg','image');
}
// 新增其他类型永久素材
public function wxAddMaterial($token,$filename='',$type='') {
// 设置请求参数
static::$url = "".$token."type=".$type;
$filePath = str_replace('\\', '/', $filename);
// 发送请求
$imginfo=pathinfo($filePath);
$fields = array(
'media'=file_get_contents(".".$filePath),
'filename'=$imginfo["basename"],
);
$res = $this-putPart( $fields);
// 发送请求
return $res;

推荐阅读