Pink
Pink

Reputation: 161

PHP page gets redirected without the execution of the rest of the script

I have the following script which takes data from the users and writes into a file using PHP. The issue that I am facing is when i direct the page using "form action" the page gets redirected but the rest of the script is not executed meaning no new data is written to the file, but when I leave the Form action blank the data gets written. Below is the code:

 <html>
 <body>
    <form action="page.php" method="post">
        <input type="text" name="text_box"/>
        <input type="submit" id="search-submit" value="submit" />
    </form>
</body>
</html>
<?php
if(isset($_POST['text_box'])) { //only do file operations when appropriate
    $a = $_POST['text_box'];
    $myFile = "t.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $a);
    fclose($fh);
}
?> 

Upvotes: 0

Views: 112

Answers (3)

Scott
Scott

Reputation: 5379

PHP won't save it automatically. You need to submit the form for it to then execute with given data.

Also, your fopen is using 'w' which truncates the file, then writes to it. So every time you save, the new data isn't appended onto the end, it replaces the current data.

Also, is this file called 'page.php'? The only other solution I can think of with your code is to move the PHP code to the top of the file, before the <html>.

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

You're submitting your form to page.php, but your form handling logic is found on index.php. That's what's causing your problems.

Either submit to index.php rather than page.php, or simply move the form handling logic to page.php.

Upvotes: 1

Dan Blows
Dan Blows

Reputation: 21174

When somebody submits the form, it will take them to 'page.php'. Whatever PHP is in that file will be executed. Any PHP in the file above (i.e. not in page.php) won't be executed - it will never be read.

Just an aside: I would check out a PHP framework like Yii or CodeIgniter to help you here. Handles a lot of these problems for you.

Upvotes: 0

Related Questions