So, as we all know because we are good developers - a 404 error is a “page not found” error. It occurs when someone visits your site and requests a page that does not exist on your site.
Depending on how you have chosen to set your site up, you may want/need to log 404s and other bad requests in a database table. Sometimes for example, I like to forward all requests to my index.php in the .htaccess to give me greater control over URI handling.
So I have written a simple class to handle bad requests and log them in the database. It will log all bad references to images or styles too for you which I have found quite helpful when debugging and polishing off new sites.
First, lets start with what the database table should look like:
CREATE TABLE BadRequests (
RequestID INT NOT NULL AUTO_INCREMENT,
RequestPath VARCHAR(250),
Description VARCHAR(200),
IPAddr VARCHAR(40),
RequestTime DATETIME,
PRIMARY KEY(RequestID)
);
Next, the class definition. It’s all pretty simple really. When I have all requests directed to the index.php in my .htaccess, I usually store URIs in the database. You can then compare the requested URI with what you have stored and if it’s not found then just call the log_404() function.
It will just sit there nicely out of the way logging your 404s and you won’t even notice it :)
<?php
require_once 'cl_dbconnect.php';
class BadRequests
{
private $DB; //db connection
public function __construct()
{
$this->DB = new DatabaseConnection();
}
//record a bad request error in the DB
public function log_404($error)
{
$badpath = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; //path of bad request
$IPAddr = $_SERVER['REMOTE_ADDR']; //IP address of visitor
$this->DB->ExecuteNonQuery("INSERT INTO BadRequests (RequestPath, Description, IPAddr, RequestTime) VALUES ('$badpath', '$error', '$IPAddr', NOW())");
}
public function get_bad_requests($orderby = 'RequestTime')
{
$bad_requests_log = $this->DB->ExecuteSelectQuerySet("SELECT RequestPath, UNIX_TIMESTAMP(RequestTime) AS RequestTime, ErrorCode, IPAddr FROM BadRequests ORDER BY $orderby");
return $bad_requests_log;
}
}
?>
Comments (0)
+ –