Skip to content

Instantly share code, notes, and snippets.

@cp6
Last active February 4, 2020 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cp6/0fba345c73ed8fde6368d798ab29f32d to your computer and use it in GitHub Desktop.
Save cp6/0fba345c73ed8fde6368d798ab29f32d to your computer and use it in GitHub Desktop.
Simple PHP page HTTP request to MySQL table
<?php
function insert_request()
{
$db = new PDO('mysql:host=127.0.0.1;dbname=requests;charset=utf8mb4', 'USERNAME', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$referer = NULL;
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
}
$insert = $db->prepare('INSERT IGNORE INTO `data` (`ip`, `referer`, `method`, `user_agent`, `code`, `dir`, `time`) VALUES (?,?,?,?,?,?,?)');
$insert->execute([$_SERVER['REMOTE_ADDR'], $referer, $_SERVER['REQUEST_METHOD'], $_SERVER['HTTP_USER_AGENT'], http_response_code(), str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_FILENAME'])), $_SERVER['REQUEST_TIME']]);
}
/*
CREATE DATABASE IF NOT EXISTS `requests`;
USE `requests`;
CREATE TABLE IF NOT EXISTS `data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ip` varchar(15) DEFAULT NULL,
`referer` varchar(255) DEFAULT NULL,
`method` varchar(8) DEFAULT NULL,
`user_agent` varchar(255) DEFAULT NULL,
`dir` varchar(255) DEFAULT NULL,
`code` int(11) DEFAULT NULL,
`time` int(11) DEFAULT NULL,
`date_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
@cp6
Copy link
Author

cp6 commented Jan 18, 2020

Usage:

insert_request();

On page you want tracked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment