是否可以使用PHP ftp_get下载到我的硬盘(与我的远程服务器相对)?使用ftp_get()的下载成功,但是我从远程服务器下载的文件正被下载到我的php脚本目录中。我并不感到惊讶,但我想知道如何将下载目录更改为硬盘上的特定位置 - 例如,“C:\”驱动器。
以下代码来自php.net,但这正是我的代码设置方式:
<?php
// define some variables
$local_file = 'local.rar';
$server_file = 'server.rar';
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
// close the connection
ftp_close($conn_id);
?>
感谢您的帮助,
埃文
答案 0 :(得分:2)
要在本地下载文件,您的PHP脚本需要发送相应的标头,然后回显文件的内容。但是,只有在尚未从PHP脚本(通过echo
或其他方式)引起任何其他输出时才会发生这种情况。此代码应该使您的浏览器打开文件保存窗口或将其下载到默认位置。
// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
// Don't echo output here...
//echo "Successfully written to $local_file\n";
// You've downloaded the file into `$local_file` on your server.
// Now send it to the browser:
header("Content-type: application/x-rar-compressed");
// Also helps to send Content-length
header("Content-length: " . filesize($local_file));
// Dump out the file contents
echo file_get_contents($local_file);
// Delete it from the server
unlink($local_file);
// Always exit when you're done
exit();
} else {
echo "There was a problem\n";
}