Page 1 of 1

Self Processing form - need help cleaning up

Posted: Tue Jul 22, 2008 10:51 am
by awreneau
I have edited your post to add [ php ] and [ /php ] tags to make your script more readable.

I've got a situation wherein I want users, a select few w/ access to the site, to be able to fill out a form that will get posted to a flat file that postfix reads from as an allowed relay list. The code I've copied below works, however it's in need of the finer elements to be polished up and I'm not sure how to do it.

User fills in the following:
Location
Description
IP address
Posters Name

The script checks for blank fields, valid ip, duplicate ip and finally writes the info to the allowed_list file, and eventually will restart postfix (I hope).

My problem, as far as aesthetics are concerned at this point, is that when the data all checks out it prints what was written to file as well as the empty form below the written data. How do I only echo/print the confirmed data? My initial thoughts were to have the form on one page and then hand off the process after all fields are confirmed not empty. But then I had the problem of validating the IP. If the validation failed I couldn't redisplay the form again after clicking submit so I wound up recreating my dilemma all over again if I separated the form from the process.

This is my first attempt at php and I've hack, copied googled, and struggled to get this far so I'd appreciate the help.
code to follow:

Code: Select all

 
<?php
//define variables
$location = $_POST['location'];
$description = $_POST['description'];
$ip = $_POST['ip'];
$user_name = $_POST['user_name'];
$tried = ($_POST['tried'] == 'yes');
$allowed_list = "/var/www/test/testfile.txt";
clearstatcache ();
 
//test for empty fields
 
if ($tried) 
{
$validated = (!empty($location) && !empty($description) && !empty($ip) && !empty($user_name));
 
    if (!$validated) 
    {
    ?>
    <p>
    The Location, Description, IP and User Name are <strong>required</strong> fields.  Please complete them to proceed.
    </p>
<?php
        }
}
 
if ($tried && $validated) {
 
    //test for valid IP
                if (preg_match("{^\b((25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\b$}",$ip))
                {               //valid ip = true
                echo "You have requested the following data to be added to the Mail Relay file:<br /><br />";
                echo "<strong>$location</strong><br />";
                echo "<strong>$description</strong><br />";
                echo "<strong>$user_name</strong><br /";
                echo "<strong>$ip</strong><br /><br />";
                echo "Click <a href = \"index.php\">here</a> to go back and enter another item into the relay.<br />";
 
                        if (file_exists($allowed_list) == false)
                        {
                        die('It seems as tho the file youre attempting to write to doesn\'t exist! Please contact the Systems Engineer ASAP!');
                        //this isnt dieing, it's still displaying the data that would have been written to file, need to fix this
                        }
 
                        else
                        // Read file
                        $data = file_get_contents($allowed_list);
                                if (preg_match("/$ip/", $data, $array))
                                {
                                echo "However the ip address ". $ip . " already exists<br />";
                                echo "Click <a href = \"javascript&#058;history.go(-1)\">here</a> to go back and re-enter the IP.";
                                }
 
                                else
                                {
                                //open relay file for writing
                                $fh = fopen($allowed_list, 'a+') or die("Can't open file");
                                fwrite($fh, "#$location\r\n"); //the "#"  adds a comment to the first of the newly written line, the "\r\n" adds a carriage $
                                fwrite($fh, "#$description\r\n");
                                fwrite($fh, "#$user_name\r\n");
                                fwrite($fh, "#$date\r\n");
                                fwrite($fh, "$ip\r\n");
                                fwrite($fh, "\r\n");
                                fwrite($fh, "\r\n");
                                fclose($fh);
                                }
                }
                else
                {               //valid ip = false
                echo "The IP address you entered " . $ip . " appears to be invalid, please re-enter the IP address.<br /><br />";
                echo "Click <a href = \"javascript&#058;history.go(-1)\">here</a> to go back and re-enter the IP.";
 
                }
 
} else {
    echo "Please fill the fields below to add an item to the WSC MailRelay.<br /><br />";  echo "<strong>ALL FIELDS ARE REQUIRED</strong><br /><br />";
}
 
?>
 
<form action="<?= $PHP_SELF ?>" method="POST">
Location: <input type=text name="location" value="<?= $location ?>" /><br /> <br />
Description: <input type=text name="description" value="<?= $description ?>" /><br /><br />
IP: <input type=integer name="ip" value="<?= $ip ?>" /><br /><br />
Your Name: <input type=text name="user_name" value="<?= $user_name ?>" /><br /> <br />
<input type="hidden" name="date" value="<?php print(date("m/d/Y, h:s A")); ?>">
<input type="hidden" name="tried" value="yes" />
<input type="submit" value="<?php echo $tried ? 'Write to file' : 'Create'; ?>" />
</form>
 

Re: Self Processing form - need help cleaning up

Posted: Tue Jul 22, 2008 6:29 pm
by califdon
You are missing a beginning curly bracket after the else on line 46 above. I don't have the time right now to analyze your script, but if no one else does before I can get back to it, I'll try to help you.

Re: Self Processing form - need help cleaning up

Posted: Wed Jul 23, 2008 9:24 am
by awreneau
Thanks for the help.

Along that thought, is there a editor that will help with Syntax like that? Presently I'm using Nano w/ a PHP include so it color codes the syntax but it does check for error. I'll google that too.

Thanks

Re: Self Processing form - need help cleaning up

Posted: Thu Jul 24, 2008 3:46 pm
by awreneau
OK, I've been hammering out this code and I've pretty much re-written the entire thing. I'm now using Rapid PHP 2008 and it's helped with my syntax errors. So I've got the following code doing exactly as I want it. I wound up separating the form from the page and no longer do I have the form being reprinted when I confirm data. So aesthetically I've made huge improvements. However now I've got another problem. On line 60 I keep getting an error that reads
Syntax error, unexpected T_ELSE in process.php on line 60
:banghead: I can comment out that else statement and of course the code just "falls" through to the next line and the logic is broken. I'd appreciate someone having a look at this.

**the actual "else" in question is on line 61 below, not sure why a blank line is added at the top of the code

Code: Select all

 
<?php
//define variables retrieved from the html form
//$branch_number = $_REQUEST['branch_number'];
//$branch_location = $_REQUEST['branch_location'];
//$dev_description = $_REQUEST['dev_description'];
//$user_name = $_REQUEST['user_name'];
//$ip = $_REQUEST['ip'];
//$date = $_REQUEST['date'];
$allowed_list = "/var/www/test/testfile.txt";//path to the postfix Allowed Relay file
 
//$branch_number = 9999;
//$branch_location = Thomasville;
//$dev_description = Printer;
//$user_name = Wes;
//$ip = "192.168.1.39";
 
 
 
 
 
