PHP 安全及相关
关注安全问题的重要性 看到的远非全部 阻止用户恶意破坏你的程式最有效却经常被忽略的方法是在写代码时就考虑它的可能性。留意代码中可能的安全问题是很重要的。考虑下边的旨在简化用PHP中写入大量文本文件的过程的实例函数: <?php function write_text($filename, $text="") { static $open_files = array(); // 如果文件名空,关闭全部文件 if ($filename == NULL) { foreach($open_files as $fr) { fclose($fr); } return true; } $index = md5($filename); if(!isset($open_files[$index])) { $open_files[$index] = fopen($filename, "a+"); if(!$open_files[$index]) return false; } fputs($open_files[$index], $text); return true; } ?> 这个函数带有两个缺省参数,文件名和要写入文件的文本。 函数将先检查文件是否已被打开;如果是,将使用原来的文件句柄。否则,将自行创建。在这两种情况中,文本都会被写入文件。 如果传递给函数的文件名是NULL,那么所有打开的文件将被关闭。下边提供了一个使用上的实例。 如果开发者以下边的格式来写入多个文本文件,那么这个函数将清楚和易读的多。 让我们假定这个函数存在于一个单独的文件中,这个文件包含了调用这个函数的代码。 下边是一个这样的程式,我们叫它quotes.php: <html><body> <form action="<?= Copyright © 2008 chengduxinxi.com All Rights Reserved PHP编程开发 由朝夕网络维护
Choose the nature of the quote: <select name="quote" size="3"> <option value="funny">Humorous quotes</option> <option value="political">Political quotes</option> <option value="love">Romantic Quotes</option> </select><br /> The quote: <input type="text" name="quote_text" size="30" /> <input type="submit" value="Save Quote" /> </form> </body></html> <?php include_once(''write_text.php''); $filename = "/home/web/quotes/{ Copyright © 2008 chengduxinxi.com All Rights Reserved PHP编程开发 由朝夕网络维护
$quote_msg = Copyright © 2008 chengduxinxi.com All Rights Reserved PHP编程开发 由朝夕网络维护
if (write_text($filename, $quote_msg)) { echo "<center><hr><h2>Quote saved!</h2></center>"; } else { echo "<center><hr><h2>Error writing quote</h2></center>"; } write_text(NULL); ?> 如同你看到的,这位开发者使用了write_text()函数来创建一个体系使得用户可以提交他们喜欢的格言,这些格言将被存放在一个文本文件中。 不幸的是,开发者可能没有想到,这个程式也允许了恶意用户危害web server的安全。 也许现在你正挠着头想着究竟这个看起来很无辜的程式怎样引入了安全风险。 如果你看不出来,考虑下边这个URL,记住这个程式叫做quotes.php: http://www.s |
