Quickly Create Form Variables - simple form, variable creation, referer check, safe guard variables

free web hosting
Free Web Hosting > Computers & Tech > Programming > Scripting > PHP

Quickly Create Form Variables - simple form, variable creation, referer check, safe guard variables

mastercomputers
The reason I wanted to share this is I've seen so many people do this with their forms when using PHP.

CODE
$username = $_POST['username'];
$password = sha1($_POST['password']);
$another_var = $_POST['another_var'];


... and so on, just imagine if you had a large number of form inputs, do you really want to create each and every variable name?

Why people do this, is probably due to most of the examples I've seen on the web, that does not show an easier and much quicker way of doing it. Though my way might be much easier and quicker, it does introduce security concerns which I've tried to eliminate the most commonly seen problems with the method I'm about to show but since I only created this today, I haven't really had the chance to extensively test every possible flaw that could lurk in it.

I should mention I develop on PHP 5, but this should work with PHP 4.3 and could possibly work with PHP 4 but I think some of the things I've done would need to be rewritten to work with it.

So first of all the complete PHP page that demonstrates what I want to show, I will break down the PHP code and explain that, the form is simple HTML conforming to XHTML 1.1 standards, but the importance here is the PHP code itself.

simple_form.php
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-NZ">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Quick Form Variable Creation</title>
    </head>
    <body>
        <?php
        $allowed_referers = array('yourdomain.com');
        if (!empty($_POST['login']) && $_POST['login'] == 'Login')
        {
            if (!empty($_SERVER['HTTP_REFERER']))
            {
                $referer = current(array_splice(explode('/',$_SERVER['HTTP_REFERER']),2,1));
            }
            else
            {
                exit('<h1>BAD REFERER</h1><p>Oops!</p></body></html>');
            }
            if (!in_array($referer,$allowed_referers))
            {
                exit('<h1>BAD REFERER</h1><p>Oops!</p></body></html>');
            }
            array_pop($_POST);
            $created_variables = '';
            foreach ($_POST as $name => $value)
            {
                if (empty($$name))
                {
                    if (!empty($name) || !empty($value))
                    {
                        ${$name} = $value;
                        $created_variables .= '<tr><td>$'.$name.'</td><td>'.$value.'</td></tr>';
                    }
                }
            }
        }
        ?>
        <p><strong>Please Note:</strong> This is just a <em>demonstration</em>, please do not insert <strong>passwords</strong> that you use, as it is displayed back in plain text.</p>
        <br />
        <p><?php if (!empty($username)) { echo 'Welcome back <strong>'.$username.'</strong>, Thank you for logging in.'; } else { echo 'Hello <strong>Guest</strong>, Please log in.'; } ?></p>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
            <fieldset>
                <legend>Login Form</legend>
                <ul>
                    <li><label for="username">Username:</label> <input id="username" name="username" type="text" /></li>
                    <li><label for="password">Password:</label> <input id="password" name="password" type="password" /></li>
                </ul>
                <input id="login" name="login" value="Login" type="submit" />
            </fieldset>
        </form>
        <?php
        if (!empty($created_variables)) { ?>
        <table>
            <thead>
                <tr>
                    <th>Variable Name</th>
                    <th>Variable Value</th>
                </tr>
            </thead>
            <tfoot>
                <td colspan="2"><em>These were the variables created from the above form.</em></td>
            </tfoot>
            <tbody>
                <?php echo $created_variables; ?>
            </tbody>
        </table>
        <?php } ?>
    </body>
</html>


First of all, I'll explain the form. This is a basic form, that takes user's input and sends the information back to the same page to be processed. The input names of the form become the created variables so that we do not have to manually create them ourselves. With the information gathered from the form, it will alter and add additional information to the page, creating a table after the form, displaying the variables created and the values they were assigned. Remember the password is not encrypted in any way with this form, it is a demonstration and will display it back in plain text, if you're using a password input, be sure to encrypt the variable that it is assigned. In this example, you would do something like the code below after the variable has been created:

