php 的FileHandler

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 的FileHandler相关的知识,希望对你有一定的参考价值。

<?php

namespace App\Controller\Component;

use App\Controller\Component\FileHandler\WrongFileException;
use App\Model\Entity\Page;
use App\Model\Entity\PagesImage;
use Cake\Controller\Component;
use Cake\Core\Configure;
use Cake\ORM\Entity;
use Gregwar\Image\Image;

/**
 * Class FileHandlerComponent
 * @package App\Controller\Component
 */
class FileHandlerComponent extends Component
{
    const THUMBNAIL_DEFAULTS = ['width' => 150, 'height' => 150];

    /**
     * @param $destination_dir
     * @param array $params
     * @return bool|string
     * @throws WrongFileException
     */
    public function upload($destination_dir, $params = array()) {
        /**
         * Copyright 2009, Moxiecode Systems AB
         * Released under GPL License.
         *
         * License: http://www.plupload.com/license
         * Contributing: http://www.plupload.com/contributing
         */

        // HTTP headers for no cache etc

        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        // Grab request data

        // Settings
        $targetDir = $destination_dir;

        if (!file_exists($targetDir)) {
            mkdir($targetDir, 0777, true);
        }

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // 5 minutes execution time
        @set_time_limit(5 * 60);
        // Get parameters
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : 'noname';
        // Clean the fileName for security reasons

        $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
        $fileExtension = substr($fileName, strrpos($fileName, '.'));

        // Make sure the fileName is unique but only if chunking is disabled

        if ($chunks < 2 && file_exists($targetDir . DS . $fileName)) {
            $ext = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);
            $count = 1;

            while (file_exists($targetDir . DS . $fileName_a . '_' . $count . $fileName_b)){
                $count++;
            }

            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }

        $fileName = mb_strtolower($fileName,'UTF-8');

        if(isset($params['excluded_extensions'])) {
            if ($params['excluded_extensions']) {
                if (in_array(substr($fileExtension,1), $params['excluded_extensions'])) {
                    throw new WrongFileException(__('Złe rozwinięcie pliku'));
                }
            }
        }

        if(isset($params['included_extensions']) && $params['included_extensions']) {
            if (!in_array(substr($fileExtension,1), $params['included_extensions'])) {
                throw new WrongFileException(__('Złe rozwinięcie pliku'));
            }
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        // Remove old temp files
        if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        } else {
            throw new WrongFileException(__('Złe rozwinięcie pliku'));
        }

        if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
        }

        if (isset($_SERVER["CONTENT_TYPE"])) {
            $contentType = $_SERVER["CONTENT_TYPE"];
        }

        // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
        if (strpos($contentType, "multipart") !== false) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = fopen($_FILES['file']['tmp_name'], "rb");
                    if ($in) {
                        while ($buff = fread($in, 4096)) {
                            // Change coding
                            //$code = mb_detect_encoding($buff);
                            //$buff = mb_convert_encoding($buff, 'UTF-8');
                            //$buff = mb_convert_encoding($buff, 'ISO-8859-2');
                            $rrr = fwrite($out, $buff);
                        }
                    } else {
                        throw new WrongFileException(__('Błąd otwierania pliku'));
                    }

                    fclose($in);
                    fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                } else {
                    throw new WrongFileException(__('Błąd otwierania pliku'));
                }
            } else {
                throw new WrongFileException(__('Błąd przenoszenia pliku'));
            }
        } else {
            // Open temp file
            $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");

            if ($out) {
                // Read binary input stream and append it to temp file
                $in = fopen("php://input", "rb");
                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                } else {
                    throw new WrongFileException(__('Błąd otwierania pliku'));
                }

                fclose($in);
                fclose($out);
            } else {
                throw new WrongFileException(__('Błąd otwarcia strumienia'));
            }
        }

        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off
            rename("{$filePath}.part", $filePath);
            return $filePath;
        }

        return false;
    }

    /**
     * @param string $src_path
     * @return mixed
     */
    public function getFileInfo(string $src_path)
    {
        return pathinfo($src_path);
    }

    /**
     * @param string $src_path
     * @param string $output_path
     */
    public function generateThumbnail(string $src_path, string $output_path)
    {
        /** @var array $thumbnails_config */
        $thumbnails_config = Configure::read('App.images.thumbnails');

        if (!$thumbnails_config) {
            $thumbnails_config = self::THUMBNAIL_DEFAULTS;
        }

        Image::open($src_path)
            ->resize($thumbnails_config['width'], $thumbnails_config['height'])
            ->save($output_path);
    }

    /**
     * @param string $src_path
     * @return bool
     */
    public function deleteFile(string $src_path)
    {
        return @unlink($src_path);
    }

    /**
     * @param $image_arg
     * @param string $table_name
     * @return bool
     */
    public function deleteSingleImage($image_arg, string $table_name)
    {
        $this->getController()->loadModel($table_name);

        if (gettype($image_arg) === 'object' && $image_arg instanceof Entity) {
            $entity = $image_arg;
        } else {
            /** @var \App\Model\Entity\Image $entity */
            $entity = $this->getController()->{$table_name}->find()->where(['id' => $image_arg])->first();
        }

        if (!$entity) {
            return false;
        }

        $image_paths = $entity->getPaths();

        foreach ($image_paths as $image_path) {
            if (!$this->deleteFile($image_path)) {
                return false;
            }
        }

        return $this->getController()->{$table_name}->delete($entity);
    }

    /**
     * @param Entity $entity
     * @param string $table_name
     * @param string $entity_plural
     * @return bool
     */
    public function cascadeDeleteImages(Entity $entity, string $table_name, string $entity_plural)
    {
        if ($entity->{$entity_plural}) {
            foreach ($entity->{$entity_plural} as $single_entity) {
                if(!$this->deleteSingleImage($single_entity, $table_name)) {
                    return false;
                }
            }
        }

        return true;
    }
}

以上是关于php 的FileHandler的主要内容,如果未能解决你的问题,请参考以下文章

logging将日志写入文件filehandler

如何为 java.util.logging.FileHandler 使用 try-with-resources?

属性的级别值不正确,无法为java.util.logging.FileHandler设置级别

java.util.logging FileHandler.count 不工作

使用带有来自java.util.logging的FileHandler的logger时,不需要.0扩展日志文件

logging模块