Fix My Computer, Mark! - Capture the URL where the user came from and save it in a .txt file 

Scripts

Capture the URL where the user came from and save it in a .txt file

To capture the URL where the user came from and save it in a .txt file using PHP, you can use the $_SERVER['HTTP_REFERER'] superglobal. Here's a simple example:

<?php
// Get the referrer URL
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct Access';

// Define the file path
$file = 'referrer_log.txt';

// Open the file for writing (append mode)
$fileHandle = fopen($file, 'a');

// Format the content to write to the file
$date = date('Y-m-d H:i:s');
$logEntry = "Date: $date - Referrer: $referrer" . PHP_EOL;

// Write to the file
fwrite($fileHandle, $logEntry);

// Close the file
fclose($fileHandle);

// Optional: Output the referrer URL
echo "You came from: " . htmlspecialchars($referrer);

?>

Explanation:

  1. $_SERVER['HTTP_REFERER']: Captures the URL of the page the user came from.
  2. $file = 'referrer_log.txt': Specifies the file where the referrer data will be saved.
  3. fopen($file, 'a'): Opens the file in append mode, so new entries are added without overwriting the existing ones.
  4. fwrite($fileHandle, $logEntry): Writes the formatted referrer data and date to the file.
  5. fclose($fileHandle): Closes the file after writing.


This code logs each visit with the referrer URL and the date/time when the visit occurred. The htmlspecialchars function is used to safely display the referrer URL in case it's being echoed back to the user.


You can also capture the visitor's IP address using the $_SERVER['REMOTE_ADDR'] superglobal. Here's the updated PHP code that logs the referrer URL, the visitor's IP address, and the date:

<?php
// Get the referrer URL
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'Direct Access';

// Get the visitor's IP address
$ipAddress = $_SERVER['REMOTE_ADDR'];

// Define the file path
$file = 'referrer_log.txt';

// Open the file for writing (append mode)
$fileHandle = fopen($file, 'a');

// Format the content to write to the file
$date = date('Y-m-d H:i:s');
$logEntry = "Date: $date - IP Address: $ipAddress - Referrer: $referrer" . PHP_EOL;

// Write to the file
fwrite($fileHandle, $logEntry);

// Close the file
fclose($fileHandle);

// Optional: Output the referrer URL and IP address
echo "You came from: " . htmlspecialchars($referrer) . "<br>";
echo "Your IP address is: " . htmlspecialchars($ipAddress);

?>

Explanation:

  1. $_SERVER['REMOTE_ADDR']: Captures the visitor's IP address.
  2. $ipAddress = $_SERVER['REMOTE_ADDR']: Stores the IP address in a variable.
  3. $logEntry: Now includes the visitor's IP address along with the referrer URL and the date.


This code will log each visit with the date, IP address, and referrer URL. The visitor's IP address and the referrer URL can also be optionally displayed on the webpage.

Click to listen highlighted text!