標籤

4GL (1) 人才發展 (10) 人物 (3) 太陽能 (4) 心理 (3) 心靈 (10) 文學 (31) 生活常識 (14) 光學 (1) 名句 (10) 即時通訊軟體 (2) 奇狐 (2) 爬蟲 (1) 音樂 (2) 產業 (5) 郭語錄 (3) 無聊 (3) 統計 (4) 新聞 (1) 經濟學 (1) 經營管理 (42) 解析度 (1) 遊戲 (5) 電學 (1) 網管 (10) 廣告 (1) 數學 (1) 機率 (1) 雜趣 (1) 證券 (4) 證券期貨 (1) ABAP (15) AD (1) agentflow (4) AJAX (1) Android (1) AnyChart (1) Apache (14) BASIS (4) BDL (1) C# (1) Church (1) CIE (1) CO (38) Converter (1) cron (1) CSS (23) DMS (1) DVD (1) Eclipse (1) English (1) excel (5) Exchange (4) Failover (1) Fedora (1) FI (57) File Transfer (1) Firefox (3) FM (2) fourjs (1) Genero (1) gladiatus (1) google (1) Google Maps API (2) grep (1) Grub (1) HR (2) html (23) HTS (8) IE (1) IE 8 (1) IIS (1) IMAP (3) Internet Explorer (1) java (4) JavaScript (22) jQuery (6) JSON (1) K3b (1) ldd (1) LED (3) Linux (120) Linux Mint (4) Load Balance (1) Microsoft (2) MIS (2) MM (51) MSSQL (1) MySQL (27) Network (1) NFS (1) Office (1) OpenSSL (1) Oracle (131) Outlook (3) PDF (6) Perl (60) PHP (33) PL/SQL (1) PL/SQL Developer (1) PM (3) Postfix (2) postfwd (1) PostgreSQL (1) PP (50) python (5) QM (1) Red Hat (4) Reporting Service (28) ruby (11) SAP (234) scp (1) SD (16) sed (1) Selenium (3) Selenium-WebDriver (5) shell (5) SQL (4) SQL server (8) sqlplus (1) SQuirreL SQL Client (1) SSH (3) SWOT (3) Symantec (2) T-SQL (7) Tera Term (2) tip (1) tiptop (24) Tomcat (6) Trouble Shooting (1) Tuning (5) Ubuntu (37) ufw (1) utf-8 (1) VIM (11) Virtual Machine (2) VirtualBox (1) vnc (3) Web Service (2) wget (1) Windows (19) Windows (1) WM (6) Xvfb (2) youtube (1) yum (2)

2014年7月2日 星期三

MySQL 設定檔優化-cache

http://article.denniswave.com/6345

From:http://www.bsdlover.cn/html/89/n-1789.html
  • thread_concurrency
  • 數量設置為CPU核心數量的兩倍.
  • thread_cache_size
  • 按照內存大小來設置, 1G=8, 2G=16, 3G=32, >3G=64

  • wait_timeout
  • 超時時間,如果連接數比較大,可以減少此參數的值,我使用的是10
  • max_connections
  • 最大連接數,mysql實際允許連接數的值是max_connections+1,按照系統庫不同而有不同性能。一般是500~1000,MySQL AB提供的linux靜態庫可以達到4000。
  • query_cache_size
  • 查詢緩衝,默認是0,所以必須打開以提高mysql性能,其本身需要40K來保存結構數據。所以不能設置的太小,初期可以設置成32M,然後根據實際運行情況另行調整。
  • query_cache_type
  • 指定查詢緩衝的類型:
    0是關閉
    1是緩衝除了使用 SELECT SQL_NO_CACHE 語句指明了不需要緩衝的數據意外的所有查詢
    2是只緩衝 SELECT SQL_CACHE 指定的查詢
    一般設置為1
  • query_cache_limit
  • 允許進入查詢緩衝區的最小數據大小,默認值是1MB,可以修改的小一點以滿足更多查詢的需求。但是如果設置的過於小,則會導致很多新的小查詢的結果將原有的查詢結果交換出去,增加系統的顛簸。
相關命令
  • 查詢mysql服務器相關狀態數據
  • >SHOW STATUS;
  • 查詢mysql服務器相關配置選項
  • >SHOW VARIABLES;
  • 整理查詢緩衝區裡的碎片
  • >flush query cache;
  • 刪除查詢緩衝區裡的所有內容
  • >reset query cache;
  • 設置mysql參數
  • >SET GLOBAL;
  • 查詢mysql當前執行的sql語句
  • >show processlist;
