📜  randon 文件名 php (1)

📅  最后修改于: 2023-12-03 15:19:42.501000             🧑  作者: Mango

Introduction to the "random_filename.php" Script

The "random_filename.php" script generates a random filename for a given file extension. This can be particularly useful when creating temporary files or assigning unique names to uploaded files.

How it Works

The script contains a function called "generate_filename" which takes a single parameter, the file extension (e.g. "jpg", "pdf", "txt"). This function generates a random 16-character string using the PHP function "uniqid" and then appends the file extension to the end of the string.

/**
 * Generate a random filename with the given file extension
 *
 * @param string $extension The file extension (without the dot)
 *
 * @return string The random filename
 */
function generate_filename($extension)
{
    $id = uniqid();
    $filename = $id . '.' . $extension;
    return $filename;
}

To use this function, simply include the "random_filename.php" script in your PHP file and call the "generate_filename" function with the desired file extension.

Examples

Here are a few examples of how to use the "generate_filename" function:

// Generate a random filename with the "png" extension
$filename = generate_filename('png');
echo $filename; // Outputs something like "60ab725b3fbf3.png"

// Generate a random filename with the "txt" extension
$filename = generate_filename('txt');
echo $filename; // Outputs something like "60ab726dbb68d.txt"

// Generate a random filename with the "jpg" extension
$filename = generate_filename('jpg');
echo $filename; // Outputs something like "60ab7278dd0b4.jpg"
Conclusion

The "random_filename.php" script is a simple yet useful tool for generating random filenames with a given file extension. It can save time and hassle when working with temporary or uploaded files.