php How to delete files through ftp: first connect to ftp; then download the file through the "ftp_get" function; then use the "ftp_delete($con,"eee.doc");" method to directly delete the file.
Recommended: "PHP Video Tutorial"
php operation ftp upload files, create directories, delete files, delete Directory, download files to the local
<?php $host = 'xxx'; $user = 'user'; $pwd = '123'; $con = ftp_connect($host); $login = ftp_login($con,$user,$pwd); if($login){ echo "ftp链接成功!<br/>"; } $file1="baaa.doc"; echo ftp_put($con,$file1,"2222/aaa.doc",FTP_BINARY);//file1shi ftp的路径 第二个参数是当前服务器上的路径 2222/aaa.doc是本地的路径 echo "<br>"; $file2="测试aaa.doc"; //中文也是好使的 echo ftp_put($con,$file2,"2222/测试.doc",FTP_BINARY);//file1shi ftp的路径 第二个参数是当前服务器上的路径 2222/aaa.doc是本地的路径 echo "<br>"; $path="444/555";//创建目录只能一层一层的创建 $dir=explode("/", $path); $path=""; for ($i=0;$i<count($dir);$i++) { $path.="/".$dir[$i]; echo $path."<br>"; if(!@ftp_chdir($con,$path)){ @ftp_chdir($con,"/"); if(!@ftp_mkdir($con,$path)){ $ret=false; break; } } } ftp_put($con,"eee.doc","2222/aaa.doc",FTP_BINARY);//file1shi ftp的路径 第二个参数是当前服务器上的路径 此时放到了555下面 // echo ftp_pwd($con)."<br>";//当前目录名 //exit; @ftp_chdir($con,"../"); ftp_put($con,$file1,"2222/aaa.doc",FTP_BINARY); //附件放到了444里面 FTP_ASCII //把当前目录切换为父目录 ftp_cdup($con); //回到了上一级目录 默认的是share下 ftp_put($con,"ccc.doc","2222/aaa.doc",FTP_BINARY); //附件放到了444里面 @ftp_chdir($con,"444"); //进入到了444目录 //文件下载 ftp_get($con,"2222/aaa1.doc", "baaa.doc", FTP_BINARY);//第一个是本地 第二个是ftp的路径文件 @ftp_chdir($con,"555");//进入555 ftp_delete($con,"eee.doc"); //删除文件是好使的 ftp_cdup($con); ftp_rmdir($con,"555"); //删除目录 echo ftp_pwd($con)."<br>";//当前目录名 //http://www.w3school.com.cn/php/php_ref_ftp.asp ftp_close($con); ?> </body> </html>
ftp is not very efficient, it is recommended to use curl
function file_upload($ftpIp,$ftpUser,$ftpPwd,$path,$fileSavePath){ $curlobj = curl_init();//初始化 //传入ftp的目标文件,如'ftp://192.168.3.1/test/1.jpg' curl_setopt($curlobj,CURLOPT_URL,"ftp://".$ftpIp."/".$path); curl_setopt($curlobj,CURLOPT_HEADER,0);//不输出header curl_setopt($curlobj,CURLOPT_RETURNTRANSFER,0); //time out after 300s curl_setopt($curlobj,CURLOPT_TIMEOUT,2000);//超时时间 //通过这个函数设置ftp的用户名和密码,没设置就不需要! curl_setopt($curlobj,CURLOPT_USERPWD,$ftpUser.':'.$ftpPwd); $outfile = fopen($fileSavePath,'w+'); //保存到本地文件的文件名 curl_setopt($curlobj,CURLOPT_FILE,$outfile); $rtn = curl_exec($curlobj); if(curl_errno($curlobj)){ writeLog('Curl error: ' . curl_error($curlobj)); } fclose($outfile); curl_close($curlobj); if($rtn == 1){ return true; }else{ unlink($fileSavePath);//如果下载失败,但是本地open了这个文件,所以要删除 return false; } }
The above is the detailed content of How to delete files in php ftp. For more information, please follow other related articles on the PHP Chinese website!