Page 1 of 1

Two interfering function

Posted: Sun Jul 04, 2010 4:33 am
by vfm
Hi,

I've had someone write code for me and because I don't have PHP experience I'm struggling to figure it out. I've pasted my code below, one is for the submission of the form, the other is for a newsletter subscription. I've meddled with the code to get the subscription bit working which is part of the standard footer but that seems to have caused the other form to become inoperable. If someone could please help me figure out what the problem is I'd be greatly appreciative.

Code below - thanks in advance:

Code: Select all

<?php
		/****SET THE MAX CHARS FOR EACH MESSAGE***************/
			
			//it is recommended not to set the max too high, to prevent extremely long messages
			// from stalling your server
			
			$EMAIL_MAX = 2500;
			$SMS_MAX = 120;
		
		/*****************************************************/

		//function for stripping whitespace and some chars
		function cleanUp($str_to_clean, $newlines, $spaces){
		
			//build list of whitespace chars to be removed
			$bad_chars = array('\r', '\t', ';');
		
			//if newlines are false, add that to the list of bad chars
			if(!$newlines){array_push($bad_chars, '\n');}
			
			//if spaces are false, strip them too
			if(!$spaces){array_push($bad_chars, ' ');}
			
			$str_to_clean_a = str_replace($bad_chars, '', $str_to_clean);
			$str_to_clean_b = strip_tags($str_to_clean_a);
			return $str_to_clean_b;
		}
		
		//function to check for valid email address pattern
		function checkEmail($email) {
			if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {return false;}
			return true;
		}
		//function to check for valid url pattern
		function checkURL($url) {
			if(!eregi("^http:\/\/", $url)) {return false;}
			return true;
		}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Diagonal | Contact Us</title>

<!-- Stylesheets -->
<link rel="stylesheet" href="style.css" type="text/css" /><!-- Main stylesheet -->

