Send mail php and ajax component not sending inputs from contact form

Hi,

Im having some issues with my contact form, I’ve done a website a local charity but I’m having trouble getting the inputs to pass through my email-validator.php and send the email.

The whole process makes up four files.

index.html
ajaxmail.js
sendmail.php
email-validator.php

If you visit www.crichtonoutreachservices.co.uk and at the bottom click on the “fill in the form” button, a contact form appears. When I send an input I get an error

parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /home/crichton/public_html/email-validator.php on line 27

The code for the form is as follows

<form id="newsletter" action="http://www.crichtonoutreachservices.co.uk/sendmail.php" method="post">
								
<label for="name_1">Name:</label>	
<input id="name" class="text" type="text" name="name"/>
									
<label for="email_2">Email</label>
<input id="email" class="text" type="text" name="email"/>
									
<label for="tel_3">Tel:</label>
<input id="telephone" class="text" type="text" name="telephone"/>
									
<input type="submit"  value="SEND" class="submit"/>
										
<a class="close" title="Close" href="#"><span>Close</span></a>
									
	<p class='hide' id='response'></p>
				
		<div class='hide'>
								
<label for='spamCheck'>Do not fill out this field</label>
<input name='spam_check' type='text' value='' />
									
</div><!-- End of hide div -->
									
</form>	

it calls the sendmail.php file which is



<?php
//Catch any errors while testing our script
//Remove when going live.
ini_set("display_errors", "1");
error_reporting(E_ALL); 

//Ensures no one loads page and does simple spam check.
if(isset($_POST['name']) && empty($_POST['spam_check']))
{
	//Include our email validator for later use 
	require 'email-validator.php';
	$validator = new EmailAddressValidator();
	
	//Declare our $errors variable we will be using later to store any errors.
	$errors = array();
	
	//Setup our basic variables
	$input_name = strip_tags($_POST['name']);
	$input_email = strip_tags($_POST['email']);
	$input_telephone = strip_tags($_POST['telephone']);
		
	
	//We'll check and see if any of the required fields are empty.
	//We use an array to store the required fields.
	$required = array('Name field' => 'name', 'Email field' => 'email');
	
	//Loops through each required $_POST value 
	//Checks to ensure it is not empty.
	foreach($required as $key=>$value)
	{
		if(isset($_POST[$value]) && $_POST[$value] !== '') 
		{
			continue;
		}
		else {
			$errors[] = $key . ' cannot be left blank';
		}
	}
	
	//Make sure the email is valid. 
    if (!$validator->check_email_address($input_email)) {
           $errors[] = 'Email address is invalid.';
    }
	
	//Now check to see if there are any errors 
	if(empty($errors))
	{
		
		//No errors, send mail using conditional to ensure it was sent.
		if(mail('owain.llew@gmail.com', "Message from: $input_name", "Email: $input_email", "Their telephone number is: $input_telephone"))
		{
			echo 'Your email has been sent.';
		}
		else 
		{
			echo 'There was a problem sending your email.';
		}
		
	}
	else 
	{
		
		//Errors were found, output all errors to the user.
		echo implode('<br />', $errors);
		
	}
}
else
{
	die('Direct access to this page is not allowed.');
}

and runs the ajax file whic is



$(function(){
	
	//Do what we need to when form is submitted.	
	$('.submit').click(function(){
	
	//Setup any needed variables.
	var input_name = $('#name').val(),
		input_email = $('#email').val(),
		input_telephone = $('#telephone').val(),
		response_text = $('#response');
		//Hide any previous response text 
		response_text.hide();
		
		//Change response text to 'loading...'
		response_text.html('Loading...').show();
		
		//Make AJAX request 
		$.post('http://www.crichtonoutreachservices.co.uk/sendmail.php', {name: input_name, email: input_email, telephone: input_telephone}, function(data){
			response_text.html(data);
		});
		
		//Cancel default action
		return false;
	});

});



The email validator.php is

