Redirect and error/success messages

Hi guys! i’m coding a site up for a friend and i can’t seem to get this redirect or even my success/error messages to work xD help plx heres my PHP.

<?php
 if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
 
 
/* ----------------------------------------------------------------
   ONLY PROCESS POST METHODS
-----------------------------------------------------------------*/

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
	$name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(400);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    $goto_after_mail = "http://www.bichenoglassbottomboat.com/contact.html"; // This is the URL that is shown after the mail is submitted.


    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "contact@bichenoglassbottomboat.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        header("Location: ".$goto_after_mail);
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

Any help would be highly appreciated, the web address is bichenoglassbottomboat.com/contact.html to see what i am refering to

So i am unable to see my responses because of the exit if accessed directly at the top, how do i get around this as it is for safety, and when i remove it i am receiving my first unsuccessfull message >.<

Try copying this script to a temporary-filename.php.

Play around with the script by modifying the $DEBUG value and thoroughly test for every eventuality.

When everything is working OK then remove all $DEBUG, try then try with working $_POST values.

<?php
declare(strict_types=1);
ini_set('display_errros', 'TRUE');
error_reporting(-1);
# echo $x/$y+1;

if ($DEBUG=0 &&  ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/* ----------------------------------------------------------------
ONLY PROCESS POST METHODS
-----------------------------------------------------------------*/

if($DEBUG=1):
  $_POST['name']    = 'Joe Bloggs';
  $_POST['email']   = 'JoeBloggs@gmail.com';
  $_POST['message'] = 'message from JoeBloggs';
endif;

if ($DEBUG=1 || $_SERVER["REQUEST_METHOD"] === "POST")
{
    // Get the form fields and remove whitespace.
    $name    = strip_tags(trim($_POST["name"]));
    $name    = str_replace(array("\r","\n"),array(" "," "),$name);
    $email   = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if($DEBUG=0 || empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL) )
    {
      // Set a 400 (bad request) response code and exit.
      http_response_code(400);
      echo "Oops! There was a problem with your submission. Please complete the form and try again.";
      exit;
    }
    $goto_after_mail = "http://www.bichenoglassbottomboat.com/contact.html"; 
    // This is the URL that is shown after the mail is submitted.

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "contact@bichenoglassbottomboat.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content  = "Name: $name\n"
                    . "Email: $email\n\n"
                    . "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if($DEBUG=0 && mail($recipient, $subject, $email_content, $email_headers))
    {
        header("Location: " .$goto_after_mail);
        // Set a 200 (okay) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";

    }else{
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }
    
} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

echo '<h1>http_response_code() ==> ' .http_response_code() .'</h1>';

i have nooooo idea what debug values are or do lol, most basic of basic php level like i can echo stuff haha

I did not create this i was just told what that thing at the top does like i got a basic understanding but i have no idea what these debugging things do xD, you are much more trained in the ways than I good sir

When you ran that file, what did you see?

Seems strange you were asked to modify the file and not have a great deal of PHP knowledge. Be careful it is far too easy to create havoc and expose the site to malicious hackers.

Setting the $DEBUG value to 0 ignores the remaining tests.

//  Force if condition to be FALSE.
if ($DEBUG=0  && $_SERVER["REQUEST_METHOD"] === "POST")

Setting the $DEBUG value to 1 ignores the remaining tests.

//  Force if condition to be TRUE.
if ($DEBUG=1 || $_SERVER["REQUEST_METHOD"] === "POST")

Can you expand on “can’t get it to work”? What happens that should not, or doesn’t happen that should?

The first problem I see is the script is trying to echo a message AFTER you have already redirected (Line 48). You also need to kill the script after a redirect.

okie dokie thanks john i will have a play around =), i think i understand that right xD so i play around setting the debug value to 0 from 1 as a i down the page till i find a problem? xD and @droopsnoot it should be echoing either a success or error message then returning to the contact page, or displaying the either successfull or unsuccesful message on the contact page after a message has been sent either of those would be fine haha,

1 Like

If you want to level up your skills learn to use xdebug – “smart debugging”. Poor mans debugging is for amateurs and prod servers. Also real time debugging is a skills that transcends any single language resulting in more efficient problem solving. Even though you are just starting learning real time debugging will make you better than 75% of people programming php. I find it amazing such a low number of php devs don’t know how to real time debug php.

https://xdebug.org/

XD i would love to use something like this zookeper but without access to my computers BIOS atm its a little hard xD, cant even use local by flywheel =( stupid HP computer my monitor wont turn on when i bring up BIOS =( its making my life hell haha, so for now i have to do the poor man’s way xD

I’m assuming you are using xamp or mamp?

ohhhh i can update my php to 7 with that for my main computer? xD yea i have XAMPP, haha is it the phpinfo() file from xampp i send them for detailed install instructions?

Not exactly.

You need to install the xdebug extension and use a editor compatible with xdebug.

I abandoned xampp several years ago for vagrant or more specifically puphpet which makes it very easy to build environments for running projects locally.

I’m also a a proponent of all the JetBrains products. PHPStorm supports xdebug very well.

PHPStorm isn’t free but it is the BEST IDE available. There are several editors that integrate with xdebug. You can use one of your choosing if not PHPStorm.

That being said you will need to first install xdebug on xamp. I’m sure there are articles on google for that.

wow thanks for the tips zookeeper! so essentially once i have the IDE set up with say PHP 7, i download the PHP 7 extension for xdebug and follow instructions and it should work? haha or download the IDE, install, then send them the phpinfo() from that IDE for detailed instructions?

oh and john the form I was given is supposed to work I obtained it from my teacher at TAFE haha, all I was supposed to be required to do was change the e-mail address it gets sent to lol which is super basic and easy to do without touching anything else xD, well it would be in a perfect world haha you guys have all been great and I appreciate all the help =)

1 Like

You can download a free version of PHPStorm as a 30 day trial. I highly recommend that. Once you do that you need to install the xdbug extension. I’ve only used xdebug as an extension on a puphpet box but you can install it on xamp/mamp. I’m going to preference this by saying xdebug can be a total pain to set-up. When you get it set-up and working though you will love it. I can see why php devs don’t use it. It can be difficult to set-up. I’m working with ruby after a decade of php and ruby debugging is SO much easier to set-up than php. Again though the skill of real time debugging is one of the most valuable things you can learn. If you are going to spend any time learning php I HIGHLY recommend using puphpet to stand up a local environment and smart debugging. I’m not going to say anything bad about xamp / mamp but puphpet / vagrant is amazing. I’ve worked with people who spend several days on a problem only to ask me. I recreate it locally, smart debug it and have a cause within an hour and solution that be implemented in 1/4 the time. So I highly believe in promote in smart debugging. Ironically back in the day the first place I learned about all this was sitepoint but this site has completely dropped off in its usefulness as a knowledge resource. I wish the info they provide would be more useful and not just fluff / opinion.

xD yea theres alot of sites and live speakers these days who can be very opinion based, and I am very interested in learning more PHP xD, yea i’m going to give vagrant a go haha just had people dragging me around left right and center last few days xD ill have a crack at installing all of this and getting it runnning, thanks for all your tips =), if that’s the case I definately wanna learn how to do it haha, plus anything that can tell me why something isnt working would be lovely xD.
I am not against putting in a bit of hard work haha, only thing is if it involves anything where you gotta get to the BIOS menu of your computer I cant do it atm because my monitor decides it doesn’t wanna turn on when I access the BIOS after restarting lol

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