How to skip php error and render rest of html

Hi Sitepointers

I made a contact page with a form and the issue is that if I send the email and the error is caused by PHPmailer than the rest of the page does not render But if it is a validation error than the entire page renders as it should.

Unfortunately I am running on localhost so I understand that there will be connection errors when sending but how would I be able to make the page continue to render after the error has been found?

html that includes the php files : include_once('validate.php');

than the php file that is included I am aware there will be an error connection:

<?php
		 $name = $srn = $email = $txt = "";
		 $border1 = $border2 = $border3 = $border4 = "";
		 $errornum1 = $errornum2 = $errornum3 = $errornum4 = 0;
		 
		 $errorname = $errorsrn = $errormail =  $errortxt =  $secondcap = "";
		 
		  function test_input($data) {
			  $data = trim($data);
			  $data = stripslashes($data);
			  $data = htmlspecialchars($data);
			  $data = preg_replace('/\s+/',' ', $data);
			  return $data;
		}
		 
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			 
		if($_POST['hidden'] !== ""){
				$secondcap ='<span style="text-align:center;background-color:RGBA(255, 255, 255, 0.7);position:absolute;left:0px;width:100%;color:#f00;font-size:1.2em;">There Appears to be an issue, Please try again</span>';

		}else{
				$secondcap = "";
			
			if($_POST['name'] == ""){
				$errorname = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Name Field is Empty</span>';
				$name = "";
				$border1 = 'style="border:#f00 solid 1px;"';
				$errornum1 = 1;
			}else{
				if(!preg_match("/^[a-zA-Z ]*$/",$_POST['name'])){
					$errorname = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Name Field contains invalid characters</span>';
					$name = "";
					$border1 = 'style="border:#f00 solid 1px;"';
					$errornum1 = 1;
				}else{
					$errorname = "";
					$name = test_input($_POST['name']);
					$border1 = 'style="border:#2f2 solid 1px;"';
					$errornum1 = 0;
				}
			}
			
			if($_POST['srn'] == ""){
				$errorsrn = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Surname Field is Empty</span>';
				$srn = "";
				$border2 = 'style="border:#f00 solid 1px;"';
				$errornum2 = 1;
			}else{
				
				if(!preg_match("/^[a-zA-Z ]*$/",$_POST['srn'])){
					$errorsrn = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Surname Field contains invalid characters</span>';
					$srn = "";
					$border2 = 'style="border:#f00 solid 1px;"';
					$errornum2 = 1;
				}else{
					$errorsrn = "";
					$srn = test_input($_POST['srn']);
					$border2 = 'style="border:#2f2 solid 1px;"';
					$errornum2 = 0;
				}
			}
			
			if($_POST['email'] == ""){
				$errormail = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Email Field is Empty</span>';
				$email = "";
				$border3 = 'style="border:#f00 solid 1px;"';
				$errornum3 = 1;
			}else{
				if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
					$errormail = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Email Field Requires an "@Service" and ".Web" E.G thisemail@gmail.com</span>';
					$email = "";
					$border3 = 'style="border:#f00 solid 1px;"';
					$errornum3 = 1;
				}else{
					$errormail = "";
					$email= test_input($_POST['email']);
					$border3 = 'style="border:#2f2 solid 1px;"';
					$errornum3 = 0;
				}
			}
			
			if($_POST['text'] == ""){
				$errortxt = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Message is Empty</span>';
				$txt= test_input($_POST['text']);
				$border4 = 'style="border:#f00 solid 1px;"';
				$errornum4 = 1;
			}else{
				if(!preg_match("/^[a-zA-Z ]*$/",$_POST['text'])){
					$errortxt = '<span style="color:#f00;font-weight:bold;font-size:0.9em;padding:0px 10px;">*Message field Contains Invalid characters</span>';
					$txt= "";
					$border4 = 'style="border:#f00 solid 1px;"';
					$errornum4 = 1;
				}else{
					$errortxt = "";
					$txt= test_input($_POST['text']);
					$border4 = 'style="border:#2f2 solid 1px;"';
					$errornum4 = 0;
				}
			}
			
			if($errornum1 + $errornum2 + $errornum3 + $errornum4 == 0){
				require("../PHPMailer-5.2-stable/PHPMailerAutoload.php");
				require '../PHPMailer-5.2-stable/class.phpmailer.php';

				$mail = new PHPMailer();

				// set mailer to use SMTP
				$mail->IsSMTP();
				$mail->SMTPDebug = 0;

				// As this email.php script lives on the same server as our email server
				// we are setting the HOST to localhost
				$mail->Host = "smtp.gmail.com";  // specify main and backup server

				$mail->SMTPAuth = true;     // turn on SMTP authentication
				$mail->SMTPSecure = "tls";
				$mail->Port = 465;
				$mail->Username = "****";  // SMTP username
				$mail->Password = "***"; // SMTP password

				// $email is the user's email address the specified
				// on our contact us page. We set this variable at
				// the top of this page with:
				// $email = $_REQUEST['email'] ;
				$mail->From = $email;

				// below we want to set the email address we will be sending our email to.
				$mail->AddAddress("****", "****");

				// set word wrap to 50 characters
				$mail->WordWrap = 50;
				// set email format to HTML
				$mail->IsHTML(true);

				$mail->Subject = "You have received feedback from your website!";
				$mail->Body    = $txt;
				$mail->AltBody = $txt;

				if(!$mail->Send()){
					$secondcap = '<h3 style="color:#f00;text-align:center;">There Was an error sending your email please try again</h3>';
					return;
				}else{
					$secondcap = '<h3 style="color:#0f0">Your Email has been sent</h3>';
					return;
				}
			}
		}
	}
		
?>

<htmL>
	<form method="post" action="contact.php#head" autocomplete="off">
			
		<h2>Form</h2> 
		
		<?php echo $secondcap; ?>
		
		<div class="form">
			<label>Name<?php echo $errorname; ?></label><input type="text" <?php echo $border1; ?> name="name" value="<?php echo $name ?>"><br>
			<label>Surname <?php echo $errorsrn; ?></label><input type="text" <?php echo $border2; ?> name="srn" value="<?php echo $srn ?>"> <br>
			<label>Email <?php echo $errormail; ?></label><input type="email" <?php echo $border3; ?> name="email" value="<?php echo $email ?>"><br>
			<label style="display:none;">Hidden</label><input type="text" name="hidden" style="display:none">
		</div>
				 
		<div class="form line">
			<label>Message <?php echo $errortxt; ?></label><textarea name="text" <?php echo $border4; ?> ><?php echo $txt ?></textarea>
		</div>


		<div class="form">
			<!--	<h3>Please, complete puzzle to submit</h3> -->
			<input type="submit" name="submit" value="Send">
		</div>
	</form>
</html>

the rest of the page that isn’t loading after the php is found in the html page:

<div id="map">
	<script>
      function initMap() {
        var uluru = {lat: -26.209248, lng: 28.254368};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 17,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
	</div>
 
	<footer>
		<p>Join us on social media:</p>
		
		<a href="https://www.facebook.com/****" target="_blank" class="fa fa-facebook">&nbsp;&nbsp;Facebook</a>
		<a href="https://twitter.com/****" target="_blank" class="fa fa-twitter">&nbsp;&nbsp;Twitter</a>
		
	</footer>

Bonus question how can I add the email and password Securely without it being visibile in the document? any help would be appreciated and regarding this form will it generally work when I make it live or is there still things I need to input?

The problem, I think, is here:

  if(!$mail->Send()){
    $secondcap = '<h3 style="color:#f00;text-align:center;">There Was an error sending your email please try again</h3>';
    return;     // ******* HERE
  }else{
    $secondcap = '<h3 style="color:#0f0">Your Email has been sent</h3>';
    return;     // ******* HERE

When you execute return from the global scope, it ends the script. So really, whatever the outcome of your test in the code above, it should stop. That might be what you want, though I can’t imagine it would be a good thing in production code, but maybe commenting those two lines out would allow you to test.

I don’t see those anywhere in the html.
The php parts won’t be visible on the client side.
But to be on the safe side, in case of php not parsing for some reason you can store confidential info in an include stored below the public root.
Something like:-

<?php
$mailpass = 'myMailPassword';
$mailuser = 'MyUserName';
$mailaddress = 'me@example.com';

Save that someplace safe, then include it in the main script.

require '../private/includes/myMail.php' ;

Then if for any reason the user did see your php source code, all they would see is the line above, not the values of the variables you set in the private include file.

Hi Droopsnoot

I tried what you said and I do agree the issues is with the send results ,If i try passing the validation and it fails than the webpage returns with the error messages displayed where they should be which is correct but when validation passes successfully than the page up to about 10 - 15 minutes to load and checking the debug mode I get connection timed out so I believe gmail is refusing my request by not responding and I am aware about that since this is localhost but what I want to do is if it becomes normal on a server and responds as expected than what if that time out ever occurs due to lost connection.

In this case scenario the users won’t be able to continue navigating the page as most of it doesn’t render thats the issues I am trying to sort out :smiley: But you are right there is something wrong with that if function because taking it out seems to work but obviously wont send the message.

Hi SamA74

So how do I call a file outside of the root folder because …/ usually only calls from within the root folder which in this case is htdocs but if I was on the server where would outside the root file be?

I understand files can’t be accessed outside the root directory so it’s more secure than most other ideas and I have looked up how to access files outside the directory before but I couldn’t get it to work?

That path assumes you are in a file in the root folder, so ../ takes you below the root.
You may want to set a path as a constant if you are using a lot of includes and don’t want the hassle of thinking about relative paths, if for example your files are in different folders.

define('INCPATH', $_SERVER['DOCUMENT_ROOT'].'/../private/includes/') ;

If you are storing includes above the root, you can use htaccess to block a folder.

No, what I meant is that the reason the script stops executing is that you have a return statement in there, which is effectively the same as exit().

Hi SamA74

So if I created a file called Private outside of htdocs and place it there how would I use that relative paths because I am using relative paths for all my files the only thing is if I use ../Filename/FileExtension.txt than it would translate as htdocs/FIlename/FileExtension.txt therefore only selecting a file within htdocs which is the root file for my files

so how would I be able to save a file outside of root and access it there? does ../ actually select passed the root directory because I use it to select a file that is up the access tree for instance a file for html and a file for css Both files inside another website name file so when accessing the html files using the css I would go ../WebsiteFilename/Html/file.html and all this would be within the root file.

This is just an example normally that would apply to my background-images found in Images not Html file

Hi droopsnoot

I tried to comment the return out and the issues is the same everything from the form,map and footer is gone and if I switch on the debug option it would just say connection timed out as if Gmail is ignoring my request.

Sorry If i take too long to respond the request will sit for like 10 -15minute before it gives me connection timed out due to secruity issues while using localhost.

the reason I am asking is because if for some reason if it was caused on the server because of slow internet connection and stuff than it could possibly do the same and I want to avoid that.

I was also wondering if I was to make the form live would it still give me the security issue? is there a way to make it secure through localhost or to even send through localhost for debugging purposes?

It’s a relative path, so it really depends upon where you call it from.
As I already said, my first example assumes you are in the root folder, so takes you below that.
If you were in a sub-folder it would not work, you would need ../../ so things may get confusing if you use different folders.
That is why I mention setting path as a constant (or you could use a variable, but a constant has more scope) to avoid such confusion.

When you make a http request for things like .html or .css files, you will be denied from going below the root, that is the point. But a php include does have access there.

1 Like

Hi SamA74

You are right it is confusing would you help me out with this include.

my form validation tree is like root/websitename/file.php thats where I have to store the include and

My included file is outsideRoot/IncludedFilename/file.php so how would I access the included file outside of the directory?

I tried ../../includedfilename/file.php which is quite confusing that sounds like outsideRoot/root/includedfilename/file.php if i tried ../includedfilename/file.php that would be within the root file? so yeah it is quite confusing :frowning:

Hi SamA74

I was doing some research regarding the whole include thing and stumble upon this Setting up htaccess and I was wondering would this be sufficient enough?

and how would it work? would I need to create a new file and have that as the root directory of the htaccess, Does that mean I really have to delete the root file thats already there?

I am not asking you to do things for me I was asking for help understanding the logic behind the whole upwards file directory, Sorry If I came off helpless or a Noob at this :frowning:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.