0

I have a page for people to submit their information /collect.php but when submitting it keeps going to the root. Is it possible to submit the form and make it go to the same collect?

Here is the code I have so far:

<?php if (!empty($_POST)):
    $firstname = htmlentities($_POST['firstname']);
    $lastname = htmlentities($_POST['lastname']);
    $email = htmlentities($_POST['email']);
    $phone = htmlentities($_POST['phone']);

    echo $firstname."<br/>";
    echo $lastname."<br/>";
    echo $email."<br/>";
    echo $phone."<br/>";
else: ?>
    <form action="." method="post">
        <input type="text" name="firstname" placeholder="First name"><br/>
        <input type="text" name="lastname" placeholder="Last name"><br/>
        <input type="email" name="eamil" placeholder="Email address"><br/>
        <input type="phone" name="number" placeholder="Phone number"><br/>
        <input type="submit">
    </form>
<?php endif; ?>
iam5
  • 1
  • 2
    Welcome. `
    ` without `action` attribute would submit it to your current url
    – Denis Ostrovsky Apr 18 '20 at 06:28
  • I was going to ask - What made you decide to use action="."? Did you actually try anything else like action="" or actually specifying the action path? or leaving it out ( but I would leave it in set to be empty just to be sure in that case) – TimBrownlaw Apr 18 '20 at 06:30

1 Answers1

0

You're almost there, to submit to the same page you can use the $_SERVER["PHP_SELF"] which is a super global variable that returns the filename of the currently executing script.

You'll also want to be careful with your input names, email is misspelled and the form for the phone number is named number while the post is labelled phone. Also, the correct the correct HTML5 for a phone number is tel.

<?php if (!empty($_POST)):
    $firstname = htmlentities($_POST['firstname']);
    $lastname = htmlentities($_POST['lastname']);
    $email = htmlentities($_POST['email']);
    $phone = htmlentities($_POST['phone']);

    echo $firstname."<br/>";
    echo $lastname."<br/>";
    echo $email."<br/>";
    echo $phone."<br/>";
else: ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <input type="text" name="firstname" placeholder="First name"><br/>
        <input type="text" name="lastname" placeholder="Last name"><br/>
        <input type="email" name="email" placeholder="Email address"><br/>
        <input type="tel" pattern="([0-9]{3}) [0-9]{3}-[0-9]{4}" name="phone" placeholder="(123) 456-7890" required><br/>
        <input type="submit">
    </form>
<?php endif; ?>
r0t13
  • 39
  • 3