php接收文件再转发 (问:php怎样接收文件并转发?)
在开发Web应用程序中,经常需要上传和转发文件。PHP作为一种流行的Web开发语言,可以方便地实现这个功能。本文将介绍如何使用PHP接收文件并转发到其它服务器。
首先,需要在HTML文件中创建一个文件上传表单。这可以通过使用标记来实现。当提交表单时,选择的文件将被传递到PHP脚本中。
“`html
“`
接下来,需要编写PHP脚本来接收并处理上传的文件。可以使用PHP内置的$FILES数组来处理文件上传。$FILES数组包含上传文件的名称、大小、类型和临时文件路径等信息。
“`php
<?php
$uploadedfile = $FILES[‘file’][‘tmpname’];
$filename = $FILES[‘file’][‘name’];
$filesize = $FILES[‘file’][‘size’];
$filetype = $_FILES[‘file’][‘type’];
if (isset($uploadedfile)) {
if (moveuploadedfile($uploadedfile, ‘uploadedfiles/’.$filename)) {
echo “文件上传成功。”;
// 发送文件到其它服务器
$remote_url = 'http://example.com/upload.php';
$post_fields = array('file_contents' => new CurlFile('uploaded_files/'.$file_name));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_exec($ch);
curl_close($ch);
} else {
echo “文件上传失败。”;
}
}
?>
“`
上述代码中,首先判断上传的文件是否存在,然后使用moveuploadedfile()函数将文件移动到指定目录。接着,使用Curl库向目标服务器发送文件。在这里,可以使用下面的代码来接收文件:
php
<?php
if (isset($_POST['file_contents'])) {
$received_file = $_POST['file_contents'];
file_put_contents('received_files/'.$received_file->getPostFilename(), $received_file->getContent());
echo "文件接收成功。";
} else {
echo "文件接收失败。";
}
?>
在上述代码中,将接收到的文件保存在一个指定的目录中。getContent()函数用于获取文件内容,getPostFilename()函数用于获取文件名。
通过这种方式,可以方便地在PHP应用程序之间传递文件。以上代码作为参考,可以根据具体情况进行调整和修改。