PHP異常處理類(檔案上傳提示)

來源:互聯網
上載者:User

標籤:正則   com   echo   尾碼   jpg   功能   程式員   text   拋出異常   

知識點:

大部分時候我們的代碼總有各種各樣的bug,新手程式員(比如我)最經常的工作就是不停的報錯和echo變數,一個好的異常處理類可以幫我們更快+更容易理解報錯代碼的問題,同時,異常處理還可以避免一些因為程式錯誤而泄露網站重要訊息內容的提示(比如檔案報錯,會彈出根目錄),此外異常處理還可以協助項目上的正則驗證,檔案上傳提示,存取權限控制等提高項目體驗的功能。

代碼:


<?php
header("Content-type: text/html; charset=utf-8");
/*
PHP異常處理常用函數:
1、getCode();得到傳遞給建構函式的錯誤碼
2、getFile();返回拋出異常的檔案名稱
3、getLine();返回拋出異常的行號
4、getMessage();返回傳遞給建構函式的訊息
5、getPrevious();返回前一個異常變數
6、getTrace();返回一個數組,包括錯誤的檔案名稱、行號、函數名、函數參數。

*/

class exctest{

var $filename;//檔案名稱
var $fileexten;//檔案尾碼

public function __construct($file){

$this->filename = $file;
$this->fileexten = pathinfo($file, PATHINFO_EXTENSION);

}
public function checkexist(){


try{
if(!file_exists($this->filename)){

throw new exception(‘檔案不存在!‘);

}
}catch(exception $e){

echo $this->filename.$e->getMessage()."<br>";

}
}
public function checkexten(){

$extens = array(‘gif‘,‘jpg‘,‘png‘,‘xlxs‘,‘xls‘,‘doc‘);

try{
if(!in_array($this->fileexten,$extens)){

throw new exception(‘檔案類型錯誤!請上傳下列格式的檔案:‘);

}
}catch(exception $e){

$extens = implode(",",$extens);
echo $this->filename.$e->getMessage().$extens;

}

}
public function checkall(){


$this->checkexist();
$this->checkexten();

}


}

$a = new exctest(‘test.rar‘);

$a->checkall();

 


?>

:

 

PHP異常處理類(檔案上傳提示)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.