Chris Lad Chris Lad - 1 year ago 102
PHP Question

Generate Unique Code/ID In Contact form ? PHP/Ajax

Hello So I have my contact form and everything is working fine What I want to do now is have the PHP Generate a unique code/id for example "002302103" and attach it to the email when the email is submitted.
Basically a random reference number that is generated each time the form is used and that random set of numbers is also sent with the email.
Does anyone know how I go about this ?

Here is my php code:

$to_Email = "";
$subject = 'Message from my website'; //Subject line for emails

//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

//exit script outputting json data
$output = json_encode(
'text' => 'Request must come from Ajax'


//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));

//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

$user_Message = str_replace("\&#39;", "'", $user_Message);
$user_Message = str_replace("&#39;", "'", $user_Message);

//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
if(strlen($user_Message)<5) //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));

//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$sentMail = @mail($to_Email, $subject, $user_Message . "\r\n\n" .'-- '.$user_Name. "\r\n" .'-- '.$user_Email, $headers);

$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .'! Thank you for your email'));

Thank you in advance for helping/pointing me in the right direction

Answer Source

Try something like this:

echo mt_rand() . "\n";
echo mt_rand() . "\n";

Its output is:


mt_rand() Reference:

Append this to your message like:

$subject = 'Message from my website - '.$mt_rand();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download