if (!isset ($_request['$branch_number']) || (!isset ($_request['$branch_location'])) || (!isset ($_request['$dev_description'])) || (!isset ($_request['$user_name'])) || !isset ($_request['$ip']))
{
     if (empty ($branch_number) || empty ($branch_location) || empty ($dev_description) || empty ($user_name) || empty ($ip))
     {
          echo "<center><strong>A field is empty</strong></center><br />";
          echo "<center><strong>Click <a href = \"javascript&#058;history.go(-1)\">here</a> to go back and re-enter the data</strong></center>";
          //add more granular checking above, so when a user is returned to the form the field in error is in red, or has some indication of error
     }
     else
     {
          if (preg_match("{^\b((25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\b$}", $ip))
          {
               echo "ip is good";
               // Read file so we can check for duplicate IP addresses
               $data = file_get_contents($allowed_list);
               if (preg_match("/$ip/", $data) == false)
               {
                    echo "<br /><center><strong><i><font color = #0000CC>" . $user_name . "</font></i> has requested the following data to be written to the WSC Mail Relay:</strong></center><br />";
                    echo "<center><strong>Branch <i><font color = #0000CC>" . $branch_number . " " . $branch_location . "</font></i></strong></center> <br />";
                    echo "<center><strong>Device description:<i><font color = #0000CC> " . $dev_description . "</font></i></strong></center><br />";
                    echo "<center><strong>IP Address:<i><font color = #0000CC> " . $ip . "</font></i></strong></center><br />";
                    echo "<center><strong>Are you sure you want to write this information to the file?</strong></center>";
                    echo "<html>";
                    echo "<form method = \"post\" action = \"<?= $PHP_SELF ?>\">";
                    echo "<center><strong><input type= \"submit\" name=\"write\" value=\"Yes\"/> <input type=\"reset\" name=\"reset\" value=\"No\"/></strong></center>";
                    $write_file = $_POST['write'];
                    $no_write_file = $_POST['reset'];
               }
 
                   if (!isset ($_POST['$write_file']))
                   {
                   echo "I'm going to write the file now";
                   }
 
                   else // (!isset ($_POST[ '$no_write_file']))
                   {
                     echo "I'm not going to write the file now";
                   }
 
               else
               {
                    echo "<center><strong>The ip address<font color  = #ff0000> " . $ip . "</font> already exists</strong></center><br />";
                    echo "<center><strong>Click <a href = \"javascript&#058;history.go(-1)\">here</a> to go back and re-enter the IP.<center><strong>";
               }
          }
          else
          {
               echo "ip is bad";
               echo "<center><strong>The ip address<font color  = #ff0000> " . $ip . "</font> is invalid.</strong></center><br />";
               echo "<center><strong>Click <a href = \"javascript&#058;history.go(-1)\">here</a> to go back and re-enter the IP.<center><strong>";
          }
     }
}
?>
 
My logic and desired result is basically the same.

Check for blank fields
Check for valid IP
Check for duplicate IP
Confirm data prior to writing
Write file

Todo:
backup file prior to write
restart postfix

Regards...

Re: Self Processing form - need help cleaning up

Posted: Thu Jul 24, 2008 9:31 pm
by califdon
What that error says is that it encountered an else token unexpectedly, so there is something wrong with the preceding code blocks, so it doesn't know what you wanted it to do. I don't have the time right now to go through your code in detail, but if you will pair up your { ... } blocks, no doubt you will discover where you have closed an if block and later you have that else statement on Line 60.

Re: Self Processing form - need help cleaning up

Posted: Fri Jul 25, 2008 7:48 am
by awreneau
califdon,

thanks for being the sounding board. I had a hunch that the else was "orphaned", not sure if that is the correct way to describe it, but I couldnt nail down why.

Well I downloaded two editors yesterday, Rapid PHP and PHP Expert Editor. I was using Rapid PHP and really liked it but I hadnt used PHP Expert Editor so I opened the code in that editor and the error of my way jumped off the page at me. In PHP Expert Editor you can collapse the IF statements to make reading the code easier. The IF statement that checks if the submit button was clicked on line 51 should have been included in the previous IF statement. I inadvertently left it outside the statement.

So now that it's working it exposes a few other "gotchas" not yet seen. Off to hammer those out.

Thanks!

Re: Self Processing form - need help cleaning up

Posted: Fri Jul 25, 2008 2:57 pm
by awreneau
I'm not sure if I'm making progress or further complicating things, either way I have my script working :D. However, I ran into a problem with my approach I'll try to explain...

form.php //user inputs data and the post is sent to process.php
process.php //validates user input, asks user to confirm intentions w/ a html form that is sent to write_file.php
write_file.php writes data to file

Now, to get this to work I introduced sessions making the variables available throughout the whole experience. That will come in handy later as I add functionality such as parsing the Postfix log file for denies and/or activity for a specific IP.

Once sessions were enabled and setup when I confirmed the data I got the following warning.

Warning: Unknown: Your script possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that the session extension does not consider global variables as a source of data, unless register_globals is enabled. You can disable this functionality and this warning by setting session.bug_compat_42 or session.bug_compat_warn to off, respectively. in Unknown on line 0


So, I went ahead and turned on global_variables and it works flawlessly. Well, reading about the global_variables being turned on is a security risk, I'd like to eliminate that. How can I use variables throughout the users experience by implementing session data? Or can I? Googling I go...

I'm assuming I'll have to use cookies in place of session?

Regards