使用 unlink 从服务器删除文件

问题描述 投票:0回答:4

我有一个 ffmpeg 转换器,可以将视频转换为 mp4。转换后我想删除原始视频以节省文件空间。 我尝试使用

unlink($file_path)
但它说权限被拒绝。

到目前为止,视频已完成转换并生成转换后的缩略图。

$ffmpeg = 'ffmpeg';
$output = dirname(__DIR__).'/uploads/thumbs/'.$_file.'.jpg';
$input = dirname(__DIR__).'/uploads/'.$file;
$mov = new ffmpeg_movie($input);
$d =  $mov->getDuration();
$iscopy = $mov->getCopyright();
$h = $mov->getFrameHeight();
$w = $mov->getFrameWidth();
$pos = ceil((int)$d /3);
$size = $w.'x'.$h;
$i = explode('.',$input);
$o = $i[0].'.mp4';
if(ceil($d) < 1200){
   if($ext != 'mp4'){
    $cmd = "ffmpeg -i $input -vcodec h264 -acodec aac -strict -2 $o";
        shell_exec($cmd);
   }
   $cmd = "ffmpeg -ss $pos -i $o -an -s $size $output";
   shell_exec($cmd);
   $total_time += $pos;
   $succedeed[] = array('name' => $name,'file' => 'thumbs/'.$_file.'.jpg', 'type' => 'mp4');    

if(file_exists('../uploads/'.$file)){
                                unlink('../uploads/'.$file);
    }                       

}else{
    $failed[] = array('name' => $name, 'file' => $file, 'error' => 'Video length cannot exceed 20mins.');
}

文件的路径将是这样的:

unlink(../uploads/fdbc716e18173d4fe895c6d0b03365df1399237360.avi)

我尝试过这个(问题)这个(问题)以及很多谷歌搜索,但没有成功:

chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);

if($do=="1"){ 
    echo "The file was deleted successfully."; 
} else { echo "There was an error trying to delete the file."; } 
php chmod unlink
4个回答
2
投票

如果我正确阅读了你的问题,以下内容应该有效:

<?php
    $FileName = "uploaded_file";
     if (unlink($FileName))
      {
        echo ("$FileName has been deleted successfully. ");
      }
        else
      {
        echo ("The uploaded file has NOT been deleted.");
      }
?> 

如果没有。您必须在上传过程中更改文件的所有权。

 chmod($FileName, 0755);

0
投票

您需要在取消链接函数中的路径周围加上引号。

$do = unlink('../uploads/fdbc716e18173d4fe895c6d0b03365df1399237360.avi');

我也建议这样做:

if($do) {
    // true
} else {
    // false
}

$unlink 仅返回 true 或 false,因此您可以直接在 if 语句中使用 in。

如果您可以 ssh 进入服务器,请在上传所在目录上执行“ls -la”,查看所有者和权限是什么。如果它们是通过 php 上传的,那么它们应该属于可以删除它们的同一用户。


0
投票

file_exists 函数不采用相对路径,而是使用绝对路径:

$doc_root = $_SERVER['DOCUMENT_ROOT'];
if(file_exists($doc_root . '/uploads/' . $file)){
    unlink($doc_root . '/uploads/' . $file);
} 

0
投票
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder

只需修改此代码即可为您工作

© www.soinside.com 2019 - 2024. All rights reserved.