2017-06-25 40 views
2

這是創建歌曲對象PHP - 檢查音頻文件沒有損壞

public function getSong() { 
     return new Song($this->rackDir, $this->getLoadedDisc()->getName(), $this->song); 
    } 

方法有宋級

class Song extends CD { 
    private $id; 

    public function __construct($rack, $name, $id) 
    { 
     $this->id = $id; 
     parent::__construct($rack, $name); 

    } 

    public function getSelectedSongId() { 
     return $this->id; 
    } 

    public function getSelectedSongPath() { 
     $list = $this->getSongsList(); 

     return $list[$this->id]; 
     } 
    } 

    public function getSongInfo() { 
     $data = [ 
      'name' => $this->getName(), 
      'size' => $this->getSize(), 
     ]; 

     return $data; 
    } 

    public function getSize() { 
     $path = $this->getPath() . '/' . $this->getName(); 

     return filesize($path); 
    } 

    public function getName() { 
     return $this->getSelectedSongPath(); 
    } 

} 

而且有CD類,我檢查文件是否具有音頻擴展。

class CD { 
    private $path; 
    private $name; 
    private $rack; 
    private $validExtensions; 

    public function __construct($rack, $name) 
    { 
     $this->rack = $rack . '/'; 
     $this->name = $name; 
     $this->path = $this->rack . $this->name; 
     $this->validExtensions = ['mp3', 'mp4', 'wav']; 
    } 

    public function getPath() { 
     return $this->path; 
    } 

    public function getName() { 
     return $this->name; 
    } 

    public function getSongsList() { 
     $path = $this->rack . $this->name; 
     $songsList = []; 

     if (!is_dir($path)) { 
      return false; 
     } 
     if ($handle = opendir($path)) { 
      while (false !== ($file = readdir($handle))) 
      { 
       if ($file != "." && $file != ".." && in_array(strtolower(substr($file, strrpos($file, '.') + 1)), $this->validExtensions)) 
       { 
        array_push($songsList, $file); 
       } 
      } 
      closedir($handle); 
     } 

     return $songsList; 
    } 
} 

我想檢查文件是否是真正的音頻文件,而不只是文件的音頻擴展名? 在PHP中有這樣做的方法嗎?

+1

看看[mime types](http://php.net/manual/en/function.mime-content-type.php) – Kruser

回答

2

卡洛斯是正確的。 我發現這個代碼的解決方案如下。

public function validateFile (Song $song) { 
    $allowed = array(
     'audio/mp4', 'audio/mp3', 'audio/mpeg3', 'audio/x-mpeg-3', 'audio/mpeg', 'audio/*' 
    ); 

    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $info = finfo_file($finfo, $song->getSelectedSongPath()); 

    if (!in_array($info, $allowed)) { 
     die('file is empty/corrupted'); 
    } 
    return $song; 
}