Home >Backend Development >PHP Tutorial >PHP Master | Generating One-Time Use URLs

PHP Master | Generating One-Time Use URLs

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-24 10:30:11244browse

PHP Master | Generating One-Time Use URLs

One-time URLs: Secure, Single-Use Web Addresses

A one-time URL (OTU) is a temporary web address designed for a single use. This is ideal for secure access to files or resources, often used in scenarios like account verification or limited-time access. This article details OTU generation, implementation, and expiration using PHP.

Key Concepts:

  • Secure Token Generation: Leverage PHP's sha1() and uniqid() functions to create unpredictable, unique tokens for each OTU, minimizing the risk of collisions.
  • Database Tracking: Store the token, username, and timestamp in a database to manage OTU usage and validity.
  • Token Verification and Invalidation: A processing script verifies the token against the database, performs the intended action (e.g., account activation), and immediately invalidates the token to prevent reuse.
  • Time-to-Live (TTL): Implement a TTL (e.g., 24 hours) to automatically expire OTUs, enhancing security.

Creating a One-Time URL:

Imagine a user registration system. After signup, a confirmation email containing an OTU is sent to activate the account. The OTU format would be: http://example.com/activate?token=ee97780...

Database Table:

The OTU information is stored in a database table:

<code class="language-sql">CREATE TABLE pending_users (
    token CHAR(40) NOT NULL,
    username VARCHAR(45) NOT NULL,
    tstamp INTEGER UNSIGNED NOT NULL,
    PRIMARY KEY(token)
);</code>

Token Generation (PHP):

<code class="language-php"><?php
$token = sha1(uniqid($username, true));
?></code>

uniqid() generates a unique identifier, and sha1() hashes it into a 40-character string for the token.

Database Insertion (PHP):

<code class="language-php"><?php
$query = $db->prepare("INSERT INTO pending_users (username, token, tstamp) VALUES (?, ?, ?)");
$query->execute(array($username, $token, $_SERVER["REQUEST_TIME"]));
?></code>

The token, username, and timestamp are stored for later verification.

URL Construction (PHP):

<code class="language-php"><?php
$url = "http://example.com/activate.php?token=$token";
?></code>

This creates the OTU.

Email Notification (PHP):

<code class="language-php"><?php
$message = "Thank you for signing up! Activate your account: $url";
mail($address, "Account Activation", $message);
?></code>

The OTU is sent to the user via email.

Processing the One-Time URL (activate.php):

This script verifies and processes the OTU:

<code class="language-php"><?php
// Retrieve token
$token = isset($_GET["token"]) && preg_match('/^[0-9A-F]{40}$/i', $_GET["token"]) ? $_GET["token"] : throw new Exception("Invalid token.");

// Verify token
$query = $db->prepare("SELECT username, tstamp FROM pending_users WHERE token = ?");
$query->execute(array($token));
$row = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();

if (!$row) { throw new Exception("Invalid token."); }
extract($row);

// Account activation logic...

// Delete token
$query = $db->prepare("DELETE FROM pending_users WHERE username = ? AND token = ? AND tstamp = ?");
$query->execute(array($username, $token, $tstamp));
?></code>

This script retrieves the token, verifies it against the database, performs the account activation, and then deletes the token to prevent reuse.

Adding a TTL:

<code class="language-php"><?php
$delta = 86400; // 24 hours in seconds
if ($_SERVER["REQUEST_TIME"] - $tstamp > $delta) { throw new Exception("Token expired."); }
// ...rest of the code...
?></code>

This adds a 24-hour expiration check.

Conclusion:

One-time URLs provide a robust mechanism for secure, single-use access. This approach, combined with proper database management and security practices, ensures a secure and reliable system. Remember to implement error handling and input sanitization for a production-ready solution. Consider adding a cleanup script to periodically remove expired tokens from the database.

The above is the detailed content of PHP Master | Generating One-Time Use URLs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn