当前位置:Gxlcms > PHP教程 > php优化,该怎么处理

php优化,该怎么处理

时间:2021-07-01 10:21:17 帮助过:50人阅读

php优化
//define server info begin
$servername = "192.168.1.182";
$serverusername = "whh";
$serverpassword = "whh";
$database="whh";
$usertable="user";
$userfield="user_name";
$passwordfield="password";
//define server info end

$fh = fopen("php://stdin", 'r');
$stdout = fopen('php://stdout', 'w');
$fs = fopen("auth-log.txt." . getmypid(), 'a');

if(!$fh){
die("Cannot open STDIN\n");
}

do{
$lenBytes = fgets($fh, 3);
$len = unpack('n', $lenBytes);
$len = $len[1];
if($len<1) continue;
$msg = fgets($fh, $len+1);
$toks=explode(':',$msg);
fwrite($fs, $msg . "\n");

$method = array_shift($toks);
fwrite($fs, "$method\n");
$result = false;

switch($method){
case 'auth':
list($username, $server, $password) = $toks;
$password = trim($password);
fwrite($fs, "checking user: $username and password $password\n");
//check password begin
$conn=mysql_connect($servername, $serverusername, $serverpassword);
mysql_query("set names 'utf8'");
if(!$conn){
die("could not connect to the database");
}
$db_select=mysql_select_db($database);//选择数据库
if(!$db_select)
{
die("could not to the database");
}
$query="select * from $usertable where $userfield = '$username' and $passwordfield='$password'";//构建查询语句
$result=mysql_query($query);//执行查询
$count=mysql_numrows($result);//取得条数
mysql_close($conn);
if($count > 0){
$result = true;
}else{
$result = false;
}
//check password end
break;

case 'isuser':
list($username, $server) = $toks;
//check password begin
$conn=mysql_connect($servername, $serverusername, $serverpassword);
mysql_query("set names 'utf8'");
if(!$conn){
die("could not connect to the database");
}
$db_select=mysql_select_db($database);//选择数据库
if(!$db_select)
{
die("could not to the database");
}
$query="select * from $usertable where $userfield = '$username'";//构建查询语句
$result=mysql_query($query);//执行查询
$count=mysql_numrows($result);//取得条数
mysql_close($conn);
if($count > 0){
$result = true;
}else{
$result = false;
}
//check password end
break;

default:
$result = false;
}
$message = @pack("nn", 2, $result);
fwrite($stdout, $message);
$dump = @unpack("nn", $message);
$dump = $dump["n"];
fwrite($fs, $dump . "\n");
flush();
} while(true);

大家好!
对php我不懂,请大家看下是否可以对该php做些优化呢?
我是写java的,发现可能在这个地方“$conn=mysql_connect($servername, $serverusername, $serverpassword);”可以进行优化,没有必要每次都生成一个$conn。
------解决方案--------------------
没有什么可优化的
在传入的数据中,可能只有 auth,也可能只有 isuser,更可能两者都没有
完全没有必要在可能无需数据库访问的情况下,做数据库连接

程序的优化不是减少代码,而是提升性能
------解决方案--------------------
如果传入参数都一致的话,$conn及其判断可以提到do...while前面

人气教程排行