最近,我创建了一个上传表单,用户可以在其中将他们的文件上传到远程 FTP 服务器。到现在为止,一切都很顺利。但是,我有一个问题。
我想确保当用户将他的图像上传到远程 FTP 服务器时,图像将立即显示在网站上。我怎样才能做到这一点?这个问题在 Stack Overflow 上被问了很多。然而还是有区别的。在大多数情况下,个人希望从远程 FTP 服务器下载特定文件。我不是这种情况。我想确保用户看到他上传的文件显示在网站上。
我用于将文件上传到远程 FTP 服务器的 php 代码:
<?php
if ( empty( $_FILES['file'] ) ) {
?>
<html>
<head>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
<input name="file" type="file"/>
<br>
<input name="submit" type="submit" value="Upload uw album" />
</form>
</body>
</html>
<?php
return;
} else {
?>
<html>
<head>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
<input name="file" type="file"/>
<br>
<input name="submit" type="submit" value="Upload uw album" />
</form>
</body>
</html>
<?php
}
$ftp_server = "myserver";
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$source_file = $_FILES['file']['tmp_name'];
$destination_folder = "/public_html/wp/wp-content/plugins/AbonneerProgrammas/Albums";
$destination_file = $destination_folder . "/" . basename($_FILES['file']['name']);
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "Het spijt ons, er is momenteel geen connectie met de server.";
//echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
//echo "upload is gelukt";
}
// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);
// check upload status
if (!$upload) {
//
} else {
?>
<meta http-equiv="refresh" content="0; url=https://radioprogrammabank.nl/wp/upload-album/?name=<?php echo urlencode(basename($_FILES['file']['name']));?>">
<?php
echo "<a href=\"$source_file?file=".urlencode($source_file)."\">".htmlspecialchars($source_file)."</a>";
header('Content-Type: application/octet-stream');
echo file_get_contents('ftp://username:password@ftp.example.com/path/' . $_GET["file"]);
echo "upload is gelukt";
}
// close the FTP stream
ftp_close($conn_id);
?>