简体   繁体   中英

Add a generated ID number in email subject

I have a contact form on my site and in my PHP, I use

$subject = $_POST['subject'];

to make the subject of the email as user entered in name='subject' field.

Is there any way I can add an ID at the end of the subject so that the ID number goes +1 every email?

I am guessing PHP will need to store this somewhere to know what was last ID number but am unsure how to pursue this.

Once done, emails I get at my to address would have following subjects:

user2354 typed subject [ID:000001]
user3456 typed subject [ID:000002] 
(and so on ...)

If you want to use a file to store the id, you can use this piece of code :

<?php 

$filename = __DIR__.'/id.txt'; // The file

if(!file_exists($filename)) { // File not exist start at 0
    $id = 0;
}
else {
    $id = file_get_contents($filename); // Get the id from the file
}

$id++; // Increment the id

file_put_contents($filename, $id); // Put the new id in the file

// The subject of the message
$subject = $user.' typed subject '.$_POST['subject'].' [ID:'.str_pad($id, 6, 0, STR_PAD_LEFT).']';

You can use a database but a simple solution, if you don't have to store other stuff in your website, is to store the ID in a file :

//Read id
$file = fopen("myfile", "r");
fscanf($file, "%u", $id);
fclose($file);

//Write new id
$file = fopen("myfile", "w");
fprintf($file, "%u", $id + 1);
fclose($file);

If you have to store more data, the most simple and efficient solution is to use a database, like MySQL with the PDO class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM