Thursday, June 2, 2016

trivial PHP survey/email collection with redirect PHP

Brookline Porchfest folks wanted a simple email collection script for a one-page site I made and host for them. Putting this here for future reference, save my future self 20 minutes of reading PHP docs in the future: (I called it "save.php" and made sure there wasn't any whitespace before the first tag, which might mess up the redirect)

<?php
    #$email = str_replace(array("\n", "\r"), '', $_POST["email"]);
    $email = $_POST["email"];
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
        file_put_contents("email.txt","$email\n",FILE_APPEND);
        header( 'Location: thanks.html' ) ;
    } else {
        header( 'Location: error.html' ) ;
    }
?>

So, simple... get the email address submitted, if it looks legit append it to a text file and redirect to a thanks page, otherwise redirect to an error page. (It seems a good practice to dump to a new page, both to avoid reload issues, and so that this functional script is more reusable, separation of concerns.)

The first line is commented out, before I realized PHP had a decent email validator I wanted to at least make sure that any garbage entered was at least limited to one line, even if I was mostly relying on post-facto data cleaning.

Oh, and the form looks like

<form method="POST" action="save.php">
Join our mailing: 
<input name="email" placeholder="Your E-mail Address"> 
<button>Join!</button>
</form>

I really appreciate how easy PHP makes stuff like this, and the docs are really clear and straightforward as well.

No comments:

Post a Comment