php函数行数据 php处理数据( 三 )


当在Linux环境下工作时,权限处理会浪费你很多时间 。因此,只要你的php应用程序创建了一些文件,那就应该修改它们的权限以确保它们在外面“平易近人” 。否则,例如 , 文件是由“php”用户创建的,而你作为一个不同的用户,系统就不会让你访问或打开文件,然后你必须努力获得root权限,更改文件权限等等 。
// Read and write for owner, read for everybody elsechmod("/somedir/somefile", 0644);// Everything for owner, read and execute for otherschmod("/somedir/somefile", 0755);
5.不要检查提交按钮值来检查表单提交
if($_POST['submit'] == 'Save')
{//Save the things}
以上代码在大多数时候是正确的,除了应用程序使用多语言的情况 。然后“Save”可以是很多不同的东西 。那么你该如何再做比较?所以不能依靠提交按钮的值 。相反,使用这个:
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
{//Save the things}
现在你就可以摆脱提交按钮的值了 。
6.在函数中总是有相同值的地方使用静态变量
//Delay for some timefunction delay(){
$sync_delay = get_option('sync_delay');echo "
Delaying for $sync_delay seconds...";
sleep($sync_delay);echo "Done
";
}
相反,使用静态变量:
//Delay for some timefunction delay(){static $sync_delay = null;if($sync_delay == null)
{
$sync_delay = get_option('sync_delay');
}echo "
Delaying for $sync_delay seconds...";
sleep($sync_delay);echo "Done
";
}
7.不要直接使用$ _SESSION变量
一些简单的例子是:
$_SESSION['username'] = $username;
$username = $_SESSION['username'];
但是这有一个问题 。如果你正在相同域中运行多个应用程序 , 会话变量会发生冲突 。2个不同的应用程序在会话变量中可能会设置相同的键名 。举个例子 , 一个相同域的前端门户和后台管理应用程序 。
因此,用包装函数使用应用程序特定键:
define('APP_ID' , 'abc_corp_ecommerce');//Function to get a session variablefunction session_get($key){
$k = APP_ID . '.' . $key;if(isset($_SESSION[$k]))
{return $_SESSION[$k];
}return false;
}//Function set the session variablefunction session_set($key , $value){
$k = APP_ID . '.' . $key;
$_SESSION[$k] = $value;return true;
}
8.封装实用辅助函数到一个类中
所以,你必须在一个文件中有很多实用函数:
function utility_a(){//This function does a utility thing like string processing}function utility_b(){//This function does nother utility thing like database processing}function utility_c(){//This function is ...}
自由地在应用程序中使用函数 。那么你或许想要将它们包装成一个类作为静态函数:
class Utility{public static function utility_a()
{
}public static function utility_b()
{
}public static function utility_c()
{
}
}//and call them as $a = Utility::utility_a();
$b = Utility::utility_b();
这里你可以得到的一个明显好处是,如果php有相似名称的内置函数 , 那么名称不会发生冲突 。
从另一个角度看,你可以在相同的应用程序中保持多个版本的相同类 , 而不会发生任何冲突 。因为它被封装了 , 就是这样 。
9.一些傻瓜式技巧
使用echo代替print
使用str_replace代替preg_replace , 除非你确定需要它
不要使用short tags
对于简单的'字符串使用单引号代替双引号
在header重定向之后要记得做一个exit
千万不要把函数调用放到for循环控制行中 。

推荐阅读