<script type="text/javascript">
v_fields = new Array('sender_name','sender_email','sender_message');alert_on = false;thanks_on = true; thanks_message = "Thank you. Your message has been sent.";	
	function validateForm(){
		
		//alert(v_fields);
		
		//init errors
		var err = "";
		
		//start checking fields
		for(i=0;i<v_fields.length;i++){
			
			//store the field value
			var _thisfield = eval("document.contact."+v_fields[i]+".value");
			
			//check the field value
			if(v_fields[i] == "sender_name"){
				if(!isAlpha(_thisfield)){ err += "Please enter a valid name\n";}
			}else if(v_fields[i] == "sender_subject"){
				if(!isAlpha(_thisfield)){ err += "Please enter a valid subject\n";}
			}else if(v_fields[i] == "sender_email"){
				if(!isEmail(_thisfield)){ err += "Please enter a valid email address\n";}
			}else if(v_fields[i] == "sender_url"){
				if(!isURL(_thisfield)){ err += "Please enter a valid URL\n";}
			}else if(v_fields[i] == "sender_phone"){
				if(!isPhone(_thisfield)){ err += "Please enter a valid phone number\n";}
			}else if(v_fields[i] == "sender_message"){
				if(!isText(_thisfield)){ err += "Please enter a valid message\n";}
			}
			
		}//end for
		
		if(err != ""){ 
			if(alert_on){
				alert("The following errors have occurred\n"+err);
			}else{
				showErrors(err);
			}
			
			return false;
		
		}
		
		return true;
	}
	
	//function to show errors in HTML
	function showErrors(str){
		var err = str.replace(/\n/g,"<br />");
		document.getElementById("form_errors").innerHTML = err;
		document.getElementById("form_errors").style.display = "block";
	
	}
	
	//function to show thank you message in HTML
	function showThanks(str){
		var tym = str.replace(/\n/g,"<br />");
		document.getElementById("form_thanks").innerHTML = tym;
		document.getElementById("form_thanks").style.display = "block";
	
	}
	
	function isEmail(str){
	if(str == "") return false;
	var regex = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return regex.test(str);
	}
	
	function isText(str){
		if(str == "") return false;
		return true;
	}
	
	function isURL(str){
		var regex = /[a-zA-Z0-9\.\/:]+/
		return regex.test(str);
	}
	
	// returns true if the number is formatted in the following ways:
	// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
	function isPhone(str){
		var regex = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
		return regex.test(str);
	}
	
	// returns true if the string contains A-Z, a-z or 0-9 or . or # only
	function isAddress(str){
		var regex = /[^a-zA-Z0-9\#\.]/g
		if (regex.test(str)) return true;
		return false;
	}
	
	// returns true if the string is 5 digits
	function isZip(str){
		var regex = /\d{5,}/;
		if(regex.test(str)) return true;
		return false;
	}
	
	// returns true if the string contains A-Z or a-z only
	function isAlpha(str){
		var regex = /[a-zA-Z]/g
		if (regex.test(str)) return true;
		return false;
	}
	
	// returns true if the string contains A-Z or a-z or 0-9 only
	function isAlphaNumeric(str){
		var regex = /[^a-zA-Z0-9]/g
		if (regex.test(str)) return false;
		return true;
	}

</script>

<script type="text/javascript">
v_fields2 = new Array('news_email');alert_on = false;thanks_on = true; thanks_message = "Thank you. You are now subscribed.";	
	function validateForm2(){
		
		//alert(v_fields);
		
		//init errors
		var err = "";
		
		//start checking fields
		for(i=0;i<v_fields2.length;i++){
			
			//store the field value
			var _thisfield = eval("document.contact."+v_fields2[i]+".value");
			
			//check the field value
			if(v_fields2[i] == "news_email"){
				if(!isEmail(_thisfield)){ err += "Please enter a valid email address for subscription\n";}
			}
			
		}//end for
		
		if(err != ""){ 
			if(alert_on){
				alert("The following errors have occurred\n"+err);
			}else{
				showErrors(err);
			}
			
			return false;
		
		}
		
		return true;
	}
	
	//function to show errors in HTML
	function showErrors(str){
		var err = str.replace(/\n/g,"<br />");
		document.getElementById("form_errors").innerHTML = err;
		document.getElementById("form_errors").style.display = "block";
	
	}
	
	//function to show thank you message in HTML
	function showThanks(str){
		var tym = str.replace(/\n/g,"<br />");
		document.getElementById("form_thanks").innerHTML = tym;
		document.getElementById("form_thanks").style.display = "block";
	
	}
	
	function isEmail(str){
	if(str == "") return false;
	var regex = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return regex.test(str);
	}

</script>

	<?php
	if(isset($_POST["submitForm"])){

		$_name = cleanUp($_POST["sender_name"], false, true);

		$_email = cleanUp($_POST["sender_email"], false, false);

		$_message = cleanUp($_POST["sender_message"], true, true);

		$_url = cleanUp($_POST["sender_url"], false, false);

		
		$_body = "You have been sent this message from your contact form\n\n";
		
		if($_name){
			$_body .= "NAME: $_name\n\n";
		}
		
		if($_email){
			$_body .= "EMAIL: $_email\n\n";
		}
		
		if($_url){
			$_body .= "URL: $_url\n\n";
		}
		
		if($_phone){
			$_body .= "PHONE: $_phone\n\n";
		}
		
		if($_message){
		
			//check length of body, reduce to max chars
			if(strlen($_message) > $EMAIL_MAX){$_message= substr($_message, 0, $EMAIL_MAX);}else{$_message = $_message;}
			if(strlen($_message) > $SMS_MAX){$_message2 = substr($_message, 0, $SMS_MAX);}else{$_message2 = $_message;}
		}
		
		

		//store the recipient(s)
		$_to = array();

		//now get the recipient(s)
		$_to[] = "info@viewforme.com";
		
		//define the subject
		if(!$_subject){$_subject = "E-Mail from your contact form";}

		
		if(!$_name){$_name = "CONTACT FORM";}
		if(!$_email){$_email = $_name;}
		
		//set the headers
		$_header = "From: $_name < $_email >" . "\r\n" .
    "Reply-To: ".$_email."\r\n" .
    "Super-Simple-Mailer: supersimple.org";
		
		//we can send up to 2 emails (EMAIL and/or SMS)
		if(count($_to) > 2){ $_to = array_slice($_to,0,2);}
		
		for($i=0;$i<count($_to);$i++){
			
			//get the correct message, based on where it is delivering to
			if(strstr($_to[$i],"teleflip.com")){$_text = $_body.$_message2;}else{$_text = $_body.$_message;}
			
			//send the email(s)
			mail($_to[$i], $_subject, $_text, $_header);
			
		}
		
		echo "<script type=\"text/javascript\">window.onload = function(){showThanks(thanks_message);}</script>";
	}
	?>

<?php
	if(isset($_POST["submitNewsletter"])){

		$_email2 = cleanUp($_POST["news_email"], false, false);

		
		$_body = "You have been sent the following newsletter subscription\n\n";
		
				
		if($_email2){
			$_body .= "EMAIL: $_email2\n\n";
		}
		
		if($_message){
		
			//check length of body, reduce to max chars
			if(strlen($_message) > $EMAIL_MAX){$_message= substr($_message, 0, $EMAIL_MAX);}else{$_message = $_message;}
			if(strlen($_message) > $SMS_MAX){$_message2 = substr($_message, 0, $SMS_MAX);}else{$_message2 = $_message;}
		}
		
		

		//store the recipient(s)
		$_to = array();

		//now get the recipient(s)
		$_to[] = "info@viewforme.com";
		
		//define the subject
		if(!$_subject){$_subject = "Email subscription";}

		
		if(!$_name){$_name = "CONTACT FORM";}
		if(!$_email2){$_email2 = $_name;}
		
		//set the headers
		$_header = "From: $_name < $_email2 >" . "\r\n" .
    "Reply-To: ".$_email2."\r\n" .
    "Super-Simple-Mailer: supersimple.org";
		
		//we can send up to 2 emails (EMAIL and/or SMS)
		if(count($_to) > 2){ $_to = array_slice($_to,0,2);}
		
		for($i=0;$i<count($_to);$i++){
			
			//get the correct message, based on where it is delivering to
			if(strstr($_to[$i],"teleflip.com")){$_text = $_body.$_message2;}else{$_text = $_body.$_message;}
			
			//send the email(s)
			mail($_to[$i], $_subject, $_text, $_header);
			
		}
		
		echo "<script type=\"text/javascript\">window.onload = function(){showThanks(thanks_message);}</script>";
	}
	?>

</head>

<body>

	<div id="container">
		<div id="header">
        	<a href="#"><img src="images/logo.png" alt="Diagonal Logo" height="35" width="215" class="logo" /></a>
            	<ul id="nav">
                	<li><a href="index.html">HOME</a></li>
                    <li><a href="about.html">ABOUT</a>
                    	<ul>
                    		<li><a href="fullwidth.html">Full Width</a></li>
                            <li><a href="columns.html">Columns</a></li>
                            <li><a href="#">Dropdown lvl 1</a></li>    
                        </ul>
                    </li>
                    <li><a href="portfolio.html">PORTFOLIO</a>
                    	<ul>
                    		<li><a href="#">Web</a></li>
                            <li><a href="#">Prints</a></li>
                            <li><a href="#">Dropdown Menu</a></li>    
                        </ul>
                  </li>
                    <li class="active"><a href="contact.php">GET IN TOUCH</a></li>
                    <li><a href="blog.html">OUR BLOG</a></li>
                </ul>
                
                <br class="cl" />
                
                <div id="featured">
                    <div class="tagline"><h1>Get In Touch With Us</h1></div><!-- End tagline -->
                    <br class="cl" />
                </div><!-- End featured -->
        
        </div><!-- End header -->    

        <div id="content_top">&nbsp;</div><!-- End content_top -->
        
        <div id="content_mid">
        	<div id="main">
            	<img src="images/map.jpg" alt="Locate Us" /><br /><br />
                
                <div id="contact">
                	<fieldset>
                		<form name="contact" action="<?=$_SERVER['PHP_SELF']?>" method="post" onsubmit="return validateForm();">
                        	<p id="form_errors"></p>
							<p id="form_thanks"></p>
                                <input type="text" value="Your Name" name="sender_name" />
                                <input type="text" value="Your Email" name="sender_email" />
                                <input type="text" value="Your Website" name="sender_url" />
                                <textarea rows="12" cols="65" name="sender_message">Your Message</textarea>
                                <input type="submit" class="button" name="submitForm"></input>
                    	</form>
                    </fieldset>
                </div><!-- End contact -->
            </div><!-- End main -->
            
            <div id="sidebar">
            	<a href="#"><img src="images/get_started_btn.jpg" alt="get started" class="start_btn" /></a>
                
                <div class="blog_updates">
                	<h2>Latest Blog News</h2>
                    	<ul>
                        	<li>
                            	<h6><a href="#">New Design Site</a></h6>
                                	<p>Posted under <a href="#">News</a> on 01/29/2010</p>
                            </li>
                            <li>
                            	<h6><a href="#">Awesome Portfolios of 2009</a></h6>
                                	<p>Posted under <a href="#">Design</a> on 01/27/2010</p>
                            </li>
                            <li>
                            	<h6><a href="#">What to expect in 2010</a></h6>
                                	<p>Posted under <a href="#">News</a> on 12/29/2009</p>
                            </li>
                        </ul>
                </div><!-- End blog_updates -->
                
                <div class="testimonials">
                	<h4>Client Testimonials</h4>
                    	<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sed nulla quis eros sodales malesuada 
nec at lectus.” - <i>John Doe</i>
						</p>
                </div><!-- End testimonials -->
            </div><!-- End sidebar -->
            
            <br class="cl" />
        </div><!-- End content_mid -->
        
        <div id="content_btm">&nbsp;</div><!-- End content_btm -->
        
        <div id="footer">
        	<div class="links">
            	<h6>General Links</h6>
                	<ul>
                    	<li><a href="#">HOME</a></li>
                        <li><a href="#">ABOUT</a></li>
                        <li><a href="#">PORTFOLIO</a></li>
                        <li><a href="#">GET IN TOUCH</a></li>
                        <li><a href="#">OUR BLOG</a></li>
                    </ul>
            </div><!-- End links -->
            
            <div class="services">
            	<h6>Our Services</h6>
                	<ul>
                    	<li>Web Design</li>
                        <li>Print Design</li>
                        <li>Custom Logo/Banners</li>
                        <li>Visual Effects</li>
                        <li>2D/3D Animations</li>
                    </ul>
            </div><!-- End services -->
            
            <div class="social">
            	<h6>General Links</h6>
                	<ul>
                    	<li><img src="images/social_icons/twitter.jpg" alt="twitter" /> <a href="#">Twitter</a></li>
                        <li><img src="images/social_icons/facebook.jpg" alt="facebook" /> <a href="#">Facebook</a></li>
                        <li><img src="images/social_icons/flickr.jpg" alt="flickr" /> <a href="#">Flickr</a></li>
                        <li><img src="images/social_icons/linkedin.jpg" alt="linked in" /> <a href="#">Linked In</a></li>
                        <li><img src="images/social_icons/rss.jpg" alt="rss" /> <a href="#">RSS Feed</a></li>
                    </ul>
            </div><!-- End social -->
            
            <div class="newsletter">
            	<h6>Subscribe to our Newsletter</h6>
                	<form method="post" action="<?=$_SERVER['PHP_SELF']?>" id="newsletter" onsubmit="return validateForm2();">
                    	<fieldset>
                    		<input type="text" value="Enter E-mail here..." name="news_email" />
							<button type="submit" name="submitNewsletter"><img src="images/home_send_btn.jpg" alt="send" /></button>
                        </fieldset>
                    </form>
                    <p>Copyright 2010 DIAGONAL.<br/> All Rights Reserved. <br/>Template by Kevinsturf (Remove this)</p>
            </div><!-- End newsletter -->
            <br class="cl" />
        </div><!-- End footer -->
        <div id="footer_btm">&nbsp;</div>
        
    </div><!-- End container -->

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-10435976-4");
pageTracker._trackPageview();
} catch(err) {}</script>

<!-- Javascript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js" ></script>
<script type="text/javascript" src="js/cufon.js" ></script>
<script type="text/javascript" src="js/nevis.font.js" ></script>
<script type="text/javascript" src="js/jquery.cycle.min.js" ></script>

</body>
</html>

Re: Two interfering function

Posted: Mon Jul 05, 2010 4:22 am
by cpetercarter
You don't say what happens when you try to submit the form (nothing? blank page? error message?) so finding what is wrong in your code is a bit of a guess. However, I can see two things which might be the cause of your problem.

The two functions for checking that a user has entered an email address and a url, respectively, use the php eregi() function. This function has been deprecated in the latest versions of php. You need to use a regular expression and the preg_match() function instead eg:

Code: Select all

if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) return false;
In several places the code uses short tags eg

Code: Select all

<?=$_SERVER['PHP_SELF']?>
This will only work if you have short tags enabled in your php_ini file. Normally it is best to use long tags instead

Code: Select all

<?php echo $_SERVER['PHP_SELF'] ?>

Re: Two interfering function

Posted: Fri Jul 09, 2010 12:17 am
by vfm
Thanks for the response.

What actually happens is that when you submit the email subscription form it doesnt actually invoke the function that checks whether it is a valid email address or not. For example, I can enter 'asd' and it submits it.

Re: Two interfering function

Posted: Fri Jul 09, 2010 1:45 am
by cpetercarter
Your script contains two quite separate ways of checking the e-mail address.

First, there is a JavaScript function validateForm() which is called when the user clicks the "Submit" button in your form. It should display a message "Please enter a valid email address" if the user tries to submit to form with something which does not pass a regex test for an email address. I assume that this isn't happening. I can't immediately spot anything wrong with the Javascript. You do have Javascript enabled in your browser, don't you?

Second, your script defines a php function checkEmail(). But this has no effect because, as far as I can see, you haven't called it anywhere. Similarly, you haven't called the checkUrl() function.

PS I have just run your script on my local machine. The Javascript seems to be working OK; it refuses to submit the form with an invalid e-mail address.

PPS OK, I think I have found it. There is indeed an error in the Javascript. The JS function which is supposed to check your "subscribe" form is actually looking at your "contact" form. Two changes will sort it:

First, find function validateForm2(). A few lines down change this

Code: Select all

var _thisfield = eval("document.contact."+v_fields2[i]+".value");
to this

Code: Select all

var _thisfield = eval("document.subscribe."+v_fields2[i]+".value");
Then, towards the end of the script, find the bit which puts your "subscribe" form on the page. Change this

Code: Select all

<form method="post" action="<?=$_SERVER['PHP_SELF']?>" id="newsletter" onsubmit="return validateForm2();">
to this

Code: Select all

<form method="post" name="subscribe" action="<?=$_SERVER['PHP_SELF']?>" id="newsletter" onsubmit="return validateForm2();">

Re: Two interfering function

Posted: Wed Jul 21, 2010 12:33 am
by vfm
Awesome! Thank you so much - it's all working fine now!