douhong4452 2015-05-19 10:04
浏览 44

PHP OOP处理UI的错误通知

i am looking for the best way to display error for User, i am using Class File() and profile page. The Class File() will handle the following : - check file extension - check if file already exist - explode and create link file && insert the link to database - upload file to folder directory inside project folder

The code is working properly except for error display, for exemple if the extension is wrong it will display the last error instead of stop the execution and display the extension error.

Also if the file already exist in database && folder directory the php function move_uploaded_file will display and error "Warning: failed to open the stream: permission denied"

Thanks for your help

    class File {

    private $file = array();
    private $file_up = '';
    private $pdo = '';
    private $error = '';
    private $regex_file = '/^[a-z0-9][a-z0-9]{4,20}.jpg|.jpeg|.png|.gif|.txt|.doc|.docx|.pdf|.xlsx|.xlm|.xls|.pub|.one|.pptx$i/';

    /**
     * [__construct connection ]
     * @param [int] $id [Unique user_id retrieved from database (from include/header.inc)]
     * Construct database connection using PDO
     * 
     */
    public function __construct($id)
    {
        $this->pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        $sql = 'SELECT `file_name`, `file_extention` FROM `users`'
                 .'JOIN `file`'
                 .'ON users.`user_id` = file.`user_id`'
                 .'WHERE users.`user_id` = :id';
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(array(':id' => $id));
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $this->file[] = $row['file_name'] . '.' . $row['file_extention'];
        }
    }

    /**
     * [displayFile extention]
     * @return [link] [description]
     */
    public function displayFile() 
    {
        $output = '';
        $link = $this->file;
        foreach($link as $row) {
            $output .= '<table class="table table-bordered table-hover"';
            $output .= '<thead><tr>';
            $output .= '<th><a href="../file_user/'.$row.'><i class="fa fa-folder"></i>&nbsp&nbsp'.$row.'</a><br /></th>';
            $output .= '</tr></thead>';
            $output .= '</table>';
        }
        return $output;
    }

    public function checkFile($file)
    {
        $this->file_up = strip_tags($file);
        if(!preg_match($this->regex_file, $this->file_up)){
                $this->error = '<b style="color:red">Extention ou nom de fichier incorrect</b>';
        }
        foreach($this->file as $row){
            if($this->file_up == $row){
                $this->error = '<b style="color:red">Fichier ou nom du fichier deja existant</b>';
            }
        }
        if($this->error){
            return $this->error;
        }else{
            $this->file_up = explode(".", $this->file_up);// array
            return $this->file_up;
        }       
    }

    public function getError()
    {
        if($this->error !== ''){
            return $this->error;
        }
    }

    public function uploadFile($array, $id)
    {   
        if(is_array($array)){
            array_push($array, $id);
            $sql = 'INSERT INTO `file`(`file_name`, `file_extention`, `user_id`) VALUES (?, ?, ?)';
            $con = $this->pdo->prepare($sql);
            $con->execute($array);
        }else{
            $this->error = '<b style="color:red">Fichier ne peut etre telecharger</b>';
        }
    }

    public function mvFile($size, $name, $tmp_name)
    {
        $to = 'file_user/';
        if($size <= 2000000){
            move_uploaded_file($tmp_name, $to.$name);
            $this->error = '<b style="color:green">Fichier téléchargé avec succes</b>';
        }else{
            $this->error = '<b style="color:red">Un probleme est survenue veuillez recommencer</b>';
        }
    }
}

And testing.php to test it:

require_once 'class/file.inc';
$error = '';
$id = 2;
$file = new File($id);

 $name = $_FILES['file']['name'];
 $size = $_FILES['file']['size'];
 $type = $_FILES['file']['type'];
 $tmp_name = $_FILES['file']['tmp_name'];



if(isset($_FILES['file'])){
        $file_up = $_FILES['file']['name'];
        $file_up = $file->checkFile($file_up);
        $file->uploadFile($file_up, $id);
        //$file->mvFile($size, $name, $_FILES['file']['tmp_name']);
    if($file->getError()){
        $error = $file->getError();
    }

} // end isset

if($error){
    echo $error;
}
  • 写回答

1条回答 默认 最新

  • dsfphczao23473056 2015-05-19 10:57
    关注

    Two separate problems:

    1. If you detect any errors in your checkFile() method and you want to get only the first error (which is odd from my point of view; you could collect the errors in an array or so), you should return that error directly instead of proceeding with the rest of the method. Further, I would think of harmonizing the returned values. Should your method return errors or filenames? That's not very clean by now.

    2. Your problem concerning move_uploaded_file() seems permission-related. Check your source (tmp upload) dir and destination for r/w rights.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值