I'm trying to create a dynamic file name example 1.txt and 2.txt ... and write down the form data for every user in a separate file. but every time the form get sent by a user the script ran into this problem that my file gets overwrite.
<?php
// get the field data
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
}
$mixed_data = $name ."\n". $email ."\n". $phone ."\n" . $message ."\n";
for ($dynamic_name = 1; $dynamic_name <= 1; $dynamic_name ) {
$create_file = fopen($dynamic_name.".txt", "w");
fwrite($create_file, $mixed_data);
fclose($create_file);
}
CodePudding user response:
To avoid overwriting the file every time the form is submitted, you can use the file_exists() function to check if the file already exists, and if it does, you can increment the value of $dynamic_name by 1 and try again until you find a file name that doesn't already exist.
Here's an example of how you can modify your code to do this:
<?php
// get the field data
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
}
$mixed_data = $name ."\n". $email ."\n". $phone ."\n" . $message ."\n";
$dynamic_name = 1;
while (file_exists($dynamic_name.".txt")) {
$dynamic_name ;
}
$create_file = fopen($dynamic_name.".txt", "w");
fwrite($create_file, $mixed_data);
fclose($create_file);
This code will keep incrementing the value of $dynamic_name until it finds a file name that doesn't already exist, and then it will create the file with that name and write the form data to it.