Home > Article > Backend Development > An example of code for php ftp download file
Let me introduce to you an example of downloading files using the php ftp function. It is mainly the application of ftp related functions. Friends in need can refer to it.
In previous php tutorials, we have also introduced relevant examples, such as: A simple example of php using ftp to download files, Three examples of using ftp to transfer, download and delete files, let’s give a simple example today , convenient for beginners. The code is as follows: <?php /** * 函数名 php_ftp_download * 功能 从ftp服务器上下载文件 * 入口参数 * filename 欲下载的文件名,含路径 * by http://bbs.it-home.org */ function php_ftp_download($filename) { $phpftp_host = "ftplocalhost"; // 服务器地址 $phpftp_port = 21; // 服务器端口 $phpftp_user = "name"; // 用户名 $phpftp_passwd = "passwrd"; // 口令 $ftp_path = dirname($filename) . "/"; // 获取路径 $select_file = basename($filename); // 获取文件名 $ftp = ftp_connect($phpftp_host,$phpftp_port); // 连接ftp服务器 if($ftp) { if(ftp_login($ftp, $phpftp_user, $phpftp_passwd)) { // 登录 if(@ftp_chdir($ftp,$ftp_path)) { // 进入指定路径 $tmpfile = tempnam( getcwd()."/", "temp" ); // 创建唯一的临时文件 if(ftp_get($ftp, $tmpfile, $select_file, ftp_binary)) { // 下载指定的文件到临时文件 ftp_quit( $ftp ); // 关闭连接 header("content-type: application/octet-stream"); header("content-disposition: attachment; filename=" . $select_file)//content-disposition:inline; 表示可以在线打开文件! readfile($tmpfile); unlink($tmpfile ); // 删除临时文件 exit; } unlink($tmpfile ); } } } ftp_quit($ftp); } ?> |