變量含義
  • 查詢緩存中的空閒內存塊的數目
  • Qcache_free_blocks
  • 查詢緩存的空閒內存總數
  • Qcache_free_memory
  • 緩存採樣數數目
  • Qcache_hits
  • 被加入到緩存中的查詢數目
  • Qcache_inserts
  • 因為缺少內存而被從緩存中刪除的查詢數目
  • Qcache_lowmem_prunes
  • 沒有被緩存的查詢數目 (不能被緩存的,或由於 QUERY_CACHE_TYPE)
  • Qcache_not_cached
  • 在緩存中已註冊的查詢數目
  • Qcache_queries_in_cache
  • 查詢緩存中的塊的總數目
  • Qcache_total_blocks
MySQL查詢優化
查詢Cache狀態
>SHOW STATUS LIKE 'Qcache%';
如果Qcache_lowmem_prunes非常大,說明因為內存不足而被交換出cache的數據很多.如果增加內存.可以保證較小的交換次數以及較高的命中率
例如現在我們查詢的結果如下:
Qcache_free_blocks 1234
Qcache_free_memory 25957504
Qcache_hits 55771119
Qcache_inserts 7441153
Qcache_lowmem_prunes 28332
Qcache_not_cached 1233788
Qcache_queries_in_cache 4810
Qcache_total_blocks 11038
設置為64M cache內存後
>set global query_cache_size=67108864;
Qcache_free_blocks 1
Qcache_free_memory 66623616
Qcache_hits 55788258
Qcache_inserts 7445445
Qcache_lowmem_prunes 28332
Qcache_not_cached 1234057
Qcache_queries_in_cache 183
Qcache_total_blocks 392
自由內存塊看起來變小了。
是因為現在自由內存塊是一個整塊,而以前的內存塊都是分散的小塊。而因為重建了cache區,Qcache_queries_in_cache 變量變小了。因為此操作重新建立了cache內存區,所有數據重新緩存,在運行一兩天後我們再看此數據。如果變大了,說明增大cache內存區域是有效 的,如果和以前數據差不多說明增加的內存並沒有實際起到多大的作用。
有人會覺得如果我將cache內存設置的非常大,然後將cache_limit設置成0,那麼所有查詢都會被緩存了。理論上是這樣,但是一台數據庫 服務器的查詢非常多,如果連查詢單條數據都要緩存,那麼內存再大也會不夠的。到時候老的內容就會被交換出去,當cache內存使用滿的時候,就會不停的有 新查詢進來將老查詢替換出去。
這樣導致兩個結果:一個是內存顛簸,效率反而下降;第二個是cache內存的小碎塊增多,內存利用率降低。如果是只有內容很少的小庫,並且查詢率不高,是可以使用這種方法提高響應速度。但是如果是實際生產環境,數據量會比較大,還是需要按照最佳比例來配置。
而不同的應用不同的數據量會有不同的搭配,這點大家不要看網上的優化配置隨便的填寫,還是要時時的查看mysql的狀態進行調整。即便是這個月調整好的優化參數,到了下個月業務不同,數據量增加,也會需要調整的。

2014年7月1日 星期二

PHP中查看错误log

http://blog.csdn.net/hopestar2/article/details/5960616

PHP中查看错误log

分类: PHP 4522人阅读 评论(1) 收藏 举报
    php中需要查看错误log,如何设置?
    首先需要在php.ini打开开关和制定错误log路径
    log_errors = On
    error_log = d://phperror.log   //windows下的设置

    如果是在linux 下,使用lighttpd服务器,则可以使用如下方式查看log文件
    tail -n 20 /usr/local/lighttpd/log/php-error.log

    在php代码中如何记录log,在PHP官方文档中有个函数error_log(),使用方法如下:

  定义和用法

    error_log() 函数向服务器错误记录、文件或远程目标发送一个错误。
   若成功,返回 true,否则返回 false。

   语法

   error_log(error,type,destination,headers)
 
参数 描述
error 必需。要记录的错误消息。
type 可选。规定错误记录的类型。
可能的记录类型:
  • 0 - 默认。根据在 php.ini 文件中的 error_log 配置,错误被发送到服务器日志系统或文件。
  • 1 - 错误被发送到 destination 参数中的地址。只有该类型使用 headers 参数。
  • 2 - 通过 PHP debugging 连接来发送错误。该选项只在 PHP 3 中可用。
  • 3 - 错误发送到文件目标字符串。
destination 可选。规定向何处发送错误消息。该参数的值依赖于 "type" 参数的值。
headers 可选。只在 "type" 为 1 时使用。
规定附加的头部,比如 From, Cc 以及 Bcc。由 CRLF (/r/n) 分隔。
注释:在发送电子邮件时,必须包含 From 头部。可以在 php.ini 文件中或者通过此参数设置。

