Archive for June, 2008
count和sizeof的效率对比
今日有某篇文章对指出sizeof()的效率比count()的效率要高,甚至说在for循环中使用sizeof的效率要高于在循环外预赋值的使用sizeof。 我测了一遍,觉得他的测试方法有问题。问题在于程序仅运行了一次就下结论,没有排除偶然性。以下是我的测试代码: <?php $arrTest = array_fill( 0 , 10000 , 999 ); function test1( $arrTest ) { $startTime = microtime( true ); $size = count( $arrTest ); for ( $i = 0 ; $i < $size ; $i++ ); return ( microtime( true ) - $startTime ); } function test2( $arrTest ) { $startTime = microtime( true ); for ( [...]
[代码规范]PHP中声明变量的好处
一、避免被自己的代码污染,产生非语法错误。 例如: for( $i = 0 ; $i < 100 ; ++$i ) { $a[$i] = $i; } isset( $a ) ? var_dump( $a ) : var_dump( ‘$a is not defined!’ ); 结果: array(100) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) [5]=> int(5) [6]=> int(6) [7]=> int(7) [8]=> int(8) [9]=> int(9) [...]
PHP递归调用
function daddslashes($string, $force = 0) { !defined( ‘MAGIC_QUOTES_GPC’ ) && define( ‘MAGIC_QUOTES_GPC’ , get_magic_quotes_gpc() ); if(!MAGIC_QUOTES_GPC || $force) { if(is_array($string)) { foreach($string as $key => $val) { $string[$key] = daddslashes($val, $force); } } else { $string = addslashes($string); } } return $string; } 红色部分写得很帅,绿色的部分我不赞同 改为 defined( ‘MAGIC_QUOTES_GPC’ ) or define( ‘MAGIC_QUOTES_GPC’ , get_magic_quotes_gpc() ); 和 [...]
巧妙的使用可变变量,让代码更简洁直观
foreach( array( ‘_COOKIE’ , ‘_POST’ , ‘_GET’ ) as $_request ) { foreach( $$_request as $_key => $_value ) { … } }
防止客户端端数据覆盖globals
if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS'])) { exit(‘Request tainting attempted.’); } 因为如果register_globals打开的话, 客户端提交的数据中含有GLOBALS变量名, 就会覆盖服务器上的$GLOBALS变量. 所以这段代码, 就是判断, 如果提交的数据中有GLOBALS变量名, 就终止程序.
get_magic_quotes_gpc和get_magic_quotes_runtime的区别
magic_quotes_gpc的设定值将会影响通过Get/Post/Cookies获得的数据 magic_quotes_runtime的设定值将会影响从文件中读取的数据或从数据库查询得到的数据 <form action=”" method=”post” > STR:<input type=”text” name=”str”> <input type=”submit”> </form> <?php /* 我们在表单里填写: ‘”\ 这些符号,如果magic_quotes_gpc没有开启,那么他们不会被反斜杠转义 */ echo ‘现在通过POST传递过来的值是:’ ,$_POST['str'], ‘<br />’; if (get_magic_quotes_gpc()) { // 检查magic_quotes_gpc是否打开,如果没有打开,用addslashes进行转义 $str = $_POST['str']; } else { $str = addslashes($_POST['str']); } echo ‘这里是转义过后的:’ ,$str, ‘<hr />’; $sql = “INSERT INTO lastnames (lastname) VALUES (‘$str’)”; //===================================================================================== //—–magic_quotes_gpc只会转义: 通过Get/Post/Cookies获得的数据 //—–magic_quotes_runtime会转义:从文件中读取的数据或执行exec()的结果或是从SQL查询中得到的 [...]
linux sed 批量替换多个文档中的字符串
sed -i “s/oldstring/newstring/g” `grep oldstring -rl yourdir` 例如:替换 /home/praxis/ams 下任何文档中的 192.168.0.35 为 192.168.0.21 sed -i “s/192.168.0.35/192.168.0.21/g” `grep 192.168.0.35 -rl /home/praxis/ams`