&lt;?php

    /*

        EmailAddressValidator Class
        http://code.google.com/p/php-email-address-validation/

        Released under New BSD license
        http://www.opensource.org/licenses/bsd-license.php
        
        Sample Code
        ----------------
        $validator = new EmailAddressValidator;
        if ($validator-&gt;check_email_address('test@example.org')) {
            // Email address is technically valid
        }

    */

    class EmailAddressValidator {

        /**
         * Check email address validity
         * @param   strEmailAddress     Email address to be checked
         * @return  True if email is valid, false if not
         */
        public function check_email_address($strEmailAddress) {
            
            // If magic quotes is "on", email addresses with quote marks will
            // fail validation because of added escape characters. Uncommenting
            // the next three lines will allow for this issue.
            //if (get_magic_quotes_gpc()) { 
            //    $strEmailAddress = stripslashes($strEmailAddress); 
            //}

            // Control characters are not allowed
            if (preg_match('/[\\x00-\\x1F\\x7F-\\xFF]/', $strEmailAddress)) {
                return false;
            }

            // Check email length - min 3 (a@a), max 256
            if (!$this-&gt;check_text_length($strEmailAddress, 3, 256)) {
                return false;
            }

            // Split it into sections using last instance of "@"
            $intAtSymbol = strrpos($strEmailAddress, '@');
            if ($intAtSymbol === false) {
                // No "@" symbol in email.
                return false;
            }
            $arrEmailAddress[0] = substr($strEmailAddress, 0, $intAtSymbol);
            $arrEmailAddress[1] = substr($strEmailAddress, $intAtSymbol + 1);

            // Count the "@" symbols. Only one is allowed, except where 
            // contained in quote marks in the local part. Quickest way to
            // check this is to remove anything in quotes. We also remove
            // characters escaped with backslash, and the backslash
            // character.
            $arrTempAddress[0] = preg_replace('/\\./'
                                             ,''
                                             ,$arrEmailAddress[0]);
            $arrTempAddress[0] = preg_replace('/"[^"]+"/'
                                             ,''
                                             ,$arrTempAddress[0]);
            $arrTempAddress[1] = $arrEmailAddress[1];
            $strTempAddress = $arrTempAddress[0] . $arrTempAddress[1];
            // Then check - should be no "@" symbols.
            if (strrpos($strTempAddress, '@') !== false) {
                // "@" symbol found
                return false;
            }

            // Check local portion
            if (!$this-&gt;check_local_portion($arrEmailAddress[0])) {
                return false;
            }

            // Check domain portion
            if (!$this-&gt;check_domain_portion($arrEmailAddress[1])) {
                return false;
            }

            // If we're still here, all checks above passed. Email is valid.
            return true;

        }

        /**
         * Checks email section before "@" symbol for validity
         * @param   strLocalPortion     Text to be checked
         * @return  True if local portion is valid, false if not
         */
        protected function check_local_portion($strLocalPortion) {
            // Local portion can only be from 1 to 64 characters, inclusive.
            // Please note that servers are encouraged to accept longer local
            // parts than 64 characters.
            if (!$this-&gt;check_text_length($strLocalPortion, 1, 64)) {
                return false;
            }
            // Local portion must be:
            // 1) a dot-atom (strings separated by periods)
            // 2) a quoted string
            // 3) an obsolete format string (combination of the above)
            $arrLocalPortion = explode('.', $strLocalPortion);
            for ($i = 0, $max = sizeof($arrLocalPortion); $i &lt; $max; $i++) {
                 if (!preg_match('.^('
                                .    '([A-Za-z0-9!#$%&\\'*+/=?^_`{|}~-]' 
                                .    '[A-Za-z0-9!#$%&\\'*+/=?^_`{|}~-]{0,63})'
                                .'|'
                                .    '("[^\\\\\\"]{0,62}")'
                                .')$.'
                                ,$arrLocalPortion[$i])) {
                    return false;
                }
            }
            return true;
        }

        /**
         * Checks email section after "@" symbol for validity
         * @param   strDomainPortion     Text to be checked
         * @return  True if domain portion is valid, false if not
         */
        protected function check_domain_portion($strDomainPortion) {
            // Total domain can only be from 1 to 255 characters, inclusive
            if (!$this-&gt;check_text_length($strDomainPortion, 1, 255)) {
                return false;
            }
            // Check if domain is IP, possibly enclosed in square brackets.
            if (preg_match('/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
               .'(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}$/'
               ,$strDomainPortion) || 
                preg_match('/^\\[(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
               .'(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\\]$/'
               ,$strDomainPortion)) {
                return true;
            } else {
                $arrDomainPortion = explode('.', $strDomainPortion);
                if (sizeof($arrDomainPortion) &lt; 2) {
                    return false; // Not enough parts to domain
                }
                for ($i = 0, $max = sizeof($arrDomainPortion); $i &lt; $max; $i++) {
                    // Each portion must be between 1 and 63 characters, inclusive
                    if (!$this-&gt;check_text_length($arrDomainPortion[$i], 1, 63)) {
                        return false;
                    }
                    if (!preg_match('/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|'
                       .'([A-Za-z0-9]+))$/', $arrDomainPortion[$i])) {
                        return false;
                    }
                    if ($i == $max - 1) { // TLD cannot be only numbers
                        if (strlen(preg_replace('/[0-9]/', '', $arrDomainPortion[$i])) &lt;= 0) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        /**
         * Check given text length is between defined bounds
         * @param   strText     Text to be checked
         * @param   intMinimum  Minimum acceptable length
         * @param   intMaximum  Maximum acceptable length
         * @return  True if string is within bounds (inclusive), false if not
         */
        protected function check_text_length($strText, $intMinimum, $intMaximum) {
            // Minimum and maximum are both inclusive
            $intTextLength = strlen($strText);
            if (($intTextLength &lt; $intMinimum) || ($intTextLength &gt; $intMaximum)) {
                return false;
            } else {
                return true;
            }
        }

    }

?&gt;

Sorry for all the code,

If anyone can help that would be great

:slight_smile:

You need to post the content of sendmail.php & email-validator.php. :wink:

I checked firebug and I can see it’s passing in the correct values from the inputs into sendmail.php, So i know thats all correct,

are you saying im not passing the values out the other side?

Sorry I’m very much a php novice, so my knowledge is a bit patchy.

I assumed that the line

if(mail('owain.llew@gmail.com', "Message from: $input_name", "Email: $input_email", "Their telephone number is: $input_telephone"))

mailed out the inputs to that email address.

Can you explain to me what the error I’m getting means?

i found a definition:

What Causes This PHP Error To Occur?
A parse error occurs whenever a PHP compiler is attempting to translate your code, this is also referred to in programming terms as a “runtime error”

It is often easily fixable, as the problem is often simple. The problem stems form the syntax of your code.

This may be because you forgot to add a semi-colon on the end of one of your lines of code “;” this is usually the most frequent problem especially when you first start learning PHP as its easy to forget that each line code needs to finish with this character and to the untrained eye its hard to spot when glancing at the code.

The second and third most common mistake with the syntax is when you forget to include the double quote (") or an end bracket (}) after you have created one. This can mean that the error will not be on the line of code where the error should be, but might be at the end of your program.

The error message says the problem is on this line.


public function check_email_address($strEmailAddress) {

you’re not running PHP4 perchance? You can’t use declarations such as public on there.

it’s running version 4.3.10

do I need version 5 for this to work?

If you stay with PHP4 you’ll have to get rid of public/private/protected

Or, you can upgrade to PHP 5.

O.k thanks very much…

will look into this…

I decided to move my files to a media temple grid service package… now when I send the input from the form it just says loading… but stays without sending anything…

any ideas why?

u can view this by going to www.crichtonoutreachservices.co.uk

Im getting this error now when trying to send the information…

Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /nfs/c06/h02/mnt/88828/domains/crichtonoutreachservices.co.uk/html/email-validator.php on line 27

any ideas?

the code for that line is

  public function check_email_address($strEmailAddress) {

cough ^------ :stuck_out_tongue:

From the Media Temple FAQ

Inside your WebControl Panel panel you can toggle PHP 4/5 support on a per site basis

What version of PHP does phpinfo() show for you?

hahah Sorry guys…

I set up media temple hosting assumed they would have php 5 setup as default.

I found that like you mentioned the settings were pointing to php 4… I’ve toggled that and it now works…

Thanks for your patience…

Cheers

:slight_smile: