Struggling with form

Hi,
I’m struggling with a form for a guestbook.
I want when the submit button is cilcked,
the message posted (duh…) :slight_smile:
Fields reset to empty
page reloaded with no values in the URL behind the questionmark (if I refresh the page now the same message s posted again…)

This is what I have so far, hope someone can help me out, or perhaps has a better solution. Thanks

 <?php
  $amount=15;

  if ($_POST['action']=='write') {
      header('location: gasten.php?action=read&start=0');
    $file=fopen('gastenboek.txt','a');

    $message=str_replace("\\r",'',$message);
    $message=str_replace("\
",'{{',$_GET['message']);
    fwrite($file,$_GET['name'].'|||'.$_GET['email'].'|||'.date('d-m-Y').'|||'.$_GET['url'].'|||'.$message."\
");
    fclose($file);
    
  }

  $start=(isset($_GET['start'])?$_GET['start']:0);
  $gastenboek=Array();
  $gastenboek=file('gastenboek.txt');

?>

  <SCRIPT language="JavaScript">
    function validate(form) 
  {
      if (form.name.value=="") 
    {
      alert("Vul je naam in");
      return false;
    } 
    else if (form.message.value=="") 
    {
      alert("Vul je bericht in");
      return false;
    } 
    else if (form.url.value=="") 
    {
      return true;
    } 
    else 
    {
     return false;
    }
  }
                </SCRIPT>
              </p>
<TABLE width="100%" cellspacing="0" cellpadding="0">
  <TR>
      <TD class="side"> Berichten <? echo $start+1; ?> tot en met <? echo min($start+$amount,sizeof($gastenboek)); ?>.
        <HR> <TABLE width="100%" >
          <?
          $gastenboek=array_reverse($gastenboek);
          for ($i=$start;$i<$start+$amount && $i<sizeof($gastenboek);$i++) {
            list($name,$email,$date,$url,$message)=explode('|||',$gastenboek[$i]);
            $message=str_replace('{{',"\
",$message);
            echo '<TR><TD><B>'.($email!=""?'<A href="mailto:'.$email.'">'.$name.'</A>':$name).'</B></TD><TD align="right"><B>'.$date.'</B></TD></TR>'."\
";
            echo ($url!=""?'<TR><TD colspan="2"><A href="'.$url.'" target="_blank">'.$url.'</A></TD></TR>':'')."\
";
            echo '<TR><TD colspan="2"><SPAN>'.str_replace("\
",'<BR>',htmlspecialchars($message)).'</SPAN></TD></TR>'."\
";
            echo '<TR><TD colspan="2"><HR></TD></TR>'."\
";
          }
        ?>
        </TABLE>
        <CENTER>
          <?
          if ($start>0) echo '<A href="gasten.php?start='.max(0,$start-$amount).'"><<<</A> ';
          if ($start+$amount<sizeof($gastenboek)) echo ' <A href="gasten.php?start='.($start+$amount).'">>>></A>';
        ?>   </CENTER></TD>
    </TR>
</TABLE>
  <TABLE width="100%" cellspacing="0" cellpadding="0" >
    <TR>
      <TD class="side">Nieuw bericht</TD>
    </TR>
  </TABLE>
  <TABLE width="100%" cellspacing="0" cellpadding="0" >
    <TR>
      <TD class="side"> <FORM action="gasten.php" method="POST" onSubmit="return validate(this); document.form.name.value=''; document.form.message.value=''; document.location='http://somesite.nl/newindex.html';">
          <INPUT type="hidden" name="action" value="write">
          <TABLE class="side">
            <TR>
              <TD>Naam:</TD>
              <TD><INPUT type="text" name="name" size="30"></TD>
            </TR>
            <TR>
              <TD>E-Mail:</TD>
              <TD><INPUT type="text" name="email" size="30">
                (optioneel)</TD>
            </TR>
            <TR>
              <TD><p class="antispam">Leave this empty:
            <br /><input name="url"/></p></TD>
            </TR>
            <TR>
              <TD>Bericht:</TD>
              <TD><TEXTAREA name="message" cols="50" rows="5"></TEXTAREA></TD>
            </TR>
          </TABLE>
          <INPUT type="submit" value="Verstuur">
        </FORM></TD>
    </TR>
  </TABLE>

Have to leave now, will check end of afternoon.
Thanks again for your great support, think we’re almost there…

To be honest, I’m not entirely sure what you’re trying to accomplish and the fact that I can’t read what I assume is supposed to be German really isn’t helping my understanding of this script.
In the page that has your form, if you want to trigger a special case after redirection you can use this for your redirection at the end of action.php:


header('location: '.$_POST['return'].'?action=write');

That will allow you to work with what I assume was the conditional statement for special output after posting.

