Skip to content
PHP Logo

How can data from a form be stored in a text file and images saved in a unique folder using PHP, possibly with the use of md5 for unique naming?

To store data from a form in a text file and save images in a unique folder using PHP, you can use the md5 function to generate unique names for the files. This ensures that each file has a distinct name and prevents overwriting. You can then write the form data to a text file and move the uploaded images to a folder with the unique name.

php
<?php
// Process form data
$name = $_POST['name'];
$email = $_POST['email'];

// Generate unique folder name using md5
$folderName = md5(uniqid());

// Create a folder for images
mkdir("uploads/$folderName");

// Save form data to a text file
$data = "Name: $name\nEmail: $email";
file_put_contents("uploads/$folderName/data.txt", $data);

// Save uploaded images to the unique folder
foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
    $image_name = $_FILES['images']['name'][$key];
    move_uploaded_file($tmp_name, "uploads/$folderName/$image_name");
}

echo "Form data and images saved successfully!";
?>