-3

So i have a contact form on my website. However when i submit it redirects me from my html page to the PHP page, id like to automatically redirect back. I have tried using HTACCESS but it redirects straight away and the PHP script doesnt run.

HTML FORM

<form action="action.php" method="post" class="contactForm" target="_top">
  <input type="name" name="field1" placeholder="Enter your name..."><br>
  <input type="email" name="field2" placeholder="Enter your email address..."><br>
 <input type="text" name="field3" placeholder="Enter your message..."><br>
 <input type="submit" value="Submit" id="button">
</form>

action.php

<?php

 $path = 'data.txt';
 if (isset($_POST['field1']) && isset($_POST['field2'])&& isset($_POST['field3'])) {
    $fh = fopen($path,"a+");
    $string = $_POST['field1'].' - '.$_POST['field2'].' - '.$_POST['field3'];
    fwrite($fh,$string);
    fclose($fh);
 }?>

If i am going about this the wrong way please let me know, i am a complete beginner to PHP so i know very little.

Thanks.

3 Answers3

0

header('Location: index.html');

http://php.net/manual/en/function.header.php

You can't output anything before the redirect.

A potentially better way to do this is not to post to the PHP script only to have it redirect back to html, but to post to it through ajax.

Matt
  • 5,315
  • 1
  • 30
  • 57
  • This didnt work, where am I supposed to put it in the action.php script. – user7432478 May 15 '17 at 20:03
  • If you look at your PHP error log it will most likely be complaining that output has already been sent to the browser. You need to do all your logic, and then this redirect without sending anything (echo, var_dump, etc) to the browser. – Matt May 15 '17 at 20:27
0

There are a few ways to do that. I assume you want to take the values from the Form and process them in PHP.

  1. Using Ajax - With Ajax you can send data from your form to a PHP-Script without reloading the page. So in your case no redirect is needed See here for a small tutorial http://blog.teamtreehouse.com/create-ajax-contact-form
  2. Combine PHP and HTML - You can input all your HTML Code into the PHP File and call the PHP File. See -> https://www.ntchosting.com/encyclopedia/scripting-and-programming/php/php-in/
0
               ob_end_clean( );
               header("Location: example.com");
               exit();

Allows you to output something before redirecting.

Carter
  • 131
  • 7