Pruxis
Pruxis

Reputation: 1

PHP Email Subscription, cannot post php file

Hey I have some trouble with my email subscription I'm trying to log into a textfile.

<!-- Signup Form -->
        <form id="signup-form" action="form.php" method="post">
            <input type="email" name="email" id="email" placeholder="Email Address" />
            <input type="submit" value="Sign Up" />
        </form>

Here's my PHP code:

<?php
if(empty($_POST['submit']) === false) {
    $email = htmlentities(strip_tags($_POST['email']));

    $logname = 'email.txt';
    $logcontents = file_get_contents($logname);

    if(strpos($logcontents,$email)) {
        die('You are already subscribed.');
    } else {
        $filecontents = $email.',';
        $fileopen = fopen($logname,'a+');
        $filewrite = fwrite($fopen,$filecontents);
        $fileclose = fclose($fileopen);
        if(!$fileopen or !$filewrite or !$fileclose) {
        die('Error occured');
        } else {
            echo 'Your email has been added.';
        }
    }
}
?>

I keep getting Cannot POST /form.php eventho the php file is at that path, someone knows what I'm possibly doing wrong? I'm quit noob at this :(

Upvotes: 0

Views: 449

Answers (1)

priya vyas
priya vyas

Reputation: 195

First of all add name attribute to your submit button, as in POST you will not get the form value of "submit" and your code will never go further

  <form id="signup-form" action="form.php" method="post">
    <input type="email" name="email" id="email" placeholder="Email Address" />
    <input type="submit" name="submit" value="Sign Up" />
</form>

Now in your php code, you just need to check $_POST['submit'] in if condition and you have also done a typo, you have used a variable $fopen which is not defined, change that.

<?php
   if($_POST['submit']) {
        $email = htmlentities(strip_tags($_POST['email']));
        $logname = 'email.txt';
        $logcontents = file_get_contents($logname);

        if(strpos($logcontents,$email)) {
            die('You are already subscribed.');
        } else {
            $filecontents = $email.',';
            $fileopen = fopen($logname,'a+');
            $filewrite = fwrite($fileopen,$filecontents);
            $fileclose = fclose($fileopen);
            if(!$fileopen or !$filewrite or !$fileclose) {
            die('Error occured');
            } else {
                echo 'Your email has been added.';
            }
        }
    }
?>

Upvotes: 2

Related Questions