我有一个问题,我可以在没有 curl 的情况下将文件上传到另一台服务器。因为不是每个服务器都有 CURL ...谢谢...
问问题
5192 次
2 回答
7
是的,可以将纯 PHP fopen 与 stream_context_create 一起使用。以下示例来自在线 PHP 手册(http://php.net/manual/en/function.stream-context-create.php):
function do_post_request($url, $postdata, $files = null)
{
$data = "";
$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
//Collect Postdata
foreach($postdata as $key => $val)
{
$data .= "--$boundary\n";
$data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
$data .= "--$boundary\n";
//Collect Filedata
foreach($files as $key => $file)
{
$fileContents = file_get_contents($file['tmp_name']);
$data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
$data .= "Content-Type: image/jpeg\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $fileContents."\n";
$data .= "--$boundary--\n";
}
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
'content' => $data
));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
//set data (in this example from post)
//sample data
$postdata = array(
'name' => $_POST['name'],
'age' => $_POST['age'],
'sex' => $_POST['sex']
);
//sample image
$files['image'] = $_FILES['image'];
do_post_request("http://example.com", $postdata, $files);
于 2012-12-09T07:17:58.827 回答
5
可以使用ftp_put:
define("LOCAL_FILE","PATH_TO_LOCAL_FILE");
define("FTP_ADDRESS","ftp.domain.com");
define("FTP_FILE","PATH_TO_REMOTE_FILE");
define("FTP_USERNAME","USERNAME");
define("FTP_PASSWORD","PASWORD");
$conn = ftp_connect(FTP_ADDRESS);
$login = ftp_login($conn, FTP_USERNAME, FTP_PASSWORD);
ftp_put($conn, FTP_FILE, LOCAL_FILE, FTP_ASCII);
ftp_close($conn);
而 ftp 域将为您提供 ftp 文件的位置以及用户名和密码。
于 2012-12-09T07:10:57.357 回答