If you could elaborate as to what is supposed to happen with this file I may be able to be of more assistance.

Oke no more errors, removed a few spaces before <?php
New message is posted in the textfile, but not shown.
I was looking to these lines:
$gastenboek=Array();
$gastenboek=file(‘gastenboek.txt’);
Shouldn’t this be in the gasten.php somewhere?
It looks as if the page doesn’t know where to look as $gastenboek is not defined.

<TABLE width="100%" cellspacing="0" cellpadding="0">
  <TR>
      <TD class="side"> Berichten <? echo $start+1; ?> tot en met <? echo min($start+$amount,sizeof($gastenboek)); ?>.
        <HR> <TABLE width="100%" >
          <?
          $gastenboek=array_reverse($gastenboek);
          for ($i=$start;$i<$start+$amount && $i<sizeof($gastenboek);$i++) {
            list($name,$email,$date,$url,$message)=explode('|||',$gastenboek[$i]);
            $message=str_replace('{{',"\
",$message);
            echo '<TR><TD><B>'.($email!=""?'<A href="mailto:'.$email.'">'.$name.'</A>':$name).'</B></TD><TD align="right"><B>'.$date.'</B></TD></TR>'."\
";
            echo ($url!=""?'<TR><TD colspan="2"><A href="'.$url.'" target="_blank">'.$url.'</A></TD></TR>':'')."\
";
            echo '<TR><TD colspan="2"><SPAN>'.str_replace("\
",'<BR>',htmlspecialchars($message)).'</SPAN></TD></TR>'."\
";
            echo '<TR><TD colspan="2"><HR></TD></TR>'."\
";
          }
        ?>
        </TABLE>
        <CENTER>
          <?
          if ($start>0) echo '<A href="gasten.php?start='.max(0,$start-$amount).'"><<<</A> ';
          if ($start+$amount<sizeof($gastenboek)) echo ' <A href="gasten.php?start='.($start+$amount).'">>>></A>';
        ?>   </CENTER></TD>
    </TR>
</TABLE>

Okay, the problem here is that you’re sending some kind of text to the browser before header() is run. Make sure you have no text before <?php, no echo’s, no prints, nothing outputting any data. Not even spaces.

Warning: Cannot modify header information - headers already sent by (output started at /home/mysite.nl/public_html/guests/action.php:3) in /home/mysite.nl/public_html/guests/action.php on line 18

Line 18 of action.php: header('location: '.$_POST[‘return’]);

Hmm… Try turning on Error reporting at the start of action.php to find out what’s going on.

<?php
error_reporting(E_ALL);

Let me know what errors (if any) you’re getting.

Hm something with returning isn’t oke… I checked the txt file with messages and a new one is posted, but not shown, still hanging in action.php
Also when I open the original page I don’t see the messages
Sorry to be a p.i.t.a …:goof:

Alright, here’s a revised action.php

Here’s what I’ve done:


<?php
  $amount=15;

  if ($_POST['action']=='write') {
    //Stop this redirection. Not sure what it's doing.
    //header('location: gasten.php?action=read&start=0');
    $file=fopen('gastenboek.txt','a');
    
    //Define $message before using it.
    $message=$_POST['message'];
    $message=str_replace("\\r",'', $message);
    $message=str_replace("\
",'{{',$message);
    fwrite($file,$_POST['name'].'|||'.$_POST['email'].'|||'.date('d-m-Y').'|||'.$_POST['url'].'|||'.$message."\
");
    fclose($file);
        
  }

  $start=(isset($_POST['start'])?$_POST['start']:0);
  $gastenboek=Array();
  $gastenboek=file('gastenboek.txt');


  header('location: '.$_POST['return']);
?>

Oke changed that, but still I don’t see the older posted messages, and I cannot post new one. Getting redirected to action.php and that’s it…


     <TD class="side"> <TD class="side"> <FORM action="action.php" method="POST" onSubmit="return validate(this);">
          <INPUT type="hidden" name="action" value="write">
           <TABLE class="side">
            <TR>
              <TD>Naam:</TD>
              <TD><INPUT type="text" name="name" size="30"></TD>
            </TR>
            <TR>
              <TD>E-Mail:</TD>
              <TD><INPUT type="text" name="email" size="30">
                (optioneel)</TD>
            </TR>
            <TR>
              <TD><p class="antispam">Leave this empty:
            <br /><input name="url"/></p></TD>
            </TR>
            <TR>
              <TD>Bericht:</TD>
              <TD><TEXTAREA name="message" cols="50" rows="5"></TEXTAREA></TD>
            </TR>
          </TABLE>
          <INPUT type="submit" value="Verstuur" form onsubmit="document.form.name.value=''; document.form.message.value=''; ">
