liewl
liewl

Reputation: 4071

Using same php file to show form and receive the form's data

I have a php page that generates a form. The action attribute of the form is the page itself. After the user submits the form, the same page is loaded, but this time a POST variable is set, so the page runs another script to deal with the incoming data from the form. I do this by using a conditional fork:

if(isset($_POST['var'])){
    generate form
}else{
    insert $_POST data into database
}

I'd like to know if this is ok or a bad idea.

Upvotes: 1

Views: 456

Answers (3)

Sid_M
Sid_M

Reputation: 399

I agree with Ignacio. Other than that it looks like a fairly standard approach if you don't need more complexity. One very important thing: make sure you are validating and sanitizing that data before it goes into the database.

Upvotes: 2

bcosca
bcosca

Reputation: 17555

You might even want to go to the extent of checking whether the data was submitted thru AJAX to differentiate it from a regular form submission:

if ( $_SERVER['X_REQUESTED_WITH']=='XMLHttpRequest' )
  // AJAX

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

The bad part is setting the action attribute to the script. Omitting it completely indicates to the browser that it should be posted to the same URL.

Upvotes: 1

Related Questions