创星网络[分享知识 传递快乐]
标题:
用curl 实现远程数据提交,支持文件上传
[打印本页]
作者:
luinstein
时间:
2012-10-9 18:23
标题:
用curl 实现远程数据提交,支持文件上传
不作赘述,请看程序中的注释和具体运行效果
example.php:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
require_once("client.php");
$curl = new CurlForm("http://pams.cn/server.php");
$curl->post();
}
?>
<div>
<form enctype="multipart/form-data" action="" method="post">
<input type="text" name="name" />
<input type="file" name="file" />
<input type="file" name="file1[]" />
<input type="file" name="file1[]" />
<input type="submit" />
</form>
</div>
复制代码
client.php:
<?php
/**
* Class CurlForm
*
* submit form data to a remote server use CURL
* file upload support
*
* @link http://www.pams.cn
* @author Gavin yang
* @msn: athotmail88 @ hotmail.com
*/
class CurlForm
{
/**
* url where you want to submit the form
* @var String
*/
private $remoteUrl;
/**
* form vars
* @var Array
*/
private $postvars = array();
/*
* Constructor for CurlForm
* @param String $remoteUrl url where you want to submit the form
*/
public function __construct($remoteUrl)
{
$this->remoteUrl = $remoteUrl;
/*处理提交上来的表单变量,将post变量和files变量同时放入$this->postvars 中,注意,这里是返回的是数组,当然如果只是post变量也可以是字符串"a=b&c=d"的形式,如果含有files变量,就只能放在数组里面*/
if(isset($_POST))
{
foreach ($_POST as $var => $val)
{
$this->postvars[$var] = $val;
}
}
/*上传文件的过程实际上分两步,第一步将文件上传到本地服务器,然后取得文件在本地服务器的缓存地址,也就是tmp_name;第二步是将这个缓 存文件的数据发送到远程服务器,当然读取文件数据的过程已经在curl函数内部实现了,只要你在文件地址前面加上"@",curl就会认为这是个要传送的 附件,但要保证这个文件是真实存在的。这样远程服务器端就接收到本地服务器提交过去的表单,由于向远程服务器上传的文件是本地服务器上的缓存文件,所以要 取得原始文件的文件名,在post变量里我给增加了一个叫做'filename'的变量,它是和files变量一一对应的*/
if(isset($_FILES))
{
foreach ($_FILES as $var => $val)
{
if (is_array($val['tmp_name']))
{
foreach ($val['tmp_name'] as $k=>$fname)
{
$this->postvars[$var."[$k]"]= "@".$fname;
$this->postvars['filename'."[$var][$k]"]= $val['name'][$k];
}
}
else
{
$this->postvars[$var] = "@".$val['tmp_name'];
$this->postvars['filename'."[$var]"] = $val['name'];
}
}
}
}
/*
* post form to remote server
*/
public function post()
{
set_time_limit(0);
$ch = curl_init();
//设定远程地址
curl_setopt($ch, CURLOPT_URL, $this->remoteUrl );
//post方法
curl_setopt($ch, CURLOPT_POST, 1);
//表单变量
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postvars);
//设定是否直接显示返回的数据
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//设定是否显示头信息
curl_setopt($ch, CURLOPT_HEADER, false);
//设定是否直接输出页面内容 false为输出
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_exec($ch);
//出错则显示错误并退出
curl_errno($ch) && die(curl_error($ch));
//关闭资源
curl_close($ch);
exit();
}
}
?>
复制代码
server.php
<?php
print_r($_POST);
print_r($_FILES);
?>
复制代码
from:
http://blog.csdn.net/phphot/article/details/2151138
欢迎光临 创星网络[分享知识 传递快乐] (http://bbs.cxweb.com.cn/)
Powered by Discuz! X3