CODE
if (!empty($password)) { $password = sha1($password); }


Now on to the real stuff.

CODE
$allowed_referers = array('yourdomain.com');


This is to make sure that the form information being received is going to come from the domain you list in this array, as we don't want the form to be submitted from any other place as they could then alter our automatically created variables in a way that could compromise security. Now to make it more secure (just thought of it now), I would create a md5 hash of the form so that I can tell that the page has not been altered at all as it's possible to change the clientside of the page and still have it seem like it came from your site.

CODE
if (!empty($_POST['login']) && $_POST['login'] == 'Login')
        {


This starts the form processing, when the login button is pressed, the posted information gets sent back to the page, and this checks whether login was created and whether the login had the value we made it.

CODE
if (!empty($_SERVER['HTTP_REFERER']))
            {
                $referer = current(array_splice(explode('/',$_SERVER['HTTP_REFERER']),2,1));
            }
            else
            {
                exit('<h1>BAD REFERER</h1><p>Oops!</p></body></html>');
            }
            if (!in_array($referer,$allowed_referers))
            {
                exit('<h1>BAD REFERER</h1><p>Oops!</p></body></html>');
            }


This is the referer check, it checks whether our server got the referer, it then grabs the domain part of the referer (I hope) and if it's not set or is not our allowed referers, it exits with a simple BAD REFERER message, which I'm sure you could be more creative about it. This is where PHP 4 could fail, but I'm sure there's alternative ways to grab the referer.

CODE
array_pop($_POST);


This is to drop the $_POST['login'] from the $_POST, so we don't create a variable for it, but if you do want it, then leave it in. Now I believe this relies on form ordering, so if the submission is not the last, we could not do this, but since we created the form, and made sure it came last, then this should be fine for us.

CODE
$created_variables = '';


This isn't vitally important, it's just to help this demonstration and give us something we can store information in to display back so we can see what happened.

CODE
foreach ($_POST as $name => $value)
            {
                if (empty($$name))
                {
                    if (!empty($name) && !empty($value))
                    {
                        ${$name} = $value;
                        $created_variables .= '<tr><td>$'.$name.'</td><td>'.$value.'</td></tr>';
                    }
                }
            }


This is what people were probably waiting for, the part that makes variable creating easier, basically we are looping through each $_POST item, using the form name and the value. The first if statement checks that what we are using in the form is empty and not used already, otherwise we could potentially overwrite an internal variable we use as it could affect the behaviour of the program, you could possibly handle this another way by changing the variable so it doesn't conflict but then you would need to figure out how you can remember that change, I don't like variated variables like that, e.g. $password, $password1, $password3 so make sure that your form doesn't use anything that conflicts and this is also an area we have to make sure is secure.

Next I did a check if the form name exists and if the value exists, if not, I don't bother with creating a variable, but in your case, you may want to create the empty variables too, and perform your own check on them, incase they are required variables. A quick way you could do this, if you had required variables is to prefix their form name with req_ and then if you encountered this prefix, make sure it's assigned, if not assign a boolean value that the form failed, and tell them what it was that was needed to be filled in and do not process the form any further.

The part that automatically creates the variable is the ${$name} = $value; reading this from the inner, {$name} is the form name the brackets convert it to it's name value, e.g. username, the outer $ is for the variable, so we get $username. Simple right? You could also do $$name but it's not the best practise, however I had to use it in the above for checking if the variable had been created, so it's the only time I'm letting it slide.

That's pretty much all I should need to explain, the rest just checks the variables are created and displays the information back, there's nothing too drastic about what it's doing. I just want to wrap this up, as I got to get back to doing my work.

So hopefully this helps a few people.

Cheers,

MC

 

 

 


Reply

Hercco
Thanks for the tip. That's something I've never came to think about probably because I've rarely had to process massive amounts of form input. Proof that's it's really worth reading these forums.


And where you commented that PHP 4 could fail, I don't think it will. I didn't test the code but I didn't notice anything unfamiliar to me and I've always developed in PHP 4.


Reply

TavoxPeru
First of all congrats, excellent topic, especially the one related with the variables variable. Now, i just test your code and it have an error because it doesnt shows the table with the submited data when you fill both fields, but dont worry its as simple as add an ! symbol wink.gif.

Simply change this line:
CODE
if (empty($$name))

with this one:
CODE
if (!empty($$name))

Best regards,

Reply

mastercomputers
Actually TavoxPeru,

I did notice that area failing on PHP 4.4.4 (Astahost's version which means the area I commented won't fail, but anything below PHP 4.3 could be of some concern), PHP 5 processes this correctly.

What you are suggesting isn't what the code reflects, what you're saying is, if the variable does exist (not empty means has something), then overwrite the already existing variable. This to me seems like register globals is on, or some automatic variable creation has already taken place, not the way I would configure php.ini nor would this be default, I'll try to dig into it more and see why the variables are already being created, as I might write a routine to remove this automation (I know this is what we wanted, but securing this area would be far better and just allowing ourselves to do this automation).

For now in PHP 4, just comment out if( empty(${$name}) ) { and the ending bracket } and it'll work as intended but will still overwrite existing variables, unless you think you can post the code to solve this before I get to work on it, then by all means do so.

I'll see what I can do, I'm not at home at the moment, and I'm not sure when I'll post the solution, I've also got a bit of code clean up that I did that I want to post too as well as more additions to this code.

Now the reason I'm sharing this area, is that I started working on a complete class for form processing, so that the class can handle all aspects of a form, including uploaded files, mailing, searching, registration, you name what the form does, and that is what I want to have in it. I'm also trying to incorporate ajax into the mix too, so that it will seem to process a lot smoother.


Cheers,


MC

 

 

 


Reply

TavoxPeru
The cPanel's phpinfo -PHP 4.4.4- shows that the register_globals is on, so i will test the code locally with PHP5 to verify if it works fine, i guess that this is the problem.

Related to the class that you are working on, I think that you have a lot of work to do wink.gif so, in case you need some help, please let me know to colaborate.

Best regards,

Reply

mastercomputers
Here's the updated version that works with PHP 4.4.4 and above with register_globals on. I've seperated the HTML and coding, so that it's not all mixed together, it's easier to work with it if it's seperated.

Here's the simple form (form.html)

CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-NZ">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Simple Login Form</title>
    </head>
    <body>
        <form action="login.php" method="post">
            <fieldset>
                <legend>Login Form</legend>
                <ol>
                    <li><label for="username">Username:</label> <input id="username" name="username" type="text" /></li>
                    <li><label for="password">Password:</label> <input id="password" name="password" type="password" /></li>
                </ol>
                <input id="login" name="login" type="submit" value="Login Now" />
            </fieldset>
        </form>
    </body>
</html>


Here's the PHP (login.php):

CODE
<?php
error_reporting(E_ALL);
if ( @ini_get('register_globals') )
{
    if ( isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']) )
    {
        exit('<h1>Sorry</h1><p>Not Allowed!!!</p>');
    }
    $protected = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
    $input = array_merge($_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
    foreach ( $GLOBALS['input'] as $k => $v )
    {
        if (!in_array($k, $GLOBALS['protected']) && isset($GLOBALS[$k]) )
        {
            unset($GLOBALS[$k]);
        }
    }
}
$allow = array('yourdomain.com');
$referer = '';
$created = '';
if ( !empty($_POST['login']) && $_POST['login'] == 'Login Now' )
{
    if ( !empty($_SERVER['HTTP_REFERER']) )
    {
        $GLOBALS['referer'] = current(array_splice(explode('/', $_SERVER['HTTP_REFERER']), 2, 1));
    }
    if ( !in_array($GLOBALS['referer'], $GLOBALS['allow']) )
    {
        exit('<p>Bad Referer</p>');
    }
    unset($_POST['login']);
    foreach ( $_POST as $key => $val )
    {
        if ( empty($GLOBALS[$key]) )
        {
            if ( !empty($key) && !empty($val) )
            {
                $GLOBALS[$key] = $val;
                if ( is_numeric($val) )
                {
                    $GLOBALS['created'] .= '<p>$' . $key . ' = ' . $val . ';</p>'."\n";
                }
                else if ( is_string($val) )
                {
                    $GLOBALS['created'] .= '<p>$' . $key . ' = \'' . $val . '\';</p>'."\n";
                }
            }
        }
    }
    echo $GLOBALS['created'];
}
?>


Now I'm using the GLOBALS variable a lot to just show the scope of the variables, that way you should understand that these variables are in the global scope range and not tied into specific functions.

The only major difference is that I'm emulating register_globals as off, which is the first instruction for this code, because it has to occur first to eliminate the variables being created. It's always a good idea to initialise your own variables rather than rely on them to be already created and initialised.

Now you are probably wondering, what if a variable you want created from your form doesn't get created because it's value was empty, well my method for determining whether a variable is required or not, I would prefix their names with req_ e.g. req_username and then I would create the functions needed to validate these required fields, I have a few validation routines including exact RFC specifications for email addresses as well as my more realistic email address validation routine, however since RFC states what can be valid, it's probably the better choice, my more realistic version is because some of the things they allow, just doesn't seem like what most email providers allow you to have anyways.

There's still more I want to show, including how to make sure a form was not tampered with, but that will probably come after the xmas season, so all the best and merry christmas.

Cheers,

MC

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Similar Topics

Keywords : quickly, create, form, variables, simple, form, variable, creation, referer, check, safe, guard, variables

  1. Permanent Variable
    (7)
  2. Send Php Variable To Javascript
    (5)
    Right i had a look across the internet as well as a search on here but you cannot search for
    anything less than 3 characters. But this is a really quick question. Would the following code
    allow me to send a php variable to a javascript? CODE $color = "green"; ?> BackColor= " ";
    ....
  3. Unexpected Error
    Undefined variable??? (2)
    Is this script correct? index.php : CODE     if (isset($_COOKIE ))           $_GET =
    $_COOKIE ;     else         setcookie("disp_name", Anonymous, date()+99); ?>              
    Display Name - DZN                                                                   
                    Dislpay Name: name="name" />                                                
         proccess.php : CODE      Proccessing Request...           Please wait...
        setcookie("disp_name", $_GET , date()+99); ?> main.php : CODE     function customErr....
  4. Php Long Variables
    How do you make them? (5)
    Don't ask why but I need to make a long variable that contains ' " ; and ) meaning I cannot
    use: CODE $var=('Test'); It will create an error. Here is an example of what I am
    talking about: CODE $var=("I want to use ' and " while allowing html and not using
    htmlspecialchars"); Basicly is what I want is a CODE echo This is some echo. I can use '
    " ) and; without using htmlspecialchars END; Is there a way to make a simalur code that works
    with variables? Do you get what I mean? That would really help me out. Thanks, Sparkx Note....
  5. Php Any Variable In String.
    (1)
    OK well I am making a new php program and I am trying to add bbcode to it. Anyway I was going to
    replace each thing by it self, but that could cause errors. Anyway is there a way to make a variable
    be anything? Here is an example: CODE This is the bbcode: Hey In my php: $bbcode = array(" ");
    $html = array( " "); $topic_content = str_replace($bbcode, $html, $posted_bbcode); So I want $a
    to be any variable but the same variable as used before. Do you get what I am saying? It is a little
    confusing but basicly what is the best way to make bbcode? It may not even inv....
  6. Automated File Structure Creation Script
    As Requested By Mark420 (3)
    While chatting with Mark420 today on the shoutbox, he mentioned that he was looking for a script to
    create his entire folder structure with just a click of a button. For example, he wanted the
    following folders created in his root folder by just clicking submit. /images /images/thumbs
    /images/icons /css /javascripts /content /content/articles /content/tutorials Presumably this
    would be used for some type of installation system or other quick server setup situation. Anyhow
    here is what I threw together for him: /* ********************************************....
  7. Variable From Line Further Then Current Line?
    (13)
    Hello, Is it in some way possible to load a variable that further then the current line in the
    script? I don't know if you know what i mean so I'll try to point it out in the script
    below. CODE 1 2      echo $var1; 3      # $var1 needs to be loaded from foo.php 4     # Lets
    say i want $var1 to be echoed in $var1 5       - - - -       bla bla bla 55      - - - -
    56      switch($_GET ) { 57          case "foo": 58              include("foo.php");
    59              #- - - - from foo.php - - - - 60                   $var1 = "what ever you want";
    61           ....
  8. User Authentication Session Handling Problems
    Authorization server variables not staying across pages (14)
    This is quite a bit of problem I am facing, and I cannot point exactly where I am going wrong. I
    have been lurking around here at the Asta Host forums with regard to login and user authentication
    scripts and I have got as far as this: - Starting a session - Registering a session variable -
    Using the variable to check if the user is authenticated or not. - Authenticating the user through
    MySQL database - Logging of the user, by setting the session variable to un-authenticated I have
    been able to achive the following things too that I think is not related to this proble....
  9. How To Reset The Server Variable Php_auth_user
    (9)
    Hi, i'm developing a web application which obviously requires a log in/log out script that i
    just implementing but i dont know why the log out script dont work fine. The problem is related
    with the server variable $_SERVER which remains set even when in the log out script i unset it with
    the unset() function. Does someone knows how can i reset or clear the server variable $_SERVER ???
    Best regards, ....
  10. Help: $_post Variable For Options From Select Types?
    (6)
    I want to know if there is a way to get the variables in $_POST for the options (not just the
    selected ones, but the unselected ones as well) of a type. Objective: Creating an application for
    my school. Issue: I am successful in receiving all the variables from the forms except the ones
    added to the options of a type. Just wanted to know what is the variable to access the options of
    types. Here is what I am trying to do with it: View Page If the server is down or unable to
    load file, here is the script: CODE      Malden High School va....
  11. Php : Variables Included Dont Work In Functions
    Variables from Included files dont work (4)
    Today, I came up with this strange PHP behaviour. Just wanted to know if anyone has any
    suggestions! I make a common variable/function file called config.php. I put in my generally used
    functions in it. Suppose this is my file // -----VARIABLES --- // $a=10,$b.... //
    -----FUCTIONS--- // function doit() { print "A value is " . $a; } ?> Here, suppose we execute
    this file directly. Since A has a global scope, it does work perfectly. But if this same file is
    imported in another file say, mainfile.php // -----VARIABLES --- // $c,$d.... include
    'config.ph....
  12. Php Variable Concatenation
    Something New I learned Today! :P (7)
    I was coding one of my php page today, when I realized that I had to add multiple values to a
    variable (now that I think of it, a solution with arrays is possible too). But, the problem is that
    I have to add them in different parts of the code, so the new line that defines the variable will
    cover up the previous one. I played around with the code, and I finally got this solution:
    $message = "test1"; $message .= "test2"; $message .= "test3"; echo $message; By adding a dot in
    front of the = sign, I could concatenate the previous value with the new one and put them i....
  13. Question On Depecrated Tracking Variables In Php
    (2)
    It seems I can no longer use the line... it returns an error saying this: Warning: is no
    longer supported - please use the track_vars INI directive instead in on line 1 So what do I
    replace the track_vars command with? O_o Any help would be appreciated.....

    1. Looking for quickly, create, form, variables, simple, form, variable, creation, referer, check, safe, guard, variables






*SIMILAR VIDEOS*
Searching Video's for quickly, create, form, variables, simple, form, variable, creation, referer, check, safe, guard, variables
advertisement




Quickly Create Form Variables - simple form, variable creation, referer check, safe guard variables



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE