Jump to content

PHP bootstrap contact form modul help please


anthonygallina

Recommended Posts

I am having trouble with getting this code to not show a thank you modul for incomplete submissions. I also would like the page redirect to originating page(with a pop up modul for either confirmation or error on the page in a modul would be optimal) or just redirect to the originating page without having to create a new PHP file for every page a contact form is on. I have several.

The way it is now it can send mail but it directs to a blank white page with just type on it, and a request to use the browser back button to return to originating page. Also it fires the (Thank you)modul even if in put is in correct. would it please be possible to get help with this?   Thank you.

<form class="o-form" id="contactForm" action="php/contact.php" method="post">
                          <input type="email" name="senderEmail" id="senderEmail" required="required" placeholder="email">
                           <textarea name="message" id="message" required="required placeholder="message"></textarea>
                          <input type="submit" value="send" class="send-button">
                      </form>
                  </div>
              </div>
          </div>
      </div>
      <div class="copyright">
         <span>
           anthonygallina
         </span>
      </div>
   </footer>
   <div class="th-popup">
       <div class="massage-th">
           <h1>Thank You!</h1>
           <p>We apreciate your visit to our home page. We will contact you soon!</p>
       </div>
   </div>

<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/all.js"></script>
<script src="js/jquery.mixitup.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/idangerous.swiper.min.js"></script>
</body>
</html>
<?php

// Define some constants
define( "RECIPIENT_NAME", "YOURNAME" );
define( "RECIPIENT_EMAIL", "YOUR@EMAIL.net" );
define( "EMAIL_SUBJECT", "Visitor Message" );

// Read the form values
$success = false;
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

// If all values exist, send the email
if ( $senderEmail && $message ) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
  $headers = "From: " . $senderEmail . " <" . $senderEmail . ">";
  $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
  echo $success ? "success" : "error";
} else {
?>
<html>
  <head>
    <title>Thanks!</title>
  </head>
  <body>
  <?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you soon.</p>" ?>
  <?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
  <p>Click your browser's Back button to return to the page.</p>
  </body>
</html>
<?php
}
?>
Link to comment
Share on other sites

You're telling it to echo the Thanks! etc any time the GET variable 'ajax' isn't set, you may want to more explicitly define the case where it should be shown and rewrite the condition accordingly.

 

You can also consolidate your Success/Failure lines a little; something like: ***edit*** forgot to escape a quote

$msg = $success ? 'Thanks for sending your message! We\'ll get back to you soon.' : 'There was a problem sending your message. Please try again.';
echo '<p>' . $msg . '</p>';
Link to comment
Share on other sites

 

.Also it fires the (Thank you)modul even if in put is in correct. would it please be possible to get help with this?   Thank you.

Not really  sure that the PHP is firing the modul. But yes it is giving the Thanks in the blank page that the PHP generates that I want directed to a modul in the page,instead of the blank page with type on it. Maybe I am not understanding. Could you please show more of a example of what you are suggesting. LIke a working example please?                   

Link to comment
Share on other sites

Not really  sure that the PHP is firing the modul. But yes it is giving the Thanks in the blank page that the PHP generates that I want directed to a modul in the page,instead of the blank page with type on it. Maybe I am not understanding. Could you please show more of a example of what you are suggesting. LIke a working example please?                   

This is from your code:

 

if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} 

that part first checks if the GET parameter 'ajax' is set, and if that returns true, the ternary evaluation of $success happens, and success or error is printed. Any time that 'ajax' isn't set though, which could well be every time because it's not referenced anywhere else in the provided code, this part:

 

else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you soon.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>

duplicates the same logic as the ternary(twice), but creates a page with title "Thanks" either way.

Link to comment
Share on other sites

It's not a bad looking template, but you've got  javascript errors in the console, and spelling/grammar errors on the page. Not picking on your work, but attention to detail should be a priority. Also it looks like you aren't passing anything with GET values, so the isset($_GET['ajax']) will only ever be false.

Link to comment
Share on other sites

Thank you. Yes it is a work in progress that's why it is in test. Appreciate the critique. I thought if you could see it that it would clarify the thanks pop up I was speaking of. Do you know of a way that I could pass the out put of the php file to the page so that it would display in the pop up box?  Also do you know of a way that I could make the plain white php page with only text not display?

Link to comment
Share on other sites

What thread are you referring too? If you mean this forum thread, then yes. See attached image for your site.

Sorry to be more specific I meant this thread.

PHP Coding Help

Do you need help with some code you wrote? Ask here! We'll get you the answers!

PHP bootstrap contact form modul help please.

I am having trouble with getting this code to not show a thank you modul for incomplete submissions. I also would like the page redirect to originating page(with a pop up modul for either confirmation or error on the page in a modul would be optimal) or just redirect to the originating page without having to create a new PHP file for every page a contact form is on. I have several.

 

The way it is now it can send mail but it directs to a blank white page with just type on it, and a request to use the browser back button to return to originating page. Also it fires the (Thank you)modul even if in put is in correct. would it please be possible to get help with this?   Thank you.

 

I was wondering about the relativity and impact of your post on a public thread.   Maybe I am misunderstanding but what is your point?

I am new here and really wanted help.

Are you implying that the contact form button is coded with click-Jacking code? Or any of the other pages you stripped the code from to get to?

Link to comment
Share on other sites

Clickjacking isn't a problem of your code, it's primarily a webserver configuration issue.

 

Right now, anybody can embed your website in a frame and put a fake GUI on top of it. When an unsuspecting user interacts with this fake GUI, they'll actually trigger actions on your site. This is why big sites like paypal.com, amazon.com etc. all restrict framing.

 

To fix the problem, add the X-Frame-Options header in your response. For example, this will block framing altogether:

X-Frame-Options: DENY

You can either set the header in your webserver configuration, or you can send it with PHP using the header() function.

Link to comment
Share on other sites

What is the point of my post? Is it not clear that I notified you of a security issue you were not aware of? I have not implied anything. I have straight up told you your server has security issues that should be fixed and provided you a screenshot of your site click jacked. There was no code stripped from anywhere. What you should have done if you don't know what click jacking is, is do a 2 second google search on what it is and how to fix it.

Link to comment
Share on other sites

Did a google search and found this.

 

https://cirt.net/clickjack-test

 

 

I will include my link from up above in this thread again also.

 

https://www.owasp.or...nse_Cheat_Sheet

 

And not that I would like to divert the thread from my original question. But this is another question. Could you please also run this test on the server that this forum runs on and post those results? With screen shot?

Link to comment
Share on other sites

There is no point doing the same screenshot for this site. I already told you it is vulnerable just as yours is. @Jacques1 gave you the correct answer how to fix it. It takes like two seconds. Optimally you want to do the fix in the server config rather than application level. Depends on whether you have root access to the server or not. Shared hosting, you will have to do it in the app unless you have .htaccess privleges.

 

I could have just gave you the simple fix, but my belief is you would do better for yourself to look it up and learn about it. On complicated matters I don't mind providing the answers.

 

The Owasp link is probably just going to confuse you. Just do what @Jacques1 said.

Link to comment
Share on other sites

This site is susceptible as well. What does that have to do with your site?

Thank you Scootstah I really dont like the screen shot of my site posted here like that, and would'nt really like a shot of the forum posted like that, even though it could be done. My original question was not about site security. And the whole diverting a way from my original question is a bit frustrating. Is there any one here that could help me with my original question please.

Link to comment
Share on other sites

I found this Scootstah

$('.send-button').click(function(){
         $('.th-popup').addClass('act');
         setTimeout(function() {
                $('.th-popup').removeClass('act');
                  }, 3000);
          }); 
                 $('.th-popup').click(function(){
                     $(this).removeClass('act');
                 });

Still looking for more. It looks like that code plugs into fancy box, and fires the modul.  Do you know if there is a way to have the contact.php file write to the page the out put which is either

<?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you soon.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>

If so then I would not have to write a if statement for the button. Which I am having a hard time with because I dont know how to write the var for when it does send mail. Also is there away to have the contact.php file

do the out put to the page without loading the white page?

Link to comment
Share on other sites

You will need to use an AJAX request to get the response from PHP.

 

First you should change the event to an "onSubmit" event instead of an "onClick" event.

$('.send-button').on('submit', function(){
Next we want to tell the form to not execute its default action when it is submitted. The default action would be to send a POST request to the URL specified in the action attribute. Since we'll be using AJAX to make that request ourselves, we don't want that functionality. We can do that with this:

$('.send-button').on('submit', function(e){
    e.preventDefault();
Next, we need to craft a data object to send to the server, using the values from the form.

var data = {
    email: $('#senderEmail').val(),
    message: $('#message').val()
};
Now we can send an AJAX request using the data from the form.

$.ajax({
    url: 'php/contact.php',
    type: 'POST',
    dataType: 'json',
    data: data
});
The request will be sent, but nothing will happen on the client yet at this point. So we need to put in some handlers that will capture the server response. There is a success handler which will be called when the server request was successful. This is where you will show the "thank you" modal.

$.ajax({
    url: 'php/contact.php',
    type: 'POST',
    dataType: 'json',
    data: data,
    success: function(response){
        if (response.success === true) {
            $('.th-popup').addClass('act');

            setTimeout(function(){
                $('.th-popup').removeClass('act');
            }, 3000);
        }    
    }
});
Now the client will display the "thank you" modal if the physical request was successful and if the PHP script thinks it was successful. To determine if PHP thinks it is successful, we are checking for response.success inside of the success handler. This is something you'll want to add to your PHP script.

 

So in your PHP script you'll want to return a JSON string that looks like this:

{ "success": true, "message": "Thanks for sending your message! We'll get back to you soon." }
We only want to send that kind of response if the request is from AJAX. You're sort of doing that check already, but not in the correct way. Instead of looking for an "ajax" querystring parameter, we can simply check for a specific header that is sent with AJAX requests.

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
That's kind of a long conditional so let's define a function instead.

function isAjaxRequest()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
Now then, let's make the response JSON. This will be replacing this code:

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
  echo $success ? "success" : "error";
} else {
// Return an appropriate response to the browser
if (isAjaxRequest() === true) {
    if ($success === true) {
        $message = "Thanks for sending your message! We'll get back to you soon.";
    } else {
        $message = "There was a problem sending your message. Please try again.";
    }

    // send JSON response
    echo json_encode(array(
        'success' => $success,
        'message' => $message,
    ));

    // exit to make sure no other output is sent
    exit;
} else {
Pay close attention to this part:

echo json_encode(array(
    'success' => $success,
    'message' => $message,
));
See those keys, success and message? Well, those are what we use over in the AJAX success handler, on the response object. if (response.success === true) {

 

The last thing to do would be to put the message received from the server into the "thank you" box, but I don't know how that looks. You'd simply need to select the element with jQuery and use the .text() method to apply the response.message data.

 

You may also want to add a error handler in case the request failed.

 

Here is what everything looks like all together:

 

Javascript

$('.send-button').on('submit', function(e){
    e.preventDefault();

    var data = {
        email: $('#senderEmail').val(),
        message: $('#message').val()
    };

    $.ajax({
        url: 'php/contact.php',
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function(response){
            if (response.success === true) {
                $('.th-popup').addClass('act');

                setTimeout(function(){
                    $('.th-popup').removeClass('act');
                }, 3000);
            }    
        }
    });
});
PHP altered a little bit to cleanup/reduce duplication:

<?php

function isAjaxRequest()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}

// Define some constants
define( "RECIPIENT_NAME", "YOURNAME" );
define( "RECIPIENT_EMAIL", "YOUR@EMAIL.net" );
define( "EMAIL_SUBJECT", "Visitor Message" );

// Read the form values
$success = false;
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

// If all values exist, send the email
if ( $senderEmail && $message ) {
    $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
    $headers = "From: " . $senderEmail . " <" . $senderEmail . ">";
    $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );

    if ($success === true) {
        $responseMessage = "Thanks for sending your message! We'll get back to you soon.";
    } else {
        $responseMessage = "There was a problem sending your message. Please try again.";
    }

    // Return an appropriate response to the browser
    if (isAjaxRequest() === true) {
        // send JSON response
        echo json_encode(array(
            'success' => $success,
            'message' => $responseMessage,
        ));

        // exit to make sure no other output is sent
        exit;
    } else {
    ?>
    <html>
      <head>
        <title>Thanks!</title>
      </head>
      <body>
        <p><?php echo $responseMessage; ?></p>
        <p>Click your browser's Back button to return to the page.</p>
      </body>
    </html>
    <?php
    }
} else {
    // you'll want to handle this state - where $senderEmail or $message
    // are empty strings.
}
Link to comment
Share on other sites

Thank you Scootstah Beautiful code and well documented. Really apreciated  :)

I have it installed and it looks like it should work. Unfortunatly the modul doesnt fire now, and it does'nt seem to output anything to the page. Just outputs the white page that the php script makes.

Looks like I have a real chinese puzzle over here :(

I am thinking that maybe the onclick value plugs in the bootstrap js to do the modul.

Link to comment
Share on other sites

What do you mean "the white page that PHP makes"? If you're getting just a white page then you're likely encountering a fatal error. Make sure error_reporting and display_errors are turned on in your php.ini

 

Alternately, check the Apache log for PHP errors.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.