我剛寫了這個PHP跟蹤代碼,將包括在主題中,有一些簡單的統計數據。現在,由於它會處理很多請求,它需要堅實而快速。我的PHP水平不是那麼好,所以我正在尋找幫助/最佳實踐來優化這個壞男孩。我如何優化我的PHP函數和mysql請求
我寫了重定向所有請求到index.php的簡單的.htaccess文件,所以我可以處理與PHP請求URI:$_SERVER['REQUEST_URI'], /this-is-the-theme-slug /user-name
<?php
/** MySQL Database Settings */
require dirname(__FILE__) . '/inc/database.php';
/** Klogger Log Framework*/
require dirname(__FILE__) . '/lib/KLogger.php';
$log = KLogger::instance(dirname(__FILE__).'/log/', KLogger::DEBUG);
/** Process Request String **/
$request = $_SERVER['REQUEST_URI'];
$ipaddr = $_SERVER['REMOTE_ADDR'];
$uri = explode('/',$request);
$slug = $uri[1];
$user = $uri[2];
/** Global Variables **/
$theme_id = NULL;
$account_id = NULL;
function process_request(){
global $log, $slug, $user;
if(!empty($slug) && !empty($user)){
$the_slug = validate_slug($slug);
$the_user = account_exists($user);
if($the_slug){ // if the slug is valid
if($the_user){ // and the user exists
// update entry
update_entry($user);
}else{
// create new entry
create_entry($user);
}
}
return true;
}else{
$log->logError('process_request:: Bad request');
return false;
}
}
function validate_slug($slug){
global $log, $theme_id;
$con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$con){
$log->logError('validate_slug:: Database connection failed');
return false;
}else{
$select = mysql_select_db(DB_NAME, $con);
$query = sprintf("SELECT id FROM ".DB_PREFIX."themes WHERE slug='%s'", mysql_real_escape_string($slug));
$result = mysql_query($query);
if(mysql_num_rows($result)==0){
$log->logNotice('validate_slug:: Slug not found');
return false;
}else{
$theme_id = mysql_result($result,0);
return true;
}
mysql_close($con);
}
}
function account_exists($user){
global $log, $account_id;
$con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$con){
$log->logError('account_exists:: Database connection failed');
return false;
}else{
$select = mysql_select_db(DB_NAME, $con);
$query = sprintf("SELECT id FROM ".DB_PREFIX."stats WHERE account='%s'", mysql_real_escape_string($user));
$result = mysql_query($query);
if(mysql_num_rows($result)==0){
$log->logNotice('account_exists:: Account not found');
return false;
}else{
$account_id = mysql_result($result,0);
return true;
}
mysql_close($con);
}
}
function create_entry($user){
global $log, $ipaddr, $theme_id;
$con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$con){
$log->logError('create_entry:: Database connection failed');
return false;
}else{
$select = mysql_select_db(DB_NAME, $con);
$query = sprintf("INSERT INTO ".DB_PREFIX."stats (id,active,account,date,ip,hits,theme) VALUES ('','1','%s',NOW(),'".$ipaddr."','1','".$theme_id."')", mysql_real_escape_string($user));
$result = mysql_query($query);
$log->logNotice('create_entry:: Account created with id '.mysql_insert_id());
return true;
}
mysql_close($con);
}
function update_entry($user){
global $log, $ipaddr, $account_id;
$con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$con) {
$log->logError('update_entry:: Database connection failed');
return false;
} else {
$select = mysql_select_db(DB_NAME, $con);
$query = sprintf("UPDATE ".DB_PREFIX."stats SET date=NOW(),ip='".$ipaddr."',hits=hits+1 WHERE id='".$account_id."'");
$result = mysql_query($query);
$log->logNotice('update_entry:: Entry with id '.$account_id.' is updated.');
return true;
}
mysql_close($con);
}
process_request();
編輯 我已經成功創建了工人階級的我的跟蹤器,請參閱下面的代碼。如果您的速度有所提升,請告訴我!我嘗試連接mysqlli和pdo,但它不起作用,顯然我的託管不支持它?
<?php
require_once(__DIR__ . '/inc/database.php');
require_once(__DIR__ . '/lib/KLogger.php');
Class ThemeStatsTracker
{
public $log;
private $theme_name;
private $theme_user;
private $theme_name_db_id;
private $theme_user_db_id;
public function __construct()
{
// Setup Log
$this->log = KLogger::instance(dirname(__FILE__).'/log/', KLogger::DEBUG);
// Process URI variables
$uri = explode('/',$_SERVER['REQUEST_URI']);
$this->theme_name = (!empty($uri[1])) ? $uri[1] : NULL;
$this->theme_user = (!empty($uri[2])) ? $uri[2] : NULL;
// Handle the Request
$this->database_connect();
if($this->validate_theme()){
if($this->user_entry_exists()){
$this->user_entry_update();
}else{
$this->user_entry_create();
}
}
// Always serve an image as response
$this->serve_image();
}
private function validate_theme()
{
$query = sprintf("SELECT id FROM ".DB_PREFIX."themes WHERE slug='%s' LIMIT 1", mysql_real_escape_string($this->theme_name));
$result = mysql_query($query);
if (!$result){
$this->log->logError(__FUNCTION__ . ' FAIL: ' . $query . ' BECAUSE: ' . mysql_error());
return FALSE;
}
if(mysql_num_rows($result)==0){
$this->log->logError(__FUNCTION__ . ' Theme name ' . $this->theme_name . ' NOT found');
return FALSE;
}else{
$this->log->logInfo(__FUNCTION__ . ' Theme name ' . $this->theme_name . ' found');
$this->theme_name_db_id = mysql_result($result,0);
return TRUE;
}
}
private function user_entry_exists()
{
$query = sprintf("SELECT id FROM ".DB_PREFIX."stats WHERE account='%s' LIMIT 1", mysql_real_escape_string($this->theme_user));
$result = mysql_query($query);
if (!$result){
$this->log->logError(__FUNCTION__ . ' FAIL: ' . $query . ' BECAUSE: ' . mysql_error());
return FALSE;
}
if(mysql_num_rows($result)==0){
$this->log->logInfo(__FUNCTION__ . ' New user ' . $this->theme_user);
return FALSE;
}else{
$this->log->logInfo(__FUNCTION__ . ' Existing user ' . $this->theme_user);
$this->theme_user_db_id = mysql_result($result,0);
return TRUE;
}
}
private function user_entry_create()
{
$query = sprintf("INSERT INTO ".DB_PREFIX."stats (id,active,account,date,ip,hits,theme) VALUES ('','1','%s',NOW(),'".$_SERVER['REMOTE_ADDR']."','1','".$this->theme_name_db_id."')", mysql_real_escape_string($this->theme_user));
$result = mysql_query($query);
if (!$result){
$this->log->logError(__FUNCTION__ . ' FAIL: ' . $query . ' BECAUSE: ' . mysql_error());
return FALSE;
}
$this->log->logNotice(__FUNCTION__ . ' New user created with id ' . mysql_insert_id());
return TRUE;
}
private function user_entry_update()
{
$query = sprintf("UPDATE ".DB_PREFIX."stats SET date=NOW(),ip='".$_SERVER['REMOTE_ADDR']."',hits=hits+1 WHERE id='".$this->theme_user_db_id."' LIMIT 1");
$result = mysql_query($query);
if (!$result){
$this->log->logError(__FUNCTION__ . ' FAIL: ' . $query . ' BECAUSE: ' . mysql_error());
return FALSE;
}
$this->log->logNotice(__FUNCTION__ . ' User with id ' . $this->theme_user_db_id . 'updated');
return TRUE;
}
private function serve_image()
{
header("Content-type: image/gif");
header("Content-length: 43");
$fp = fopen("php://output","wb");
fwrite($fp,"GIF89a\x01\x00\x01\x00\x80\x00\x00\xFF\xFF",15);
fwrite($fp,"\xFF\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00",12);
fwrite($fp,"\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02",12);
fwrite($fp,"\x44\x01\x00\x3B",4);
fclose($fp);
}
private function database_connect()
{
$con = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$con){
$this->log->logError(__FUNCTION__ . ' FAIL: ' . $query . ' BECAUSE: ' . mysql_error());
return FALSE;
}
$select = mysql_select_db(DB_NAME, $con);
if (!$select){
$this->log->logError(__FUNCTION__ . ' FAIL: ' . $query . ' BECAUSE: ' . mysql_error());
return FALSE;
}
}
}
$stats = new ThemeStatsTracker();
過早的優化是所有罪惡的根源。去搞清楚。 –
除非您遇到需要解決方案的特定問題,否則[Code Review SE](http://codereview.stackexchange.com/)將更適合此問題。 (編輯:當然,使用'mysql_'函數是我的第一個紅旗。) – DCoder
如果它的工作原理沒有中斷 –