Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Need some help with simple PHP script!

Featured Replies

I am new to PHP (please be gentle!) and so getting my head around it. I have just created my contact form and the code looks like this

<form action="/sendform.php" method="post">

<p>Your name: <input type="text" name="name"></p>
<p>Your email: <input type="text" name="email"></p>
<p>Your telephone: <input type="text" name="telephone"></p>
<p class="nospam">Leave this empty: <input type="text" name="url"></p>
<p><textarea name="message"></textarea></p>
<p><input type="submit" value="Send"></p>
</form>

I have created a separate sendform.php file and the code within this looks as follows:-

<?php
if(isset($_POST['url']) && $_POST['url'] == ''){

$youremail = 'me@example.com';

$body = "This is the form that was just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";

if( $_POST['email'] && !preg_match( "/[\r\n]/", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}

mail($youremail, 'Contact Form', $body, $headers ); }

header('Location: http://www.example.com/thanks/');
?>


So the first line of code (if I have got this correct) I am tryint to tell the form not to send the form to me, if the url field is filled in [as this is intended as a hidden field]. Further down I added the [!preg_match] to help protect the script from email injection. I have heard this is the correct way to do this?

Is this form okay as it stands? And in terms of validation, is there a simple piece of code I can add somewhere within this script to ensure that the user fills in all the required fields ie Name, Email, Telephone & Message?

Thanks so much for any help and advice on this.. I have been researching for days!

  • Author

Hi Nock, thanks for the response. So the url field is hidden and intended for anti-spam. Basically any bot can fill this in but I don't want the form then emailed to me if this happens. Are you saying that my code for that was wrong and that your code

if(!isset($_POST['url'])){

will ensure that if this field is ever filled in the form won't get sent?

  • Author

Okay nicely explained. So if this particular "hidden" field in not filled out (ie. not set) the stuff in squiggley brackets means "then send the form"?

  • Author

What about adding validation to the php script itself? How would I do that please as this is an area I'm struggling with.

I require the fields name, email, telephone and message to all be required.

  • Author
The easiest thing to do is to watch some of the tutorials on YouTube

I have been teaching myself PHP for the last month and have come up with this script. I'm sure its not perfect but that's the point. I was really hoping for some folk on this forum who actually know more than I about php who can can look at my script and critique or make suggestions giving me indications of whether it needs tweaking. Telling me to watch some videos on youtube is quite unhelpful.

What about adding validation to the php script itself? How would I do that please as this is an area I'm struggling with.

I require the fields name, email, telephone and message to all be required.

For validation, I typically create a class with common methods such as checking if a field is empty, or if a field is a valid email address and so on.

 

Nowadays, I tend not to submit a form the normal way and create a post back, because I find it easier to use JavaScript combined with AJAX. This way, I can submit the form via Ajax and get a response from the server with any incorrect/invalid fields, whilst the user remains on screen and doesn't have to wait for a page refresh etc.

 

I used to submit using a normal POST, retrieve the values, send the user back with the fields appended to be query string where there was an error, and display errors or whatever based on that. This was with my html in one page and the processing happening on a separate php page. There are alternatives like validating on the same screen so html and php is combined. However, I'm not a fan of that now, I like to keep html file as little server side code as possible and do all processing using AJAX, where it is ok to do so.

 

I am on my mobile so apologies for any typos etc.

 

Hope this helps a bit.

To be more helpful on the topic of validation and php here is some example functions i built to help get you started. You can throw these in a simple include file

<?php
/**
 * Checks if a email address is in valid format or not
 * @[member="param"] string $email
 * @[member="param"] string $flags
 * @return bool
 */
if (!function_exists('is_email')) {

    function is_email($email, $flags = "") {
        return (filter_var($email, FILTER_VALIDATE_EMAIL, $flags)) ? true : false;
    }

}
/**
 * Returns true if a valid integer is passed.
 * @[member="param"] int $int
 * @[member="param"] string $flags
 * @return bool
 */
if (!function_exists('is_int')) {

    function is_int($int, $flags = "") {
        return (filter_var($int, FILTER_VALIDATE_INT, $flags)) ? true : false;
    }

}
/**
 * Checks if a IP address is valid or not
 * @[member="param"] string $ip
 * @[member="param"] string $flags
 * @return bool
 */
if (!function_exists('is_ip')) {

    function is_ip($ip, $flags = "") {
        return (filter_var($ip, FILTER_VALIDATE_IP, $flags)) ? true : false;
    }

}
/**
 * Checks to see if a url is valid or not
 * the url must contain http:// for 
 * this check to return true
 * @[member="param"] string $url
 * @[member="param"] string $flags
 * @return bool
 */
if (!function_exists('is_url')) {

    function is_url($url, $flags = "") {
        return (filter_var($url, FILTER_VALIDATE_URL, $flags) && strpos(strtolower($url), "http://") !== false) ? true : false;
    }

}


Then call a function like this

if(is_url("test") === true)
{
//Url is valid
}else{
//Url is not valid
}

Another good method to use when validating data is to store the error messages in an array like such

$error = array();//Error array

if(!isset($_POST['name']))
{
$error[] = "Please enter your name";
}

//SOME ERROR DISPLAYING EXAMPLES
//Get first error in the error array
if(count($error) > 0)
{
echo $error[0];
}
//Loop through entire array
if(count($error) > 0)
{
foreach($error as $errors):
echo $errors."<br />";
endforeach;
}

Edited by webdesigner93

  • Author

@ thanks for the advice and yes this certainly answers my question regarding server-side validation and the filter_var is the route I need to take. Just checking for "blank values" and echoing any errors, is not as helpful to me as actually checking that say, a validly formatted email address has been added into the field as opposed to just "something has been added into that field".

@@NOCK thanks for the advice and yes I am a novice (does it show?!) - but what I was looking for was really some form of explanation of what I had done right and wrong and indeed what could be done or added to improve - so such as webdesigner93 - those were the kind of suggestions I was after.

@@Lyndsey yes personally I have chosen to have all my html on one page (the contact form page) and run the php code separately within a .php page thereby keeping the two separate. I know others prefer to place the php on the same page as html..does it matter or just a personal preference?

Edited by manx

@ is not as helpful to me as actually checking that say, a validly formatted email address

 

I provided a function in my above code called is_email for you to check if the email is a valid one :) But checking for blank values is still part of validation and does need to be covered either way :)

Hi Manx,

 

To validate empty fields.

<?php
// Check the data was posted and the url field was empty.
if($_SERVER['REQUEST_METHOD']=='POST' && trim($_POST['url'])=="") {
   $form_ok = true; // We assum the form is all good to go.
   if(trim($_POST['name'])=="") {
      // the name field is empty.
      $form_ok = false;
   }
   if(trim($_POST['email'])=="") {
      // the email field is empty.
      $form_ok = false;
   } elseif(!filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL)) {
      // it's not empty but it's probably not an email address.
      $form_ok = false;
   }
   if($form_ok) {
      // Execute the send bit.
   }
} else {
   // It wasn't posted / url field was filled in so kick them out - 404 or 403 it's your choice.
}
?>

Hope this helps.

Edited by BrowserBugs

  • 2 weeks later...

Validation is often much more straight forward than it seems.

 

For starters, there are some HTML input types that can help with validation before the form is even posted such as type="email" which will check whether the input follows a valid email structure (basically whether it contains @) and notify the user if it does not. Browser support for these types are limited but unsupported browsers fallback to "text" anyway so every little helps. There's also min and max attributes that are useful for number type inputs.

 

Utilise PHP functions such as trim, preg_match/replace, isset, empty, filter_var and is_int to validate the characters of the form data.

 

Sanitise by stripping tags and escaping quotes.

 

Bind parameters where necessary during database input.

 

If you're unaware of any of these concepts or functions, take some time to look over their official documentation on PHP.net.

 

But personally, I'm not a big fan of Contact Forms anyway.

 

Also, you stated KNOCK's reply wasn't helpful but he provided help before that post and then realised that it would probably be more effective for you to read a good tutorial and study the code they use until you understand why it's being use - it's an effective way to learn rather than teaching yourself insecure or bad practices.

 

How's your contact form coming along anyhow?

 

P.S. Got to the end noticed that the last post is a week ago :|

Edited by Alluziion

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.