本文整理汇总了PHP中finfo类的典型用法代码示例。如果您正苦于以下问题:PHP finfo类的具体用法?PHP finfo怎么用?PHP finfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了finfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
function execute($temp_name, $allow_existing_file = false)
{
if ($this->_autoRename) {
$this->_cleanFilename();
$this->_path_target = $this->_findSafeFilename();
}
if (!isset($this->_whitelist[$this->_file_extension])) {
die('File extension is not permitted.');
}
$finfo = new finfo(FILEINFO_MIME);
$mime_type = $finfo->file($temp_name);
$mime_type = explode(';', $mime_type);
$mime_type = $mime_type[0];
if ($mime_type != $this->_whitelist[$this->_file_extension]) {
die('File type/extension combination not permitted for security reasons.');
}
if (is_uploaded_file($temp_name)) {
if (!move_uploaded_file($temp_name, $this->_path_target)) {
return false;
}
} elseif ($allow_existing_file) {
if (!rename($temp_name, $this->_path_target)) {
return false;
}
} else {
return false;
}
chmod($this->_path_target, 0755);
AMP_s3_save($this->_path_target);
AMP_lookup_clear_cached('downloads');
return true;
}
示例2: isValid
/**
* Defined by Zend_Validate_Interface
*
* Returns true if the mimetype of the file does not matche the given ones. Also parts
* of mimetypes can be checked. If you give for example "image" all image
* mime types will not be accepted like "image/gif", "image/jpeg" and so on.
*
* @param string $value Real file to check for mimetype
* @param array $file File data from Zend_File_Transfer
* @return boolean
*/
public function isValid($value, $file = null)
{
// Is file readable ?
require_once 'Zend/Loader.php';
if (!Zend_Loader::isReadable($value)) {
return $this->_throw($file, self::NOT_READABLE);
}
if ($file !== null) {
if (class_exists('finfo', false) && defined('MAGIC')) {
$mime = new finfo(FILEINFO_MIME);
$this->_type = $mime->file($value);
unset($mime);
} elseif (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) {
$this->_type = mime_content_type($value);
} else {
$this->_type = $file['type'];
}
}
if (empty($this->_type)) {
return $this->_throw($file, self::NOT_DETECTED);
}
$mimetype = $this->getMimeType(true);
if (in_array($this->_type, $mimetype)) {
return $this->_throw($file, self::FALSE_TYPE);
}
$types = explode('/', $this->_type);
$types = array_merge($types, explode('-', $this->_type));
foreach ($mimetype as $mime) {
if (in_array($mime, $types)) {
return $this->_throw($file, self::FALSE_TYPE);
}
}
return true;
}
示例3: __construct
/**
* Attachment constructor.
*
* @param string $filePath
* @param string|null $type
* @throws MessageException
*/
public function __construct(string $filePath, string $type = null)
{
// Check if file exists and is readable
if (!@is_readable($filePath)) {
throw MessageException::attachmentUnreadable(__METHOD__, $filePath);
}
$this->path = $filePath;
// Save file path
$this->type = $type;
// Content type (if specified)
$this->name = basename($this->path);
$this->id = null;
$this->disposition = "attachment";
// Check if content type is not explicit
if (!$this->type) {
// Check if "fileinfo" extension is loaded
if (extension_loaded("fileinfo")) {
$fileInfo = new \finfo(FILEINFO_MIME_TYPE);
$this->type = $fileInfo->file($this->path);
}
if (!$this->type) {
$this->type = self::fileType($this->name);
}
}
}
示例4: mime
/**
* Attempt to get the mime type from a file. This method is horribly
* unreliable, due to PHP being horribly unreliable when it comes to
* determining the mime type of a file.
*
* $mime = File::mime($file);
*
* @param string $filename file name or path
*
* @return string mime type on success
* @return FALSE on failure
*/
public static function mime($filename)
{
// Get the complete path to the file
$filename = realpath($filename);
// Get the extension from the filename
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (preg_match('/^(?:jpe?g|png|[gt]if|bmp|swf)$/', $extension)) {
// Use getimagesize() to find the mime type on images
try {
$file = getimagesize($filename);
} catch (\Exception $e) {
}
if (isset($file['mime'])) {
return $file['mime'];
}
}
if (class_exists('finfo', false)) {
if ($info = new \finfo(defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME)) {
return $info->file($filename);
}
}
if (ini_get('mime_magic.magicfile') and function_exists('mime_content_type')) {
// The mime_content_type function is only useful with a magic file
return mime_content_type($filename);
}
if (!empty($extension)) {
return self::mime_by_ext($extension);
}
// Unable to find the mime-type
return false;
}
示例5: download
/**
* Try download file
*/
public function download()
{
if ($this->fileInfo instanceof \SplFileInfo) {
if ($this->fileInfo->isFile()) {
if (is_array($this->validatorExtension)) {
if (!in_array($this->fileInfo->getExtension(), $this->validatorExtension)) {
throw new \Exception("Extensão invalida!");
}
}
if (!$this->fileInfo->isReadable()) {
throw new \Exception("O Arquivo não pode ser lido!");
}
if (is_null($this->newName)) {
$this->setNewName($this->fileInfo->getBasename());
}
$finfo = new \finfo();
header("Content-Type: {$finfo->file($this->fileInfo->getRealPath(), FILEINFO_MIME)}");
header("Content-Length: {$this->fileInfo->getSize()}");
header("Content-Disposition: attachment; filename={$this->newName}");
readfile($this->fileInfo->getRealPath());
} else {
throw new \Exception("Por favor, adicione um arquivo valido!");
}
} else {
throw new \Exception("Por favor, adicione o arquivo primeiro!");
}
}
示例6: magicMimeType
/**
* Tries to determine the file type magically
* @param string $data
* @returns a string, the mime type, or null if none was found.
*/
public static function magicMimeType($data)
{
if (self::$finfo == null) {
if (!class_exists('finfo')) {
I2CE::raiseError('Magic file utilties not enabled. Please run \'pecl install Fileinfo\' or some such thing.');
return null;
}
$config = I2CE::getConfig();
$magic_file = null;
if ($config->setIfIsSet($magic_file, "/modules/MimeTypes/magic_file")) {
$magic_file = I2CE::getFileSearch()->search('MIME', $magic_file);
if (!$magic_file) {
$magic_file == null;
}
}
//I2CE::raiseError("Using $magic_file");
//@self::$finfo = new finfo(FILEINFO_MIME, $magic_file);
@(self::$finfo = new finfo(FILEINFO_MIME));
if (!self::$finfo) {
I2CE::raiseError('Unable to load magic file database ' . $magic_file, E_USER_NOTICE);
return null;
}
}
if (!($mime_type = self::$finfo->buffer($data))) {
I2CE::raiseError('Unable to determine mime type magically', E_USER_NOTICE);
//some error occured
return null;
}
return $mime_type;
}
示例7: GetMimeTypeForFile
/**
* Returns the suggested MIME type for an actual file. Using file-based heuristics
* (data points in the ACTUAL file), it will utilize either the PECL FileInfo extension
* OR the Magic MIME extension (if either are available) to determine the MIME type. If all
* else fails, it will fall back to the basic GetMimeTypeForFilename() method.
*
* @param string $strFilePath the absolute file path of the ACTUAL file
* @return string
*/
public static function GetMimeTypeForFile($strFilePath)
{
// Clean up the File Path and pull out the filename
$strRealPath = realpath($strFilePath);
if (!is_file($strRealPath)) {
throw new QCallerException('File Not Found: ' . $strFilePath);
}
$strFilename = basename($strRealPath);
$strToReturn = null;
// First attempt using the PECL FileInfo extension
if (class_exists('finfo')) {
if (QMimeType::$MagicDatabaseFilePath) {
$objFileInfo = new finfo(FILEINFO_MIME, QMimeType::$MagicDatabaseFilePath);
} else {
$objFileInfo = new finfo(FILEINFO_MIME);
}
$strToReturn = $objFileInfo->file($strRealPath);
}
// Next, attempt using the legacy MIME Magic extension
if (!$strToReturn && function_exists('mime_content_type')) {
$strToReturn = mime_content_type($strRealPath);
}
// Finally, use Qcodo's owns method for determining MIME type
if (!$strToReturn) {
$strToReturn = QMimeType::GetMimeTypeForFilename($strFilename);
}
if ($strToReturn) {
return $strToReturn;
} else {
return QMimeType::_Default;
}
}
示例8: fileSave
public function fileSave($data, \Uppu3\Entity\User $user)
{
$fileResource = new File();
//$fileResource->saveFile($data['load']);
$fileResource->setName($data['load']['name']);
$fileResource->setSize($data['load']['size']);
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$fileResource->setExtension($finfo->file($data['load']['tmp_name']));
//$fileResource->setMediainfo($data['load']['tmp_name']);
$fileResource->setComment($_POST['comment']);
$mediainfo = \Uppu3\Entity\MediaInfo::getMediaInfo($data['load']['tmp_name']);
//$mediainfo = json_encode($mediainfo);
$fileResource->setMediainfo($mediainfo);
$fileResource->setUploaded();
$fileResource->setUploadedBy($user);
$this->em->persist($fileResource);
$this->em->flush();
$id = $fileResource->getId();
$tmpFile = $data['load']['tmp_name'];
$newFile = \Uppu3\Helper\FormatHelper::formatUploadLink($id, $data['load']['name']);
$result = move_uploaded_file($tmpFile, $newFile);
if (in_array($fileResource->getExtension(), $this->pictures)) {
$path = \Uppu3\Helper\FormatHelper::formatUploadResizeLink($id, $data['load']['name']);
$resize = new \Uppu3\Helper\Resize();
$resize->resizeFile($newFile, $path);
}
return $fileResource;
}
示例9: getSource
/**
* @return string
*
* @throws Backend\SourceFileException
*/
public function getSource()
{
if ($this->src !== NULL) {
return $this->src;
}
$source = file_get_contents($this->getPathname());
if ($source == '') {
$this->src = '';
return '';
}
if ($this->encoding == 'auto') {
$info = new \finfo();
$this->encoding = $info->file((string) $this, FILEINFO_MIME_ENCODING);
}
try {
$source = iconv($this->encoding, 'UTF-8//TRANSLIT', $source);
} catch (\ErrorException $e) {
throw new SourceFileException('Encoding error - conversion to UTF-8 failed', SourceFileException::BadEncoding, $e);
}
// Replace xml relevant control characters by surrogates
$this->src = preg_replace_callback('/(?![\\x{000d}\\x{000a}\\x{0009}])\\p{C}/u', function (array $matches) {
$unicodeChar = '\\u' . (2400 + ord($matches[0]));
return json_decode('"' . $unicodeChar . '"');
}, $source);
return $this->src;
}
示例10: __construct
public function __construct($file, $validate)
{
parent::__construct();
if (!is_string($file) || (!is_readable($file)))
{
throw new DocBlox_Reflection_Exception('The given file should be a string, should exist on the filesystem and should be readable');
}
if ($validate)
{
exec('php -l '.escapeshellarg($file), $output, $result);
if ($result != 0)
{
throw new DocBlox_Reflection_Exception('The given file could not be interpreted as it contains errors: '.implode(PHP_EOL, $output));
}
}
$this->filename = $file;
$this->name = $this->filename;
$contents = file_get_contents($file);
// detect encoding and transform to UTF-8
$info = new finfo();
$mime = $info->file($file, FILEINFO_MIME);
$mime_info = explode('=', $mime);
if (strtolower($mime_info[1]) != 'utf-8')
{
$contents = iconv($mime_info[1], 'UTF-8', $contents);
}
$this->contents = $contents;
$this->setHash(filemtime($file));
}
示例11: upload
public static function upload($data, $file)
{
if (isset($file)) {
$tmpFile = $_FILES["file"]["tmp_name"];
$idArticle = $data['idArticle'];
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
switch ($mime) {
case 'image/jpeg':
$extension = ".jpg";
$destination = IMAGES_PATH;
break;
case 'image/png':
$extension = ".png";
$destination = IMAGES_PATH;
break;
case 'image/gif':
$extension = ".gif";
$destination = IMAGES_PATH;
break;
case 'application/pdf':
$extension = ".pdf";
$destination = DOCS_PATH;
break;
default:
throw new UploadException("Ce n'est pas le bon type de fichier");
break;
}
$fileName = !empty($nameOfFile) ? uniqid('articleFile_' . $idArticle . '_') : '';
$chemin = $destination . $fileName . $extension;
list($width, $height) = getimagesize($tmpFile);
}
}
示例12: addFile
public function addFile($field_name, $absolute_filename_path)
{
$file_info = new \finfo(FILEINFO_MIME);
$mime_type = $file_info->buffer(file_get_contents($absolute_filename_path));
$mime = explode(';', $mime_type);
$this->files[$field_name] = curl_file_create($absolute_filename_path, reset($mime), basename($absolute_filename_path));
}
示例13: getMime
/**
* checks mime type of file
* @param string $file
* @return bool
* @access private
*/
public static function getMime($file)
{
$mime = null;
if (class_exists("finfo")) {
$finfo = new finfo(FILEINFO_MIME);
$mime = $finfo->file($file);
}
if (function_exists("finfo_open")) {
$finfo = finfo_open(FILEINFO_MIME);
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
} else {
$fp = fopen($file, 'r');
$str = fread($fp, 4);
fclose($fp);
switch ($str) {
case "ÿØÿà":
$mime = 'image/jpeg';
break;
case "‰PNG":
$mime = 'image/png';
break;
case 'GIF8':
$mime = 'image/gif';
break;
default:
trigger_error("Tell the guy behind the levers of i² to see {$str} as a valid file. Thank you //Sincerely, i ", E_USER_ERROR);
$mime = $str;
}
}
if (preg_match("/[a-zA-Z]+\\/[a-zA-Z]+.+/", $mime)) {
$mime = preg_replace("/([a-zA-Z]+\\/[a-zA-Z]+)(.+)/", "\$1", $mime);
}
return $mime;
}
示例14: __construct
/**
*
* @param string $filepath
*/
public function __construct($filepath)
{
$this->filepath = $filepath;
$this->basename = basename($filepath);
$finfo = new \finfo(FILEINFO_MIME);
list($this->mime, $this->charset) = explode('; ', $finfo->file($filepath));
}
示例15: file_check
private function file_check()
{
try {
if (!isset($_FILES['upfile']['error']) || !is_int($_FILES['upfile']['error'])) {
throw new RuntimeException("不正なパラメータです。管理人にお問い合わせください。");
}
switch ($_FILES["upfile"]["error"]) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException("ファイルが選択されていません。");
break;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException("ファイルサイズが許容値を超えています。");
break;
default:
throw new RuntimeException("不明なエラーが発生しました。");
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (!array_search($finfo->file($_FILES["upfile"]["tmp_name"]), array("oud" => 'text/plain'), true) || pathinfo($_FILES["upfile"]["name"])["extension"] !== "oud") {
throw new RuntimeException("oudファイルではありません。");
}
$fp = fopen($_FILES["upfile"]["tmp_name"], "r");
if (!preg_match("/FileType=OuDia/", fgets($fp))) {
throw new RuntimeException("oudファイルですが、書式が正しくありません。");
}
fclose($fp);
} catch (Exception $e) {
echo "エラーが発生しました:" . $e->getMessage();
exit;
}
}