例子

本例发送一封带有自定义错误的电子邮件:
<?php
$test=2;

if ($test>1)
{
error_log("A custom error has been triggered",
1,"someone@example.com","From: webmaster@example.com");
}
?>
输出:
A custom error has been triggered
 PS: 在调试php代码的时候,除了使用error_log()函数,还可以使用 throw new Exception()抛出异常信息。

PHP logging

http://www.devshed.com/c/a/php/logging-with-php/

Logging With PHP

Want to log script activity in your Web application, but have no clue where to begin? Take our handy tour of PHP’s logging functions, and find out how simple it really is.

I have to warn you not to be misled by the title of this article. It isn’t really about cutting down trees with PHP.

I know that PHP is the Swiss Army knife of Web scripting languages, but I don’t think its developers have come up with a way to have it reduce our tree cover (at least not yet). Rather, this article is about a different sort of logging – the sort which involves writing messages to files or devices on a regular basis, and using these messages to “do something useful”, be it generating a report or building an audit trail for activity tracking.

Over the next few pages, I’m going to take a quick look at the various mechanisms available to log script activity via PHP, demonstrating both built-in functions and add-on classes that allow you to add logging functionality to your applications. I’ll also spend some time on the PHP functions and configuration options related to logging, demonstrating how, for example, PHP errors can be sent to the Web server error log or emailed to an administrator when they are over a particular priority level.

My primary audience for this tutorial is the novice to intermediate PHP user – if you’re an advanced user, you probably already know enough about logging with PHP, and might prefer to skip the rest of this article in favour of more nutritious fare. Everyone else – keep reading!{mospagebreak title=The Bare Necessities} Logging data to a file in PHP can be as simple or as complex as you want to make it. Break it down, though, and it all comes down to these three simple lines of code:

<?php // open file $fd = fopen($filename, “a”); // write string fwrite($fd, $str . “n”); // close file fclose($fd); ?>
Fundamentally, logging data to a file consists of three steps:

1. Open the target file (or create it if it doesn’t already exist);

2. Append your data to the end of the file;

3. Close the file.

You can encapsulate this as a function,