<!-- Down where I have $_SERVER['REQUEST_URI'], your script says $_SERVER['REQUEST_URL']
That will not work. -->
          <input type="hidden" name="return" value="<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>" /> 
        </FORM>

Must be my stupidity but I can’t get it working… sorry…
I changed the Form to

     <TD class="side"> <TD class="side"> <FORM action="action.php" method="POST" onSubmit="return validate(this);">
          <INPUT type="hidden" name="action" value="write">
           <TABLE class="side">
            <TR>
              <TD>Naam:</TD>
              <TD><INPUT type="text" name="name" size="30"></TD>
            </TR>
            <TR>
              <TD>E-Mail:</TD>
              <TD><INPUT type="text" name="email" size="30">
                (optioneel)</TD>
            </TR>
            <TR>
              <TD><p class="antispam">Leave this empty:
            <br /><input name="url"/></p></TD>
            </TR>
            <TR>
              <TD>Bericht:</TD>
              <TD><TEXTAREA name="message" cols="50" rows="5"></TEXTAREA></TD>
            </TR>
          </TABLE>
          <INPUT type="submit" value="Verstuur" form onsubmit="document.form.name.value=''; document.form.message.value=''; ">
          <input type='hidden' name='return' value='<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URL'] ?>' /> 

        </FORM>

And created the action.php

<?php
  $amount=15;

  if ($_POST['action']=='write') {
      header('location: gasten.php?action=read&start=0');
    $file=fopen('gastenboek.txt','a');

    $message=str_replace("\\r",'',$message);
    $message=str_replace("\
",'{{',$_POST['message']);
    fwrite($file,$_POST['name'].'|||'.$_POST['email'].'|||'.date('d-m-Y').'|||'.$_POST['url'].'|||'.$message."\
");
    fclose($file);
        
  }

  $start=(isset($_POST['start'])?$_POST['start']:0);
  $gastenboek=Array();
  $gastenboek=file('gastenboek.txt');


  header('location: '.$_POST['return']);
?>

Now I don’t see the messages posted, and on posting new one, I get empty page “action.php” nothing happens…

As I showed above, all you’d do is add a hidden element with the current location to the end of the form, and set the form’s action attribute to direct the user to action.php

<form action='action.php' method='post'> 
<!-- ^^^ Note the action. -->
//Form elements
<!-- This goes before the end of your form. VVV -->
<input type='hidden' name='return' value='<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>' /> 
</form>

Then all your PHP goes in the action.php file.

Oke, sounds oke to me, but how should I integrate this into the form I already have? WIth the validating and all…
Can you show me please ?
Thanks for your time and support, appreciate it !

Yup. To do that, you need should use this page structure:
Posting page -> Action page -> Posting page

The posting page should send its data to an action page where you work with the data. This action page should have no output, and then redirect the user to the posting page.

Here’s how you might do this:
Posting Page:


<form action='action.php' method='post'>
//Form elements
<input type='hidden' name='return' value='<?php echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>' />
</form>

Action Page


<?php
  //Actions
  header('location: '.$_POST['return']);
?>

That will return the user to the original page, but should do so without their posted data.

Hi Zarina,
Cool!!
Works like you said, no data in URL. Thanks

One more question, I refreshed the page and the same message, although not visible anywhere, is posted again. Is there a way to prevent that?

Oke I got it…:lol:
The page couldn’t read the txt file now it can and all works as supposed
Added this to gasten.php (page with the form):

<?php
//error_reporting(E_ALL);
  $amount=15;
    $file=fopen('gastenboek.txt','a');
    $start=(isset($_GET['start'])?$_GET['start']:0);
  $gastenboek=Array();
  $gastenboek=file('gastenboek.txt');
 ?>

Thanks again for your patience and support

You’re using $_GET to try to retrieve data stored in $_POST.
You have 3 options:

  1. Change your form method to GET
  2. Change your PHP variables to $_POST
  3. Change your PHP variable to $_REQUEST. This will retrieve from GET, POST, SESSION or COOKIE without having to know where the data is stored. The order of the retrieval will depend on your PHP settings.

I recommend using option 2. The data will be hidden from the URL, but will be more secure than using $_GET. $_GET can be spammed almost no effort, and has a content length limit.

I’m glad I could help! If you need anything else don’t hesitate to ask.

Oke, let me try to explain…
The first code I posted was all in gasten.php (guests.php)
Messages posted before they arrived at this page were visible and they can leave a message by filling in the fields. (except for the URL field which is not visible through css, so if a spambot fills in the UR field the message would not be posted.

Most things are working now: message gets posted, URL is refreshed, fields are emptied.
However when I open the page, no messages which were posted earlier, are shown, while before changing the code this was the case.

I think because we got most php code out of the gasten.php, the gastenboek.txt (the file where messages are stored) is not read properly, as it should.

Does this make sense ?