1. 程式人生 > >php assert函式的分析

php assert函式的分析

assert這個函式在php語言中是用來判斷一個表示式是否成立。返回true or false;
例如
<?php
$s = 123;
assert("is_int($s)");
?>

從這個例子可以看到字串引數會被執行,這跟eval()類似。不過eval($code_str)只是執行符合php編碼規範的$code_str。
assert的用法卻更詳細一點。

assert_option()可以用來對assert()進行一些約束和控制;
預設值
ASSERT_ACTIVE=1 //Assert函式的開關
ASSERT_WARNING =1 //當表示式為false時,是否要輸出警告性的錯誤提示,issue a PHP warning for each failed assertion

ASSERT_BAIL= 0 //是否要中止執行;terminate execution on failed assertions
ASSERT_QUIET_EVAL= 0 //是否關閉錯誤提示,在執行表示式時;disable error_reporting during assertion expression evaluation
ASSERT_CALLBACK= (NULL) // 是否啟動回撥函式 user function to call on failed assertions

如果按照預設值來,在程式的執行過程中呼叫assert()來進行判斷表示式,遇到false時程式也是會繼續執行的,這在生產環境中這樣使用是不好的,而 在開發除錯環境中,卻是一種debug的不錯的方式。特別是用上callback的方法,可以知道具體的出錯資訊。例如



<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "<hr>Assertion Failed:File '$file'<br />Line '$line'<br />Code '$code'<br /><hr />";

}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>


所以,php的官方文件裡頭是建議將assert用來進行debug,我們可以發現還有一個開關ASSERT_ACTIVE可以用來控制是否開啟debug。

現在問題就產生了,如果程式設計師在開發的時候在程式碼中留下了很多assert(),然後在程式釋出的時候關閉執行,設定assert_options(ASSERT_ACTIVE,0);這樣做是否可行?有沒有安全問題?

我的建議是,既然assert主要作用是debug,就不要在程式釋出的時候還留著它。在程式中用assert來對錶達進行判斷是不明智的,原因上文說了, 一個是在生產環境中assert可能被disabled,所以assert不能被完全信任;二是assert()可以被繼續執行;而如果在生產環境讓ASSERT_ACTIVE=1,那這個表示式字串可以被執行本身就存在安全隱患。
例如
<?php
function fo(){
  $fp = fopen("c:/test.php",'w');
  fwrite($fp,"123");
  fclose($fp);
  return true;
}
assert("fo()");
?>