<?php function logToFile($filename, $msg) { // open file $fd = fopen($filename, “a”); // write string fwrite($fd, $msg . “n”); // close file fclose($fd); } ?>
and then use it liberally within your code as and when required.

<?php function logToFile($filename, $msg) { // open file $fd = fopen($filename, “a”); // write string fwrite($fd, $msg . “n”); // close file fclose($fd); } $v = “Mary had a little lamb”; if (!is_numeric($v)) { logToFile(“my.log”, “Non-numeric variable encountered”); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { logToFile(“my.log”, “No fish available”); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { logToFile(“my.log”, “Could not connect to database”); die(“Could not connect to database”); } ?>
You can make the function a little more professional by having it automatically append the date and time of the log message to the log file as well:

<?php function logToFile($filename, $msg) { // open file $fd = fopen($filename, “a”); // append date/time to message $str = “[" . date("Y/m/d h:i:s", mktime()) . "] ” . $msg; // write string fwrite($fd, $str . “n”); // close file fclose($fd); } ?>
Here’s an example of the output:

[2002/11/25 06:02:42] Non-numeric variable encountered [2002/11/25 06:02:42] No fish available [2002/11/25 06:02:43] Could not connect to database
{mospagebreak title=Turning The Tables} While the most common destination for log data is a text file, it’s quite possible that you might want to send your log messages elsewhere as well. A frequently-used alternative to a text file, especially when the number of writes isn’t too high, is an SQL database, where log messages are appended as records to the end of a table.

In order to illustrate this, consider the following example of an SQL table used to store log messages:

CREATE TABLE `log` ( `date` TIMESTAMP NOT NULL, `type` TINYINT NOT NULL, `msg` VARCHAR(255) NOT NULL );
And here’s the rewritten logToDB() function, this time built around PHP’s MySQL database functions and the table above:

function logToDB($msg, $type) { // open connection to database $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“logdb”) or die (“Unable to select database!”); // formulate and execute query $query = “INSERT INTO log (date, type, msg) VALUES(NOW(), ‘$type’, ‘$msg’)”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // close connection mysql_close($connection); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { logToDB(“No fish available”, 14); }
If you don’t estimate seeing a very large number of writes, using a database to store logs can offer significant advantages over a regular file, purely from the point of view of easier retrieval and sorting. Storing log messages in this manner makes it possible to easily retrieve ordered subsets of the log data, either by date or message type.

Another option might be to send log messages to a specified email address via PHP’s mail() function – for example, alerting a sysop whenever a script encounters errors. Here’s an example:

function logToMail($msg, $address) { // append date/time to message $str = “[" . date("Y/m/d h:i:s", mktime()) . "] ” . $msg; mail($address, “Log message”, $str); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { logToMail(“Could not connect to database”, “webmaster@my.domain.name.com”); }
{mospagebreak title=Turning Up The Heat} If the thought of rolling your own code doesn’t appeal to you, you can also use PHP’s built-in error_log() function, which logs data both to a file and elsewhere. The error_log() function needs a minimum of two arguments: the error message to be logged, and an integer indicating where the message should be sent. There are three possible integer values in PHP 4.x:

0 – send the message to the system logger (“syslogd” on *NIX, and the Event Log on Windows NT);

1 – send the message to the specified email address;

3 – send the message to the specified file;

Here’s a trivial example which demonstrates how this works:


<?php // set a variable $temp = 101.6; // test it and log an error // this will only work if // you have “log_errors” and “error_log” set in your php.ini file if ($temp > 98.6) { error_log(“Body temperature above normal.”, 0); } ?>
Now, if you look at the system log file after running the script, you’ll see something like this:

[28-Feb-2002 15:50:49] Body temperature above normal.
You can also write the error message to a file,

<?php // set a variable $temp = 101.6; // test it and log an error if ($temp > 98.6) { error_log(“Body temperature above normal.”, 3, “a.out”); } ?>
or send it out as email.

<?php // set a variable $temp = 101.6; // test it and log an error if ($temp > 98.6) { error_log(“Body temperature above normal.”, 1, “administrator@this.body.com”); } ?>
It’s possible to combine this error logging facility with a custom error handler to ensure that all script errors get logged to a file. Here’s an example which demonstrates this:

<?php // custom handler function eh($type, $msg, $file, $line) { // log all errors error_log(“$msg (error type $type)”, 0); // if fatal error, die() if ($type == E_USER_ERROR) { die($msg); } } // report all errors error_reporting(E_ALL); // define custom handler set_error_handler(“eh”); // let’s now write some bad code // this will trigger a warning, since the file doesn’t exist include(“common.php”); ?>
And here’s the output that gets logged to the system log file:

[28-Feb-2002 16:15:06] Failed opening ‘common.php’ for inclusion (include_path=’.;’) (error type 2)
{mospagebreak title=Biting Into A PEAR} As if all that wasn’t enough, PHP offers one more alternative – a special Log class that comes courtesy of PEAR, the PHP Extension and Application Repository (http://pear.php.net). In case you didn’t know, PEAR is an online repository of free PHP software, including classes and modules for everything from data archiving to XML parsing. This Log class is maintained by Jon Parise, and the latest version can be downloaded from http://pear.php.net/package-info.php?package=Log

Like the error_log() function, the PEAR Log class allows logging to a variety of different destinations – system logger, text file, email address, database and even MCAL. Here’s an example demonstrating basic usage:

<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“file”, “my.log”); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
The first step here is to include() the Log class:

// include class include(“Log.php”);
Once that’s done, a new Log object can be created. This object constructor requires, as its first parameter, a string indicating the kind of log to open – current valid values are ‘console’, ‘syslog’, ‘sql’, ‘file’, and ‘mcal’. Depending on the log type, additional data may be provided – the name of the file to use in case of a file logger, for example.

// create Log object $l = &Log::singleton(“file”, “my.log”);
The Log class internally defines eight priority levels for logging – here’s the list, culled directly from the source code of the class:

$priorities = array( PEAR_LOG_EMERG => ‘emergency’, PEAR_LOG_ALERT => ‘alert’, PEAR_LOG_CRIT => ‘critical’, PEAR_LOG_ERR => ‘error’, PEAR_LOG_WARNING => ‘warning’, PEAR_LOG_NOTICE => ‘notice’, PEAR_LOG_INFO => ‘info’, PEAR_LOG_DEBUG => ‘debug’ );
Each log message that you send to the logger can be flagged with a specific priority, and the logger can be set up to log only those messages matching or exceeding a specific priority level (by default, all messages are logged). This can be clearly seen from the test code below, in which each message to the logger includes a priority level:

$v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); }
Here’s what the log file looks like:

Nov 26 06:47:15 [warning] Non-numeric variable encountered Nov 26 06:47:15 [error] No fish available Nov 26 06:47:17 [critical] Could not connect to database
If you’d like to tell the logger to only log messages above a certain priority level – for example, critical and above – this priority level should be specified as the fifth argument to the object constructor. Consider the following revision of the previous example:

<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“file”, “my.log”, NULL, array(), PEAR_LOG_ERR); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
In this case, only messages flagged as PEAR_LOG_ERR and above will be written to the specified log file.{mospagebreak title=Destination Unknown} The Log class also supports sending log messages to the console, the system logger, an SQL database or a user-specified email address. Take a look:

<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“console”); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
In this case, log messages are directed to the text console (if you’re running this script via a Web server, the console is the browser window). Here’s the output:

Nov 26 22:05:25 [warning] Non-numeric variable encountered Nov 26 22:05:25 [error] No fish available Nov 26 22:05:27 [critical] Could not connect to database
Messages can also be sent to an SQL database,

<?php // include class include(“Log.php”); // create Log object // second argument is table name // fourth argument is PHP::DB compatible DSN for database access $l = &Log::singleton(“sql”, “log_table”, “”, array(‘dsn’ => ‘mysql://joe:pass@localhost/test’)); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
which can then be queried to retrieve subsets of the log messages, sorted by date or priority level.

mysql> SELECT * FROM log_table WHERE priority >= 4; +—————-+——-+———-+———————————-+ | logtime | ident | priority | message | +—————-+——-+———-+———————————-+ | 20021126074936 | | 4 | Non-numeric variable encountered | | 20021126074936 | | 4 | Non-numeric variable encountered | | 20021126074937 | | 4 | Non-numeric variable encountered | +—————-+——-+———-+———————————-+ 3 rows in set (0.05 sec)
Finally, log messages can also be directed to a specified email address, as in the following example:

<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“mail”, “admin@host.com”); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
You can customize the mail message by adding an array containing a custom From: and Subject: line to the object constructor, as below:

<?php // include class include(“Log.php”); // create Log object $l = &Log::singleton(“mail”, “admin@host.com”, NULL, array(‘from’ => ‘L. Ogger’, ‘subject’ => ‘Log message’)); // test it $v = “Mary had a little lamb”; if (!is_numeric($v)) { $l->log(“Non-numeric variable encountered”, PEAR_LOG_WARNING); } $a = array(“chocolate”, “strawberry”, “peach”); if (!in_array(‘fish’, $a)) { $l->log(“No fish available”, PEAR_LOG_ERR); } $conn = @mysql_connect(“localhost”, “joe”, “pass”); if (!$conn) { $l->log(“Could not connect to database”, PEAR_LOG_CRIT); } ?>
{mospagebreak title=Artificial Intelligence} You can also configure PHP to automatically log all script errors to a specific file via the special “log_errors” configuration directive in “php.ini”. This directive, when set to true, logs all PHP errors to either a user-specified log file (the value of this file must be specified in the “error_log” configuration directive, also set via “php.ini”), or to the Web server error log if no log file is specified.

Consider the following example, which demonstrates:

<?php // turn on automatic error logging ini_set(‘log_errors’, true); // include non-existent file include(“non.existent.file.php”); ?>
In this case, I’m manually instantiating an error by attempting to include a file which does not exist. Obviously, PHP will barf and display an error screen containing the following:

Warning: Failed opening ‘non.existent.file.php’ for inclusion (include_path=’.;/usr/local/php/includes’) in error.php on line 10
The same error also appears in the server’s error log:

[Tue Nov 26 12:49:31 2002] [error] PHP Warning: Failed opening ‘non.existent.file.php’ for inclusion (include_path=’.;/usr/local/php/includes’) in error.php on line 10
You can turn off PHP error display, and only have the error message appear in the log file, by setting the “display_errors” variable (also accessible via “php.ini”) to false. Consider the following variant of the previous example, which demonstrates:

<?php // turn on automatic error logging ini_set(‘log_errors’, true); // turn off error display ini_set(‘display_errors’, false); // include non-existent file include(“non.existent.file.php”); ?>
In this case, though an error takes place, it is never displayed to the user, but merely gets logged to the server’s error log.

On *NIX systems, setting the “error_log” variable to the special value “syslog” logs all errors via the standard “syslog” daemon.{mospagebreak title=Big Brother Is Watching} Finally, let’s wrap things up with a couple of examples that show how the various techniques demonstrated above can be used to build logs and audit trails for a Web application.

In the first example, every time a Web page is displayed, a log entry is made in an “access.log” file. This log entry is a comma-separated list of values containing the URL requested, the client browser identification string, and a timestamp.

<?php // create log string $str = date(“Y/m/d h:i:s”, mktime()) . “,” . $_SERVER['REQUEST_URI'] . “,” . $_SERVER['HTTP_USER_AGENT'] . “n”; // write to file error_log($str, 3, “access.log”); // rest of page here ?>
Here’s a snippet from the access log:

2002/11/26 09:07:38,/alpha.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:07:38,/alpha.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:10:31,/home/hello.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:17:38,/index.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95) 2002/11/26 09:17:38,/base/index.php,Mozilla/4.0 (compatible; MSIE 5.0; Windows 95)
Since this data is in a structured format, it can easily be analyzed and a “hit count” created for each URL in the file. This next script does exactly that:

<?php // create array to hold unique URLs $urlStats = array(); // read access log $lines = file(“access.log”); // iterate through access log foreach ($lines as $l) { $data = explode(“,”, $l); $ts = $data[0]; $url = $data[1]; $agent = $data[2]; // check to see if URL exists in array // if it does, increment incidence count // if it does not, create a new key with incidence count 1 if ($urlStats[$url]) { $urlStats[$url]++; } else { $urlStats[$url] = 1; } } // print list of unique URLs with count print_r($urlStats); ?>
This script parses the “access.log” file, and creates a PHP associative array whose keys correspond to the URLs found in the file. The value associated with each key is an integer indicating the number of appearances the URL makes in the file. Once the entire file has been parsed, the $urlStats array contains a list of all the unique URLs in the access log, together with the number of times each has appeared. This data can then be used to generate a report of the most frequently-accessed URLs.

Consider this next example, which provides an API for adding, editing and deleting users to (from) a Web application. Each time the user database is edited, a separate audit() process tracks the change, logging both the nature of the change and information about the user initiating the change. This log data is stored in a separate SQL table, from where it can be retrieved for statistical reporting, user activity monitoring or debugging.

<?php // assume that administrator has logged in to system to perform user-administration tasks // admin username is stored in a session variable by default // this is useful for audit purposes session_start(); $_SESSION['LOGGED_IN_USER'] = “john”; // add a new user function addUser($user, $pass, $perms) { // open connection to database $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“myapp”) or die (“Unable to select database!”); // formulate and execute query $query = “INSERT INTO users (user, pass, perms) VALUES(‘$user’, ‘$pass’, ‘$perms’)”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // log activity to audit database audit(“ADD_USER”, $_SESSION['LOGGED_IN_USER'], “$user:$pass:$perms”, addslashes($query)); // close connection mysql_close($connection); } // edit an existing user function updateUser($user, $pass, $perms) { $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“myapp”) or die (“Unable to select database!”); // formulate and execute query $query = “UPDATE users SET pass = ‘$pass’, perms = ‘$perms’ WHERE user = ‘$user’”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // log activity to audit database audit(“UPDATE_USER”, $_SESSION['LOGGED_IN_USER'], “$user:$pass:$perms”, addslashes($query)); // close connection mysql_close($connection); } // delete an existing user function deleteUser($user) { $connection = mysql_connect(“localhost”, “joe”, “pass”) or die (“Unable to connect!”); mysql_select_db(“myapp”) or die (“Unable to select database!”); // formulate and execute query $query = “DELETE FROM users WHERE user = ‘$user’”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); // log activity to audit database audit(“DELETE_USER”, $_SESSION['LOGGED_IN_USER'], “$user”, addslashes($query)); // close connection mysql_close($connection); } // generic audit function // logs all activity to a database function audit($op, $owner, $args, $msg) { $connection = mysql_connect(“localhost”, “root”, “pass”) or die (“Unable to connect!”); mysql_select_db(“trails”) or die (“Unable to select database!”); // formulate and execute query $query = “INSERT INTO audit (timestamp, op, owner, args, msg) VALUES (NOW(), ‘$op’, ‘$owner’, ‘$args’, ‘$msg’)”; mysql_query($query) or die (“Error in query: $query. ” . mysql_error()); } addUser(“joe”, “joe”, 3); addUser(“sarahh”, “bsdfg49″, 1); updateUser(“joe”, “joe”, 4); deleteUser(“sarahh”); addUser(“sarah”, “bsdfg49″, 1); ?>
Here’s a snippet from the audit table:

+———————+————-+——-+ | timestamp | op | owner | +———————+————-+——-+ | 2002-11-26 08:28:05 | UPDATE_USER | john | | 2002-11-26 08:28:05 | DELETE_USER | john | | 2002-11-26 08:28:05 | ADD_USER | john | | 2002-11-26 08:33:14 | ADD_USER | joe | +———————+————-+——-+
This audit table can then be queried to obtain detailed information on the activities performed by the various users, sorted by time or type of activity. For example,

