我想你試圖上傳本地文件到遠程服務器。您可以編寫一個函數來模擬HTML表單是這樣的:
<?php
/**
* Upload local file to remote server
*
* @param string local file
* @param string the target URL
* @param string name of the form input (<input type="file" name="..." />)
*/
function send_file($filename, $target_url, $field_name)
{
// Check if file exist
file_exists($filename) OR die('Cannot find file');
// Get file extension
$ext = substr($filename, strrpos($filename, '.') + 1);
// Guess mimetype, add more mimetypes here
if ($ext == 'jpg') {
$mime = 'image/jpg';
} else if ($ext == 'gif') {
$mime = 'image/gif';
} else if ($ext == 'png') {
$mime = 'image/png';
} else {
$mime = 'text/plain';
}
// Extract URL to local variables
extract(parse_url($target_url));
// Build request header and body
$boundary = '---------'.str_replace('.', '', microtime());
$reqbody = '--'.$boundary."\r\n"
. 'Content-Disposition: form-data; name="'.$field_name.'"; filename="'.$filename.'"'."\r\n"
. 'Content-Type: '.$mime."\r\n\r\n"
. file_get_contents($filename)."\r\n"
. '--'.$boundary.'--'."\r\n";
$bodylen = strlen($reqbody);
$reqhead = 'POST '.(isset($path) ? $path : '/').' HTTP/1.1'."\r\n"
. 'Host: '.$host."\r\n"
. 'Content-Type: multipart/form-data; boundary='.$boundary."\r\n"
. 'Content-Length: '.$bodylen."\r\n"
. 'Connection: Close'."\r\n\r\n";
// Open socket connection to remote host
$fp = fsockopen($host, isset($port) ? $port : 80) OR die ('Cannot connect');
fputs($fp, $reqhead);
fputs($fp, $reqbody);
// ...Read response here...
fclose($fp);
}
使用方法如下:
send_file('C:/Users/lenovo/Desktop/images/img03.jpg', 'http://example.com/upload.php', 'file');
凡在http://example.com/upload.php
腳本包含:
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'path/for/'.$_FILES['file']['name'])
?>
您有關於一個根本性的誤解上傳文件的工作原理 – 2010-12-04 12:03:52