PHP - Email Form With Simple Validation
Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript, but most importantly, how to write something from scratch in PHP.
So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: [Select] <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: [Select] <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. Thanks in advance, and please let me know if it'll be possible. Similar TutorialsHi the user fill details and then the email his sent to me the only problem is that the emails keeps going to my spam, can someone help me out please I looked already php website and email format looks the same. This is the link to my form. http://www.people.eurico.co.uk/ here my form script Code: [Select] <?php // Set email variables $email_to = 'xxxxx@xxxxxxx.co.uk'; $email_subject = 'Call back form'; // Set required fields $required_fields = array('fullname','email','telephone','comment'); // set error messages $error_messages = array( 'fullname' => 'Please enter a Name to proceed.', 'email' => 'Please enter a valid Email.', 'telephone' => 'Please telephone.', 'comment' => 'Please enter your Message to continue.' ); // Set form status $form_complete = FALSE; // configure validation array $validation = array(); // check form submittal if(!empty($_POST)) { // Sanitise POST array foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value)); // Loop into required fields and make sure they match our needs foreach($required_fields as $field) { // the field has been submitted? if(!array_key_exists($field, $_POST)) array_push($validation, $field); // check there is information in the field? if($_POST[$field] == '') array_push($validation, $field); // validate the email address supplied if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field); } // basic validation result if(count($validation) == 0) { // Prepare our content string $email_content = 'peoplesmartlearning.co.uk: ' . "\n\n"; // simple email content foreach($_POST as $key => $value) { if($key != 'submit') $email_content .= $key . ': ' . $value . "\n"; } // if validation passed ok then send the email mail($email_to, $email_subject, $email_content); // Update form switch $form_complete = TRUE; } } function validate_email_address($email = FALSE) { return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE; } function remove_email_injection($field = FALSE) { return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field)); } ?> The HTML Code: [Select] <div class="call_us_form"> <p class="title">WE'LL CALL YOU BACK</p> <?php if($form_complete === FALSE): ?> <form class="contact_form" id="fm-form" method="post" action="index.php" > <fieldset> <div class="fm-req"> <label for="fm-firstname">Name</label> <input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /> <?php if(in_array('fullname', $validation)): ?><script type="text/javascript">alert("Please enter a Name"); history.back();</script><?php endif; ?> </div> <div class="fm-req"> <label for="fm-firstname">Email</label> <input type="text" id="email" class="detail" name="email" value=" <?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /> <?php if(in_array('email', $validation)): ?><script type="text/javascript">alert("Please enter a valid Email Address"); history.back();</script><?php endif; ?> </div> <div class="fm-req"> <label for="fm-firstname">Number</label> <input type="text" id="telephone" class="detail" name="telephone" value="<?php echo isset($_POST['telephone'])? $_POST['telephone'] : ''; ?>" /> <?php if(in_array('telephone', $validation)): ?><script type="text/javascript">alert("Please enter telephone number"); history.back();</script><?php endif; ?> </div> <div class="fm-req"> <label for="fm-lastname">Message</label> <textarea cols="40" rows="5" id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea> <?php if(in_array('comment', $validation)): ?><script type="text/javascript">alert("Please enter your message"); history.back();</script><?php endif; ?> </div> <input class="submit_button" type="submit" value="Call us" /> </fieldset> </form> <?php else: ?> <p>Thank you for your Message!</p> <p>We will get back to you as soon as we can</p> <script type="text/javascript"> setTimeout ('ourRedirect()', 5000) function ourRedirect () { location.href='index.php' } </script> <?php endif; ?> Hi guys, Trying to ge this to work: function checkEmail($useremail) { if (!preg_match("/^( [a-zA-Z0-9] )+( [a-zA-Z0-9\._-] )*@( [a-zA-Z0-9_-] )+( [a-zA-Z0-9\._-] +)+$/" , $useremail)) { return false; $error = '<div id="blackText"><p>Sorry! Please check your email address and try again!<p><p><a href="forumsSignUp.php">Back</a></p></div>'; } return true; //PASSWORD AND OTHER VALIDATION STUFF, blah blah blah } But its just not. Everything works fine if I remove this though. Can anyone suggest an alternative to email address validation? Thanks! I am using this a modal window(jBox) - with a web Form in it, that requires the Form (just Name & Email) to be completed and Submitted in order to close the modal window - allowing access to the main page. The Form uses this corresponding ../submit.php which this: if (empty($_POST['name'])|| empty($_POST['email'])){ $response['success'] = false; } else { $response['success'] = true; } echo json_encode($response); where, upon Form > submit, successfully shows 'error' if the Form fields are not populated, and 'success' when the Form fields are populated/submitted.
I'd like the Form to require a proper/valid email address and avoid spam and header injection Any assistance/guidance is appreciated
I have made a form that asks a user for email, first name, last name, and password. I am using Spry validation tools in Dreamweaver. When I used those only, I did not have a problem. The problem began once I tried to actually check to see if the email was already registered. I have tried changing so many things like what $_POST variable to look for at the beginning, to different db connection arrangements. I am stumped. The only other thing I can think of is that I have the order wrong somehow in the logic. Thanks for the help. First, here is the form: Code: [Select] Enter Email<?php if($error_email_taken) echo ": $error_email_taken."; ?> <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input name="email" type="text" id="email" value="<?php if($_POST["email"]) echo $_POST["email"]; ?>"> <input name="first" type="text" id="first" value="<?php if($_POST["first"]) echo $_POST["first"]; ?>"> <input name="last" type="text" id="last" value="<?php if($_POST["last"]) echo $_POST["last"]; ?>"> <input name="pass" type="password" class="formText1" id="pass" value="<?php if($_POST["pass"]) echo $_POST["pass"]; ?>"> <input type="submit" name="Submit" value="Submit"></td> </form> And the email verification and insert, which is placed before the opening html tag. Code: [Select] <?php if($_POST['Submit']) { //Check to see if email is registered. $email = $_POST['email']; $dbc=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $q_1 = "SELECT users_email FROM table WHERE users_email = $email"; $r_1 = mysqli_query($dbc, $q_1); $rows_1 = mysqli_num_rows($r_1); if ($rows_1 == 0) { //If 0, email is not already registered. $new_email = $_POST['email']; } else { $error_email_taken = "This email is already registered."; } //If everything is good, insert the information. if(isset($new_email)) { $first_name = $_POST['first']; $last_name = $_POST['last']; $password = $_POST['pass']; //Insert User information. $q_2 = "INSERT INTO table (users_email, users_first, users_last, users_pass) VALUES ('$new_email', '$first_name', '$last_name', '$password')"; $r_2 = mysqli_query($dbc, $q_2); //Go to new page if form was submitted and information properly inserted. header('Location: new_page.php'); }//End: if($new_email) } //End: if $_POST['submit'] ?> I've simplified it as much as I could. I totally eliminated stuff like a password hash, etc. because I wanted to get it down to the most simple form, so once this gets working, I'll add that other stuff later. Thanks so much again. I'm having trouble with this form. I can't seem to figure out the rest of what is required I have already done most of it...I'm just stuck on these parts: Province Select : (AutoGeneration, Multiple Select, Memory) AutoGeneration using Provinces Array: The Province Select box is generated by PHP using this array: provinces.txt Cut and paste this array into your own code. Multiple Selections: Note that the province select box permits multiple values to be selected. View the HTML source to see the configuration details. Also note how $_POST delivers these multiple values as an array. Select Box Memory: The Province select box retains the user choices after a POST. For each province selected by the user, your code will generate the "selected" attribute in the <options> tag for that province. View the HTML source of the working solution to see how this works. Status CheckBoxes (Multiple Select, Memory) Multiple Selections: Note that these checkboxes have been configured in the HTML to permit multiple selections. Also note that $_POST delivers these multiple selection values in an array. Status Box Memory:The Status Box retains the user choices after a POST. Your code will need to generate the "checked" attribute in the <input> tag for each item selected. Do not generate the checkboxes with an array. Location Radio button: Do not generate the radio buttons with an array. The Location radio button retains the user choice after a POST. Validation Success Message: Where does it go - The final success message is placed within the <div class="success"></div> tags at the top of the HTML. Use a Loop: Generate the success message with a single array loop that reads the $_POST array and prints out the success message as an ordered list. Form Variables List Un-Ordered List - The form variables are displayed in an unordered list . CSS removes the bullet. Names Capitolised - The names of the form variables are capitolised ( use strtoupper() function ) . Handle Empty Values - Print "---None supplied---" if the variable is empty. Province Long Names - Print the long names of the provinces selected as comma separated string Status Choices - Print the status choices as a comma separated string. Functions I need to use: empty() - is the string empty. Unfortunately, a "0" value counts as an empty string. strlen() - returns the number of characters in a string. is_numeric() - is the string a number count() - how many rows in an array is_array() - is the variable an array isset() - does the variable or member of array exist in_array() -does this string exist in this array strtoupper() - convert string to upper case. join() - you'll want this one too. Converts an array of strings into a string with a delimiter. error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); - suppresses warning messages in your code. Place at top. foreach ($_POST as $KEY => $VAL) {} - walk through the $_POST array (or any array) My code: Code: [Select] <!--"StAuth10065: I Adam Graham, 000136921 certify that this material is my original work. No other person's work has been used without due acknowledgement. I have not made my work available to anyone else."--> <? $PROVINCES = array( "--" => "--- Please Select Provinces ---", "nf"=>"Newfoundland", "pe"=>"Prince Edward Island", "nb"=>"New Brunswick", "ns"=>"Nova Scotia", "qc"=>"Quebec", "on"=>"Ontario", "mb"=>"Manitoba", "sk"=>"Saskatchewan", "ab"=>"Alberta", "bc"=>"British Columbia", "nt"=>"Northwest Territories"); if ($_SERVER['REQUEST_METHOD'] == 'GET') { $dimwelcomeMsg = TRUE; } if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_POST['uname'] == ''){ $errMsgs['uname'] = "Username must not be blank!!!"; $unameInError = true; } if (empty($_POST['year']) == TRUE){ $errMsgs['year'] = "Year must not be blank!!"; } if (count($errMsg) > 0 ): $dispErrorMsg = TRUE; else: foreach ($_POST as $key => $val): $key = strtoupper($key); $successMsg[$key] = $val; endforeach; $dispSuccessMsg = TRUE; endif; } ?> <html > <head> <title>Comp10065 - Simple Form Validatioon</title> <style type="text/css"> body { margin: 0; padding: 0; font: 80%/1.5 Arial,Helvetica,sans-serif; color: #111; background-color: green; } h2 { margin: 0px; padding: 10px; font-family: Georgia, "Times New Roman", Times, serif; font-size: 200%; font-weight: normal; color: #FFF; background-color: #CCC; border-bottom: #BBB 2px solid; } h1 {color:#006600} p#copyright { margin: 20px 10px; font-size: 90%; color: #999; } div.form-container { margin: 10px; padding: 5px; background-color: #FFF; border: #EEE 1px solid; } p.legend { margin-bottom: 1em; } p.legend em { color: #C00; font-style: normal; } div.errors { margin: 0 0 10px 0; padding: 5px 10px; border: #FC6 1px solid; background-color: #FFC; } div.errors p { margin: 0; } div.errors p em { color: #C00; font-style: normal; font-weight: bold; } div.success { margin: 0 0 10px 0; padding: 5px 10px; border: #FC6 1px solid; background-color: #FFC; } div.success p { margin: 0; color:#006633} div.success li {list-style-type: none; } div.form-container form p { margin: 0; } div.form-container form p.note { margin-left: 170px; font-size: 90%; color: #333; } div.form-container form fieldset { margin: 10px 0; padding: 10px; border: #DDD 1px solid; } div.form-container form legend { font-weight: bold; color: #666; } div.form-container form fieldset div { padding: 0.25em 0; } div.form-container label, div.form-container span.label { margin-right: 10px; padding-right: 10px; width: 150px; display: block; float: left; text-align: right; position: relative; } div.form-container label.error, div.form-container span.error { color: #000; } div.form-container select.error, div.form-container div.error {background-color: #FEF;} div.form-container label em, div.form-container span.label em { position: absolute; right: 0; font-size: 120%; font-style: normal; color: #C00; } div.form-container input.error { border-color: #C00; background-color: #FEF; } div.form-container input:focus, div.form-container input.error:focus, div.form-container textarea:focus { background-color: #FFC; border-color: #FC6; } div.form-container div.controlset {margin: 3px} div.form-container div.controlset label, div.form-container div.controlset input { display: inline; float: none; } div.form-container div.controlset div { margin-left: 170px; } div.form-container div.buttonrow { padding-left: 430px; border: 1px solid #CCCCCC } div#wrapper {width: 700px ; margin-left: auto; margin-right: auto} pre {color:black; font-size: 10pt; font-weight: bold; margin-left: 30px} </style> </head> <body> <div id="wrapper"> <h1> Form Validation Lab</h1> <div class="form-container"> <? if ($_SERVER['REQUEST_METHOD'] == 'GET') : ?> <? if (displayWelcomeMsg) : ?> <p>Please fill in the form........</p> <? endif; ?> <? endif; ?> <? if ($displaySuccessMsg): ?> <div class="success"> <p>Thank you for your submission.</p> <ol> <? foreach($successMsgs as $key => $successMsg): ?> <li><?= $key ?> = <?= $successMsg ?> </li> <? endforeach; ?> </ol> </div> <? endif; ?> <? if ($dispErrorMsg) : ?> <div class="errors"> <p><em>Oops...the following errors were encountered</em></p> <ul> <? foreach ($errMsgs as $key => $errMsg): ?> <li><?= $errMsgs ?> </li> <? endforeach; ?> </ul> <p>Please correct the errors and re-submit this form.</p> </div> <? endif; ?> <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post"> <input type="hidden" name="act" value="post"> <div class="buttonrow"> <input type="submit" value="Submit This Form " class="button" /> <a href="<?= $_SERVER['PHP_SELF'] ?>" >Start Again</a> </div> <p class="legend"><strong>Note:</strong> Required fields are marked with an asterisk (<em>*</em>)</p> <fieldset> <legend>User Details</legend> <div> <label for="uname" >User Name <em>*</em></label> <? if (isset($errMsgs['uname'])) echo 'class = "errors"' ?> <input id="uname" type="text" name="uname" value="<?=$_POST['uname'] ?>" /> (must be greater than 5 chars)</div> <div> <label for="email">Email Address </label> <input id="email" type="text" name="email" value="" /> </div> </fieldset> <fieldset> <legend>Submission</legend> <div> <label for="year">Year (YYYY) <em>*</em></label> <input id="year" type="text" name="year" <? if (isset($errMsgs['year'])) echo 'class = "errors"' ?> value="" size="4" maxlength="4" /> (4 digit number)</div> <div> <label for="date">Month (MM)</label> <input id="date" type="text" name="month" value="" size="4" maxlength="2" /> (number ranging from 1-12)</div> </fieldset> <fieldset> <legend>Preferences</legend> <div> <label for="type" >Province (Multiple Select) <em>*</em></label> <select name = "province[]" multiple size = "12" id="type" > <? foreach ($PROVINCES as $abbreviation => $longname); ?> <option value = "<?=$abbreviation ?> "></option> <? enfgoreach; ?> </select> </div> <div class= 'controlset' > <span class="label">Status (Mult Select)<em>*</em></span> <input name="status[]" id="approved" value="approved" type="checkbox" /> <label for="approved">Approved</label> <input name="status[]" id="pending" value="pending" type="checkbox" /> <label for="pending">Pending Application</label> <input name="status[]" id="actives" value="actives" type="checkbox" /> <label for="actives">Active Service</label> </div> <div class= 'controlset'> <span class="label"> Location <em>*</em></span> <input name="location" id="radio1" value="Garage" type="radio" /> <label for="radio1">Garage</label> <input name="location" id="radio2" value="Attic" type="radio" /> <label for="radio2">Attic</label> <input name="location" id="radio3" value="House" type="radio" /> <label for="radio3">House</label> </div> </fieldset> </form> <p>This debug info is here to help you. You are only required to display the POST array</p> <pre><?= print_r($_POST,true) ?> </pre> </div> </div> </body> </html> I am trying to add some simple validation to my form. I only wanter users to be able to enter 11 numbers into the number field or else it will say 11 digit numbers only. A validation to only allow users to input numbers anything else and it brings up an error. and finally i want to check the email string to make sure it has an @ and a (.) . How would i go about adding these validation techniques to this code? <?php if ($_SERVER['REQUEST_METHOD']=="POST"){ // Recipent Email $to="andrew@peppermintdigital.com"; $subject="Reply to Peppermint Invitation"; $title = $_POST['title']; $name = stripslashes($_POST['name']); $add1 = stripslashes($_POST['add1']); $add2 = stripslashes($_POST['add2']); $add3 = stripslashes($_POST['add3']); $add4 = stripslashes($_POST['add4']); $postcode = stripslashes($_POST['postcode']); $number = stripslashes($_POST['number']); $email = stripslashes($_POST['email']); $time = $_POST['time']; $from = ($_POST['name']) . "<".stripslashes($_POST['email']).">"; $subject = ($_POST['name']) . "<".stripslashes($_POST['email']).">"; // Email Message $message = "Name : $title $name. Address : $add1, $add2, $add3, $add4, $postcode. Phone Number : $number. Email : $email. Appointment Time : $time"; // Validation Begins // Add Erros To Array $errors = array(); // Check Form if (!$_POST['title']) $errors[] = "Title Required"; if (!$_POST['name']) $errors[] = "Name Required"; if (!$_POST['add1']) $errors[] = "Address Required"; if (!$_POST['add4']) $errors[] = "City Required"; if (!$_POST['postcode']) $errors[] = "Postcode Required"; if (!$_POST['number']) $errors[] = "Number Required"; if(!$_POST['number'] == 11) $errors[] = "Full Number Required"; if (!$_POST['email']) $errors[] = "Email Required"; if (!$_POST['time']) $errors[] = "Time Required"; // Display Errors if (count($errors)>0) { echo"<h1 class='fail'>"; foreach($errors as $err) echo "$err.\n"; echo"</h1>"; echo " <form method='post' action='#'> <table cellpadding='0' cellspacing='0' border='0'> <tr> <td class='form_results' colspan='2'> </td> </tr> <tr> <td class='form_left' valign='top'> <table width='200' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='title_left' valign='top'>Title</td> </tr> <tr> <td class='sname_left' valign='top'>Name</td> </tr> <tr> <td class='add_left' valign='top'>Address</td> </tr> <tr> <td class='post_left' valign='top'>Postcode</td> </tr> <tr> <td class='number_left' valign='top'>Phone Number</td> </tr> <tr> <td class='email_left' valign='top'>Email Address</td> </tr> <tr> <td class='time_left' valign='top'>Appointment Time</td> </tr> </table> </td> <td class='form_right' valign='top'> <table width='300' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='right_spacer'> <select name='title' class='select'> <option>Mr</option> <option>Mrs</option> <option>Ms</option> <option>Miss</option> </select> </td> </tr> <tr> <td class='right_spacer'><input type='text' name='name' class='field' value='$name' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add1' class='field' value='$add1' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add2' class='field' value='$add2' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add3' class='field' value='$add3' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add4' class='field' value='$add4' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='postcode' class='field' value='$postcode' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='number' class='field' value='$number' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='email' class='field' value='$email' /></td> </tr> <tr> <td class='right_spacer'> <select name='time' class='select'> <option>5.30 pm</option> <option>6.30 pm</option> <option>7.30 pm</option> </select> </td> </tr> </table> </td> </tr> <tr> <td class='form_buttom' colspan='2'> <input name='submit' type='submit' value='Submit' class='submit_button' /> </td> </tr> </table> </form> "; } else { // Build message headers $headers = "From: $from\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\""; // Send message if (@mail($to, $subject, $message, $headers)) echo "<h1 class='success'>Your message has been sent.</h1>"; else echo "<h1 class='fail'>Your message was not sent at this time.</h1>"; } } else { echo " <form method='post' action='#'> <table cellpadding='0' cellspacing='0' border='0'> <tr> <td class='form_results' colspan='2'> </td> </tr> <tr> <td class='form_left' valign='top'> <table width='200' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='title_left' valign='top'>Title</td> </tr> <tr> <td class='sname_left' valign='top'>Name</td> </tr> <tr> <td class='add_left' valign='top'>Address</td> </tr> <tr> <td class='post_left' valign='top'>Postcode</td> </tr> <tr> <td class='number_left' valign='top'>Phone Number</td> </tr> <tr> <td class='email_left' valign='top'>Email Address</td> </tr> <tr> <td class='time_left' valign='top'>Appointment Time</td> </tr> </table> </td> <td class='form_right' valign='top'> <table width='300' border='0' cellspacing='0' cellpadding='0'> <tr> <td class='right_spacer'> <select name='title' class='select'> <option>Mr</option> <option>Mrs</option> <option>Ms</option> <option>Miss</option> </select> </td> </tr> <tr> <td class='right_spacer'><input type='text' name='name' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add1' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add2' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add3' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='add4' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='postcode' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='number' class='field' /></td> </tr> <tr> <td class='right_spacer'><input type='text' name='email' class='field' /></td> </tr> <tr> <td class='right_spacer'> <select name='time' class='select'> <option>5.30 pm</option> <option>6.30 pm</option> <option>7.30 pm</option> </select> </td> </tr> </table> </td> </tr> <tr> <td class='form_buttom' colspan='2'> <input name='submit' type='submit' value='Submit' class='submit_button' /> </td> </tr> </table> </form> "; } ?> Hi all, I have the below which is meant to check if the required fields in a form have been submitted, however when submit is clicked, even with no values in the boxes, the form submits as normal. <?php error_reporting(E_ALL); ini_set('display_errors', '1'); include_once ('formvalidator.php'); ?> <link href="../Styles/form_dark.css" rel="stylesheet" type="text/css" /> <?php $show_form=true; if(isset($_POST['submit'])) { $validator = new FormValidator(); $validator->addValidation("user_name","req","Please fill in Name"); $validator->addValidation("user_password","req","Please enter a password"); $validator->addValidation("user_email","email", "The input for Email should be a valid email value"); $validator->addValidation("user_email","req","Please fill in Email"); if($validator->ValidateForm()) { echo "<h2>Validation Success!</h2>"; $show_form=false; } else { echo "<B>Validation Errors:</B>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> <form class="dark" action="regdo.php" method="post" > <ol> <li> <fieldset> <legend>User Registration</legend> <ol> <li> <label for="user_name">Username</label> <input type="text" id="user_name" name="user_name" value="" /> </li> <li> <label for="user_email">E-Mail Address</label> <input type="text" id="user_email" name="user_email" value="" /> </li> <li> <label for="user_password">Password</label> <input type="password" id="user_password" name="user_password" value="" /> </li> </ol> </fieldset> </li> </ol> <p style="text-align:right;"> <input type="reset" value="CANCEL" /> <input type="submit" value="OK" /> </p> </form> <?php }//true == $show_form ?> Can anyone explain what the problem is? Cheers I have the simple code below which seems to have worked on forms from a contact page on a website. Unfortunately, it seems to only send the forms if all fields are entered. I have played with the code but cannot seem to get it to send any field that has been completed on submit. Can someone help please? <?php $emailAddress = "bigL@gmail.com"; $thankyouPage = ""; session_start(); if (!empty($_POST)) { foreach ($_POST as $key=>$value) { $_POST[$key] = stripslashes($_POST[$key]); $_POST[$key] = htmlspecialchars($_POST[$key],ENT_QUOTES); } } if (isset($_POST['send']) AND isset($_SESSION['msgCount'])) { if ($_SESSION['msgCount'] >= "3") $alert = "Only 3 messages can be s +ent per session."; if (empty($alert)) { $_SESSION['msgCount']++; putenv('TZ=EST5EDT'); // eastern time $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n" +; $message = "<table cellpadding='5' border='1'>"; foreach ($_POST as $key => $value) if (!preg_match("(^send)",$key)) { $value = wordwrap($value,65,"<br />"); $message .="<tr><td><b>$key</b></td><td>$value</td></tr>"; } $message .= "</table>"; $message .= "<br />Time of the message: ".date(" F d h:ia")."<br +/>"; $message .= "IP Address: ".$_SERVER['REMOTE_ADDR']."<br />"; $message .= "Hostname: ".gethostbyaddr($_SERVER['REMOTE_ADDR'])."< +br />"; $subject = $_SERVER['HTTP_HOST']." Message"; mail($emailAddress,$subject,$message,$headers); if (!empty($thankyouPage)) { header('location: '.$thankyouPage); die(); } unset($_POST); $alert = "Your enquiry has been sent, we will respond as soon as p +ossible."; } } if (!isset($_SESSION['msgCount'])) $_SESSION['msgCount'] = 0; ?> if anyone out there fancy's helping the needy please can you cast your eyes over my mess! and possibly help me find my way out of this maze? So im useing a third party form, and a third party php script.......... cant get them to work together . form script : [color=red//-------------------------------------------------[/color] <form action="phpquote.php" method="post" id="reserve-form"> <div class="box"> <div class="left-top-corner"> <div class="right-top-corner"> <div class="border-top"></div> </div> </div> <div class="border-left"> <div class="border-right"> <div class="xcontent"> <h5>Get an online quote for your journey</h5> <p>please fill in all fields for your quote.</p> <fieldset> <div class="field"> <label>Customer Information</label> <input type="text" id="name" value="Name" onblur="if(this.value==''){this.value='Name'}" onfocus="if(this.value=='Name'){this.value=''}" /> </div> <div> <input type="text" id="number" value="Phone" onblur="if(this.value==''){this.value='Phone'}" onfocus="if(this.value=='Phone'){this.value=''}" /> </div> </fieldset> <fieldset class="style1"> <div class="field"> <label>Travel Date/ Time</label> <select id="year"> <option>2010</option> <option>2011</option> </select> <select class="sel-1" id="month"> <option>Jan</option> <option>Feb</option> <option>Mar</option> <option>Apr</option> <option>May</option> <option>Jun</option> <option>Jul</option> <option>Aug</option> <option>Oct</option> <option>Sep</option> <option>Nov</option> <option>Dec</option> </select> <select class="sel-2" id="date"> <option>1</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> <option>15</option> <option>16</option> <option>17</option> <option>18</option> <option>19</option> <option>20</option> <option>21</option> <option>22</option> <option>23</option> <option>24</option> <option>25</option> <option>26</option> <option>27</option> <option>28</option> <option>29</option> <option>30</option> <option>31</option> </select> </div> <div class="field"> <select class="sel-2" id="time"> <option>00</option> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> <option>07</option> <option>08</option> <option>09</option> <option>10</option> <option>11</option> <option>12</option> <option>13</option> <option>14</option> <option>15</option> <option>16</option> <option>17</option> <option>18</option> <option>19</option> <option>20</option> <option>21</option> <option>22</option> <option>23</option></select> <select class="sel-2" id="time"> <option>00</option> <option>15</option> <option>30</option> <option>45</option> </select> </div> <div class="field"> <label>No. Passangers</label> <select id="year"> <option>01</option> <option>02</option> <option>03</option> <option>04</option> <option>05</option> <option>06</option> </select> </div> </fieldset> <fieldset class="style2"> <div class="field"> <label>Pickup Information</label> <input type="text" id="where" value="Pickup Address" onblur="if(this.value==''){this.value='Pickup Address'}" onfocus="if(this.value=='Pickup Address'){this.value=''}" /> </div> <div> <select id="where"> <option>or Airport</option> <option>Stansted</option> <option>Gatwick</option> <option>Heathrow</option> <option>Luton</option> </select> </div> </fieldset> <fieldset class="style2 style3"> <div class="field"> <label>Drop-off Information</label> <input type="text" id="to" value="Drop-off Address" onblur="if(this.value==''){this.value='Drop-off Address'}" onfocus="if(this.value=='Drop-off Address'){this.value=''}" /> </div> <div> <select id="to"> <option>or Airport</option> <option>Stansted</option> <option>Gatwick</option> <option>Heathrow</option> <option>Luton</option> </select> </div> </fieldset> </div> </div> </div> <div class="left-bot-corner"> <div class="right-bot-corner"> <div class="border-bot"><a href="#" class="link2" onclick="document.getElementById('reserve-form').submit()"><em><b>Get Quote</b></em></a></div> </div> </div> </div> </form> //----------------------------------------------------------------------------- php script //----------------------------------------------------------------------------- <?php //--------------------------Set these paramaters-------------------------- // Subject of email sent to you. $subject = 'Results from Contact form'; // Your email address. This is where the form information will be sent. $emailadd = 'm.mcdade@hotmail.co.uk'; // Where to redirect after form is processed. $url = 'http://www.mock.thetaxirank.co.uk/thankyou.html'; // Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty. $req = '0'; // --------------------------Do not edit below this line-------------------------- $text = "Results from form:\n\n"; $space = ' '; $line = ' '; foreach ($_POST as $key => $value) { if ($req == '1') { if ($value == '') {echo "$key is empty";die;} } $j = strlen($key); if ($j >= 20) {echo "Name of form element $key cannot be longer than 20 characters";die;} $j = 20 - $j; for ($i = 1; $i <= $j; $i++) {$space .= ' ';} $value = str_replace('\n', "$line", $value); $conc = "{$key}:$space{$value}$line"; $text .= $conc; $space = ' '; } mail($emailadd, $subject, $text, 'From: '.$emailadd.''); echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">'; ?> //----------------------------------------------------------------------------- any advice will be appreciated..... thanks in advance to any kind souls !!! Hello all, I used simple php email function but it send an email in junk folder or spam. Can anyone tell me why is this so? Her is the code: $host = "ssl://smtp.gmail.com"; $port = "465"; $to = " xx@gmail.com"; // note the comma $subject = " $_POST[company_website] "; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: About Wholesale Account' . "<$_POST[email]>\r\n"; $headers .= 'Cc: mail@gmail.com' . "\r\n"; $headers .= 'Bcc: cc@gmail.com' . "\r\n"; mail($to, $subject, $message, $headers); So basically here is what Im trying to do: I have a site that has an employee roster on it...this roster obviously has the employees information including their email addresses next to their names. I am trying to create a script that will allow an employee to easily email another employee on the roster simply by clicking the email address for that employee. To sum this up (or make it even more confusing) ... If i have an email address LINK of "myname@company.com" next to an employees name and a person clicks on that link ... I need some code that will take that email address link (myname@company.com) and add it into the email script into the "$to" function so that when they submit the email form it will go to the employees email (myname@company). I have several employee on this roster so I need a universal script that takes the email links information (ie myname@company.com) and puts it into the mail.php script. I do not want to have to make individual email scripts for each employee just to add to change the "$to" variable on each script!!! So basically how do I add a "links information" into a php script ?? Does this make sense ??? Are you confused ?? I can TRY to explain better if need be. I have looked all over the internet for this and have searched this forum however I have not been able to find a solution to this. A step in the right direction would be great!!! Hi, I have done email validation. At present it shows invalid email address if I kept blank but in the same time inserted the records in database. I want user to stay at the same page if anything is invalid. if(!empty($_POST['emailId'])){ if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_POST['emailId'])){ $records['Email']=$_POST['emailId']; } else{ $emsg="Please enter valid Email address"; }} else{ $emsg="Please enter valid Email address"; } And I have used like <tr><td>Email id</td><td><input type="text" name="emailId"></td><td><?php echo ".$emsg." ;?></td></tr> Can anybody help me in this regard? So, im trying to make my job a little easier. lol... I am constantly sending emails to the managers for escalations on calls... So I wrote this so far... (forgive my poor php skills, this is the first thing ive ever made. lol.) It does work so far, but, a friend wants to use it too, and Ive adapted it so he can enter his email address in, but, how can I make it so that it will validate only to send from @specificdomain.com ? Ive tried a few things, and just butchered it. lol.... Thanks for any help or tips. Code: [Select] <?php //$name = $_POST["email"]; $name = $_POST["name"]; $policynumber = $_POST["policynumber"]; $phonenumber = $_POST["phonenumber"]; $issue = $_POST["issue"]; $purchased = $_POST ["purchased"]; $infocheck = $_POST ["infocheck"]; $additionalinfo = stripslashes($_POST["additionalinfo"]); //checkbox value readout $mailcc = $_POST['sendmetoo']; $email_to = "SalesLevel2@specificurl.com"; // Who the email is to $email_from = $_POST['emailfrom']; // Who the email is from $email_subject = $policynumber.' - '.$issue; // The Subject of the email //here you can define whatever you want to... $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/plain; charset=UTF-8\r\n"; $headers .= "To: <".$email_to.">\r\n"; $headers .= "From: ".$email_from."\r\n"; //we control if sendmetoo is checked... if($mailcc == 'sendtome'){ $headers .= "Cc: ".$email_from."\r\n"; } //$headers .= "Bcc: noone@nowhere.com\r\n"; $email_message = "Sales Level 2,"; $email_message .= "\n\nPolicy Number: " .$policynumber; $email_message .= "\nClients Name: " .$name; $email_message .= "\nPhone Number: " .$phonenumber; $email_message .= "\nReason(s): " .$issue; $email_message .= "\nPurchased Already: " .$purchased; $email_message .= "\nAll info correct?: " .$infocheck; $email_message .= "\n\nAdditional Information: " .$additionalinfo; "\n\n\n\n". // Message that the email has in it //$headers = "From: ".$email_from; $ok = @mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "<font face=verdana size=2><center>Your message has been sent<br> to Sales Level 2<br> Click <a href=\"#\" onclick=\"history.back();\">here</a> to go back</center>"; } else { die("Sorry but the email could not be sent. Please go back and try again!"); } ?> Hey guys.. I'm completely done with my contact form data validation except I cannot seem to get one part. For my email field I need to make sure that it is a valid email address and not just words. Also, I would like to make the phone number specific length. Any ideas on how to go about this? thanks guys! <?php ini_set('display_errors', '0'); //Define Variables. $FirstName = $_GET['FirstNameTextBox']; $LastName = $_GET['LastNameTextBox']; $PhoneNumber = $_GET['PhoneNumberTextBox']; $EmailAddress = $_GET['EmailAddressTextBox']; $Address = $_GET['AddressTextBox']; $City = $_GET['CityTextBox']; $State = $_GET['StateDropDownBox']; $Zip = $_GET['ZipTextBox']; $error1='*Please enter a First Name<br>'; $error2='*Please enter a Last Name<br>'; $error3='*Please enter a Phone Number<br>'; $error4='*Please choose a state<br>'; $error5='*Please enter a valid email address<br>'; $day2 = mktime(0,0,0,date("m"),date("d")+2,date("Y")); $day3 = mktime(0,0,0,date("m"),date("d")+3,date("Y")); $day7 = mktime(0,0,0,date("m"),date("d")+7,date("Y")); // Array to collect messages $messages = array(); //Display errors. if($FirstName=="") {$messages[] = $error1; } if($LastName=="") {$messages[] = $error2; } if($PhoneNumber=="") {$messages[] = $error3; } if($State=="") {$messages[] = $error4; } if($EmailAddress=="") {$messages[] = $error5; } // Don't do this part unless we have no errors if (empty($messages)) { //Display correct contact date. if($State == "NY") { $messages[] = "Hello $FirstName $LastName! Thank you for contacting me. I will get back to you within 2 days, before " .date("d M Y", $day2); } if($State == "NJ") { $messages[] = "$Hello FirstName $LastName! Thank you for contacting me. I will get back to you within 3 days, before " .date("d M Y", $day3); } if($State == "Other") { $messages[] = "$Hello FirstName $LastName! Thank you for contacting me. I will get back to you within 1 week, before " .date("d M Y", $day7); } } // END if empty($messages echo implode('<BR>', $messages); ?> <p>--<a href="Contact_Form.html" class="style2"><span class="style1">Go Back</span></a>--</p> </body> </html> Hello, I am working with a SMTP class to send an email. It's all working perfectly fine, but when the email is received (sent from the online form), and I open my email and click reply, there are two email addresses. The correct one (which I entered when I sent the email), and my ftp username for the site?? I've got three files that could effect this, but I was unable to locate any problems: mailer.php ( smtp send mail class) mail.php ( submission data: title, subject, etc. ) contact_form.php ( form for submission ) I am only including the file which I think is applicable (mail.php), but let me know if you would also like to see the mailer.php class. Current output: reply-to ftpusername@domainname.com, correct_from_email@fromemail.com mail.php: <?php set_time_limit(120); function sendHTMLmail($from, $to, $subject, $message) { $message = wordwrap($message, 70); // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= "From: $from\r\n"; // Mail it mail($to, $subject, $message, $headers); } function sendHTMLmail2($fromid, $to, $subject, $message) { echo $fromid; echo $to; echo $subject; echo $message; include_once("mailer.php"); $mail = new PHPMailer(); $mail->IsMail(); // SMTP servers $mail->Host = "localhost"; $mail->From = $fromid; $mail->FromName = $fromid; $mail->IsHTML(true); $mail->AddAddress($to, $to); $mail->Subject = $subject; $mail->Body = $message; $mail->AltBody = "Please enable HTML to read this"; $mail->Send(); exit; } function isValidEmail($email) { return eregi("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$", $email); } class smtp_mail { var $host; var $port = 25; var $user; var $pass; var $debug = false; var $conn; var $result_str; var $charset = "utf-8"; var $in; var $from_r; //mail format 0=normal 1=html var $mailformat = 0; function smtp_mail($host, $port, $user, $pass, $debug = false) { $this->host = $host; $this->port = $port; $this->user = base64_encode($user); $this->pass = base64_encode($pass); $this->debug = $debug; $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket) { $this->result_str = "Create socket:" . socket_strerror(socket_last_error()); $this->debug_show($this->result_str); } else { exit("Initialize Faild,Check your internet seting,please"); } $this->conn = socket_connect($this->socket, $this->host, $this->port); if ($this->conn) { $this->result_str = "Create SOCKET Connect:" . socket_strerror(socket_last_error()); $this->debug_show($this->result_str); } else { exit("Initialize Faild,Check your internet seting,please"); } $this->result_str = "Server answer:<font color=#cc0000>" . socket_read($this->socket, 1024) . "</font>"; $this->debug_show($this->result_str); } function debug_show($str) { if ($this->debug) { echo $str . "<p>\r\n"; } } function send($from, $to, $subject, $body) { if ($from == "" || $to == "") { exit("type mail address please"); } if ($subject == "") $sebject = "none title"; if ($body == "") $body = "none content"; $All = "From:$from;\r\n"; $All .= "To:$to;\r\n"; $All .= "Subject:$subject;\r\n"; if ($this->mailformat == 1) { $All .= "Content-Type:text/html;\r\n"; } else { $All .= "Content-Type:text/plain;\r\n"; } $All .= "Charset:" . $this->charset . ";\r\n\r\n"; $All .= " " . $body; $this->in = "EHLO HELO\r\n"; $this->docommand(); $this->in = "AUTH LOGIN\r\n"; $this->docommand(); $this->in = $this->user . "\r\n"; $this->docommand(); $this->in = $this->pass . "\r\n"; $this->docommand(); if (!eregi("235", $this->result_str)) { $this->result_str = "smtp auth faild"; $this->debug_show($this->result_str); return 0; } $this->in = "MAIL FROM: $from\r\n"; $this->docommand(); $this->in = "RCPT TO: $to\r\n"; $this->docommand(); $this->in = "DATA\r\n"; $this->docommand(); $this->in = $All . "\r\n.\r\n"; $this->docommand(); if (!eregi("250", $this->result_str)) { $this->result_str = "Send mail faild!"; $this->debug_show($this->result_str); return 0; } $this->in = "QUIT\r\n"; $this->docommand(); socket_close($this->socket); return 1; } function docommand() { socket_write($this->socket, $this->in, strlen($this->in)); $this->debug_show("Client command:" . $this->in); $this->result_str = "server answer:<font color=#cc0000>" . socket_read($this->socket, 1024) . "</font>"; $this->debug_show($this->result_str); } } ?> I am working on user validation through email and I am having some problems with it. I can get it to work but it gives me probloms some times. This is the link that is sent to the users after they sign up Code: [Select] mydomain/confirm.php?id=".$id."&userkey=".$userkey and this is what i have for the confirm page Code: [Select] <?php //connection info $userquery = mysql_query("SELECT * FROM user"); $active=mysql_result($userquery, "active"); $userid=mysql_result($userquery, "id"); $userkey=mysql_result($userquery, "userkey"); if ($active == 1) { printf("This account has already been activated"); echo "<br />"; } elseif($userkey != $posteduserkey){ printf("We are sorry but the data offered does not match data listed, plese contact system admin."); } else{ $query="UPDATE user SET active='1' WHERE id='$id'"; mysql_query($query) or die (mysql_error()); echo "You have activated your account"; ?> <div align="center"><br /><a href="login.php" class="nav">Back to the log in page</a></div> <?php } ?> This is the fun part. I checked that the id and userkey are correct in the link, and they are. I then replaced the & in the link with & it works in gmail but not yahoo email address. I'm not sure where else to look. Thanks in advance Hi, I need simple function to validate email address format. I have found follwoing function form google. function isemail($email){ return (bool)ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email); } It's working fine with php < 5.2. But when I'm using with PHP 5.3 is says Quote Deprecated: Function ereg() is deprecated in C:\wamp\www\*******\includes\functions.php on line 28 Is any solution to this without error disable? Thanks Hello i have a syntax issue in the code below, can anyone shed some light? Code: [Select] <?php if(isset($_POST['submit'])) { $drop = mysql_real_escape_string($_POST['drop_1']); $tier_two = mysql_real_escape_string($_POST['Subtype']); echo "You selected "; echo $drop." & ".$tier_two; $Name = mysql_real_escape_string($_POST["Name"]); $Phone = mysql_real_escape_string($_POST["Phone"]); $Email = mysql_real_escape_string($_POST["Email"]); $Postcode = mysql_real_escape_string($_POST["Postcode"]); $Website = mysql_real_escape_string($_POST["Website"]); if($Name == '' || $Phone == '' || $Email == '' else if (!preg_match('/^[A-Za-z0-9\-.]+$/', $domain)|| $Postcode == '' || $Website == '') { die('<br> but you did not complete all of the required fields correctly, please try again'); } } the code works fine without the " else if (!preg_match('/^[A-Za-z0-9\-.]+$/', $domain) " . As well as checking for blank fields i'd like to check for the correct email format. Many thanks. |