mysql> SELECT timestamp, op, args FROM trails WHERE timestamp >= mysql> 2002-11-26 AND owner = ‘joe’; +———————+————-+——————+ | timestamp | op | args | +———————+————-+——————+ | 2002-11-26 08:33:29 | ADD_USER | joe:joe:3 | | 2002-11-26 08:33:29 | ADD_USER | sarahh:bsdfg49:1 | | 2002-11-26 08:33:29 | UPDATE_USER | joe:joe:4 | | 2002-11-26 08:33:29 | DELETE_USER | sarahh | | 2002-11-26 08:33:29 | ADD_USER | sarah:bsdfg49:1 | +———————+————-+——————+
This is a somewhat trivial example, but it serves to demonstrate the concept of logging activity and using those logs to build an audit trail. While you can make this as complex as you want, tracking everything from user clicks to form input in order to gain a better understanding of how users navigate through and use your application, remember that every addition to the log affects the overall performance of your application; log too much data and your application will suffocate and die.{mospagebreak title=Closing Time} And that’s about it for the moment. In this article, I offered you a brief overview of logging in PHP, demonstrating how you can use built-in functions, off-the-shelf libraries or your own code to easily and efficiently create logs of the activity taking place in your application. I demonstrated logging to a file, to a database, to an email address and to the console, and wrapped things up with a couple of simple examples that demonstrated how logs could be built and analyzed in a real-world application.

I hope you enjoyed reading this article as much as I enjoyed writing it. If you’d like to know more about the topics discussed in the previous pages, here are some links you should bookmark:

PHP file manipulation functions, at http://www.php.net/manual/en/ref.filesystem.php

PHP mail functions, at http://www.php.net/manual/en/ref.mail.php

PHP MySQL functions, at http://www.php.net/manual/en/ref.mysql.php

PHP error logging functions, at http://www.php.net/manual/en/ref.errorfunc.php

The PHP Log class, at http://pear.php.net/package-info.php?package=Log

PEAR, at http://pear.php.net

Till next time…stay healthy!

Note: All examples in this article have been tested on Linux/i586 with PHP 4.2.3. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!
This entry was posted in PHP. Bookmark the permalink.

2014年6月18日 星期三

CSS 屬性 display 的值 inline block inline-block none

http://blog.xuite.net/vexed/tech/29221717-CSS+%E5%B1%AC%E6%80%A7+display+%E7%9A%84%E5%80%BC+inline+block+inline-block+none

我先列幾個網站,有興趣的人可以算算 CSS 屬性 display 的值到底有幾種︰
這麼多種也就罷了,每個瀏覽器支援的程度又不一樣 ~!@#$%^&* 。我到現在也是頭昏昏的,很多細微的差別也不是很清楚。所以我只挑我比較常用的四種出來介紹︰
  1. display : none
    把 HTML 元件的 display 設為 none 就是不顯示這個東西。 display : none 和 visibility : hidden 的差別是 display : none 這個東西就不見了,不佔空間, visibility : hidden 只是隱形看不見,還是有佔空間。
  2. display : inline
    <a> 、 <span> 、 <b> 、 <i> 、 <img> 、 <iframe> ... 這幾個 HTML 元素預設的 display 屬性是 inline ,用最簡單的講法解釋 display : inline 就是兩個 display : inline 的元素連在一起會在同一行,不會換行。
    display : inline 的 HTML 元素可以有 margin-left 、 margin-right 、 padding-left 、 padding-right ,但不能有 margin-top 、 margin-bottom 、 padding-top 、 padding-bottom 、 width 、 height 、 background-image 。
    要讓 display : inline 元素水平置中的方式是在此元素的父元素加上 text-align : center 。
    當然你也可以用 CSS 把預設是 display : inline 的 HTML 元素設成 display : block 。
    附帶一提, display : inline 元素不該包住 display : block 元素。
  3. display : block
    <div> 、 <p> 、 <h1> 、 <h2> ... 這幾種 HTML 元素預設的 display 屬性是 block ,簡單講就是不管 display : block 元素的前面後面是什麼,碰到 display : block 元素就是會換行,而 display : block 元素的寬度預設會撐到最大。
    display : block 元素不管是 margin 、 padding 、 width 、 height 、 background-image 通通都可以。
    要將 display : block 元素水平置中,方法是在此元素加上 margin : 0 auto , 0 可以取代為任何數字。
    當然也可以用 CSS 把預設是 display : block 的 HTML 元素設成 display : inline 。
  4. display : inline-block
    顧名思義,就是外面是 inline ,裡面是 block 。
    所以碰到 display : inline-block 元素不會換行,但是又可以設定 padding-top 、 padding-bottom 、 width 、 height 、 background-image 。
    用 CSS 讓連結用圖片顯示就是 inline-block 常見的應用。
一切看來這麼美好!怎麼可能,你第一天寫 CSS 嗎?下面整理一些比較常遇到的 bug ︰
  1. IE6 IE7 只有預設是 display : inline 的元素才可以設定為 display : inline-block 。
    還好有 Hack 讓預設不是 display : inline 的元素在 IE6 IE7 秀成 inline-block ︰
    div {
      display : inline-block;
      *display : inline;
      *zoom : 1;
    }
    
  2. 在 IE6 display : block 搭配 float : left 或 right 會讓 margin-left 、 margin-right 變兩倍。
    解決方法, IE6 自己除以 2 XD !
    div {
      float : left;
      margin-left : 10px;
      _margin-left : 5px;
    }
    
    另一種解法就是搭配上上面的 Hack ,讓 display : block 變成 inline-block 囉 !
    div {
      float : left;
      margin-left : 10px;
      _display : inline;
      _zoom : 1;
    }
    
  3. IE 特定情況下 display : inline-block 會和 text-indent 相衝。
    詳情請看這篇。
  4. Webkit 核心 Chrome 、 Safari 特定情況 display : inline-block 垂直對齊問題。
    詳情請看這篇。
CSS Hack 什麼時候該用 _ ,什麼時候該用 * 請看這篇。

ul li 製中

<ul style="margin-left:auto; margin-right:auto; text-align:center">
<li style="display:inline"> </li>
</ul>

2014年6月17日 星期二

PHP date and mktime function

<?php
$tomorrow  
= mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1); 

?>


<?phpecho date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo 
date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo 
date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo 
date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));?>


19天前:
$sdate = date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-19, date("Y"))); 

7天前:
$sdate = date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-7, date("Y")));
 

2014年6月12日 星期四

apache下设置不显示目录列表 Indexes FollowSymLinks

http://blog.sina.com.cn/s/blog_66c183b3010102ql.html

如果你的文件根目录里有 index.html,浏览器就会显示 index.html的内容,如果没有 index.html,浏览器就会显示文件根目录的目录列表,目录列表包括文件根目录下的文件和子目录。
同样你输入一个虚拟目录的地址:
http://localhost:8080/b/
如果该虚拟目录下没有 index.html,浏览器也会显示该虚拟目录的目录结构,列出该虚拟目录下的文件和子目录。
如何禁止 Apache 显示目录列表呢?
要禁止 Apache 显示目录结构列表,只需将 Option 中的 Indexes 去掉即可。
比如我们看看一个目录的目录配置:
<Directory "D:/Apa/blabla">
 Options Indexes FollowSymLinks #---------->Options FollowSymLinks
 AllowOverride None
 Order allow,deny
 Allow from all
</Directory>
你只需要将上面红色代码中的 Indexes 去掉,就可以禁止 Apache 显示该目录结构。用户就不会看到该目录下的文件和子目录列表了。
Indexes 的作用就是当该目录下没有 index.html 文件时,就显示目录结构,去掉 Indexes,Apache 就不会显示该目录的列表了。
第二种方法
解决办法:
        1、编辑httpd.conf文件
            vi ./conf/httpd.conf
   找到如下内容:
          ?BR>          <Directory “C:/Program Files/Apache2.2/htdocs”>
              #
              # Possible values for the Options directive are “None”, “All”,
              # or any combination of:
                 Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
              #
              # Note that “MultiViews” must be named *explicitly* — “Options All”
              # doesn’t give it to you.
              #
              # The Options directive is both complicated and important. Please see
              # http://httpd.apache.org/docs/2.2/mod/core.html#options
              # for more information.
              #
              Options Indexes FollowSymLinks
              #
              # AllowOverride controls what directives may be placed in .htaccess files.
              # It can be “All”, “None”, or any combination of the keywords:
              #   Options FileInfo AuthConfig Limit
              #
              AllowOverride None
              #
              # Controls who can get stuff from this server.
              #
              Order allow,deny
              Allow from all
          </Directory>
          ……
   在Options Indexes FollowSymLinks在Indexes前面加上 – 符号。
        即: Options -Indexes FollowSymLinks
   【备注:在Indexes前,加 + 代表允许目录浏览;加 – 代表禁止目录浏览。】
    这样的话就属于整个Apache禁止目录浏览了。
    如果是在虚拟主机中,只要增加如下信息就行:
           <Directory “D:test”>
             Options -Indexes FollowSymLinks
             AllowOverride None
             Order deny,allow
             Allow from all
         </Directory>
     这样的话就禁止在test工程下进行目录浏览。
备注: 切记莫把“Allow from all”改成 “Deny from all”,否则,整个网站都不能被打开。
   <Finished>
 还有一种方法:
可以在根目录的 .htaccess 文件中输入
<Files *> 
Options -Indexes 
</Files> 
就可以阻止Apache 将目录结构列表出来。