form process using php - php

for form process what's better ? (secure/fast)
Layout Form :
<form id="myForm" name="frm1" action="insert.php" method="post">
<textarea name="content" id="content" cols="35" rows="5"></textarea>
<INPUT type=submit value="submit" name=submit></form>
Insert php :
<?php
if (( 'POST' == $_SERVER['REQUEST_METHOD'])) {
//php validation code
} else {
exit();
}
?>
Or
<?php
if (!isset($_POST['submit'])) {
//php validation code
} else {
exit();
}
?>

The second one, definitely. It's more readable. and even more logical
<?php
if (isset($_POST['submit'])) { //php validation code
//do something
}
else
{
exit();
}
?>

You should generally be checking whether or not the data exists that you are going to process. Along those lines, your second method is preferred, but don't assume people are going to click your submit button.
I have a couple other notes for you while I'm at it. You should really close your <input> tag with /> at the end of it.
Also, while you can make comparisons like ('POST' == $_SERVER['REQUEST_METHOD']), writing them in that order makes little sense. Flip it around like this: ($_SERVER['REQUEST_METHOD'] == 'POST')

Speed is irrelevant here. In terms of security these two cakes of code are diferents...
if (( 'POST' == $_SERVER['REQUEST_METHOD']))
{//php validation code
}
else
{exit();}
Here you are testing if the request method of your page is post, and then you do your validations.
if (!isset($_POST['submit']))
{//php validation code
}
else
{exit();}
Here you are testing if there is a value in the post values that has the key "submit". You are assuming that a field has this name, but that is not necessarily true. You can have post values with any field named "submit".
The real security concern here are your validation tests.

if (!isset($_POST['submit']))
{//php validation code
}
else
{exit();}
Second one makes more sense to me.

The second answer is the best, because you're only checking on your submit button. The other one is checking for just a post .

Related

PHP Redirect to new page after form submission

I have a form, which redirects the user to "page1.php" after the form is submitted. What I want to do is to redirect the user to "page2.php" after the form is submitted, but I need to make sure that the POST request was sent. Example:
<form action="page1.php" method="POST">
<input type="text" name="username" />
<input type="text" name="age" />
<input type="submit" value="" />
</form>
When the user clicks on Submit, it redirects him to page1.php. I want to redirect him to page2.php, but I need to make sure that the data is sent to the server. I can't use AJAX. Is there any way to do it with cURL or something like that? Any examples?
Thanks!
I guess this works !!
In page1.php
<?php
//do establish session
//and check for the input fields obtained via $_POST
if(isset($_POST['name_of_your_field']) && !empty($_POST['name_of_your_field'])){
if(!mail($to,$subject,$message)){
header('location:form.php?msg=error');
}else{
header('location:page2.php?msg=succes');
}
}
?>
You can check if the POST request was sent with something like:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// do something...
}
You can create a hidden input in your form and send additional info about the form that is submitted, e.g. action.
Inside you will do your magic and redirect user with:
header('Location: page2.php');
exit();
In your 'page1.php' processor, add a 'header' redirect to 'page2.php'.
header("Location: page2.php");
exit;
you could do a check if query is complete
example
<?php
$query=mysqli_query(".......your query statement")or trigger_error(mysqli_error());
if($query){
header("Location:page2.php");
}
else{
die('error');
}
?>
In your situation, you can just simple check for the posted data. Like
$username = $_POST['username'];
$age = $_POST['age'];
if($username&&$age){ /* This is to check if the variables are not empty */
// redirect to page2
}
It is logical that if those are not empty, meaning they are posted. Even if they are empty, as long as you get there, that means it was posted. There is no need to check if posted or not, what needs to be checked was, if posted data was there.
I hope I made it clear. ^_^ but making sure is not bad at all. Happy coding friend.

Simple PHP form submitting - what's wrong with this conditional if and logical &&?

The problem:
if i submit the html form and a textbox is left blank
then i don't want it to proceed to the echo segment,
but the problem is it does proceed.
<?php
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
{
?>
<form name="form2" method="post" action="<?php echo($_SERVER["PHP_SELF"]);?>">
<div>
Write a planet name: <input name="planet" type="text"><br>
Its moon: <input name="moon" type="text">
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
}else{
echo("Planet: ".$_POST['planet']. "<br>");
echo("Moon: ". $_POST['moon'] . "<br>");
echo "Successful.";
}
?>
As you know isset() determines if a variable is set and not null but doesn't check if it's empty.
While logic seems my if statement, I modified it from:
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
To:
if(!isset($_POST['submit']) && ($_POST['planet']=='') && ($_POST['moon']==''))
if(!isset($_POST['submit']))
if(!isset($_POST['planet']) && !isset($_POST['moon']))
if(empty($_POST['moon']) && empty($_POST['planet']))
and none of them worked.
So am I doing something wrong with my if statement? how can I not let it proceed to the Else segment while a textbox is empty? without more if and no nested statements please.
When you submit a form, the submit button will be set, so isset($_POST['submit']) will be true, therefore !isset($_POST['submit']) will be false.
When doing an if statement with the && comparison, all conditions must be true in order to execute that block of code, otherwise it goes to the else statement.
What you need to do is actually have 2 comparison checks. Once to see if the form was never submitted and one to see if it was, and the text boxes are empty:
<?php
// Check if form was submitted
if(!isset($_POST['submit'])
{
// Display the form
}
else
{
// Form was submitted, check if values are empty
if(trim($_POST['planet'])=="" || trim($_POST['moon'])=="")
{
// One or more value is empty, do something
}
else
{
// Process form
}
}
?>
I realize you are trying to avoid nesting, but in order for the logic to flow smoothly, and the code to remain readable, this is a necessary evil.
Change
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
To
if(!isset($_POST['submit']) || (empty($_POST['moon']) || empty($_POST['planet'])))
Then if you submit with either textbox being empty, it will redisplay the form. If both textboxes have been filled in, you will see the else part.
Your problem is that if(!isset($_POST['submit'])) is always set when the form is submitted - so that is true. You also might want to change the && to ||. By using || you say OR, so say if anyone is empty, then do this, else do that.

use php to change a html elements inner text

I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.

Form to form with PHP

I am trying to create a multi steps form where user will fill the form on page1.php and by submitting can go to page2.php to the next 'form'. What would be the easiest way?
Here is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
?>
<form id="pdf" method="post">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
if ($_POST["pr_name"]!="")
{
// data collection
$prname = $_POST["pr_name"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, enddate, sel, content) VALUES(?,?,?,?)");
if (!$stmt) echo "\nPDO::errorInfo():\n";
$stmt->execute(array($prname,$prend, $prmenu, $prcontent));
}
// somehow I need to check this
if (data inserted ok) {
header("Location: pr-pdf2.php");
}
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
I have changed following Marc advise, but I don't know how to check if the SQL INSERT was OK.
Could give someone give me some hint on this?
thanks in advance
Andras
the solution as I could not answer to my question (timed out:):
Here is my final code, can be a little bit simple but it works and there are possibilities to check and upgrade later. Thanks to everyone especially Marc.
<form id="pdf" method="post" action="pr-pdf1.php">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
Email subject:<input type="text" name="pr_subject" placeholder="must be filled..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
include_once "ckeditor/ckeditor.php";
$CKEditor = new CKEditor();
$CKEditor->basePath = 'ckeditor/';
// Set global configuration (will be used by all instances of CKEditor).
$CKEditor->config['width'] = 600;
// Change default textarea attributes
$CKEditor->textareaAttributes = array(“cols” => 80, “rows” => 10);
$CKEditor->replace("pagecontent");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// data collection
$prname = $_POST["pr_name"];
$prsubject = $_POST["pr_subject"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, subject, enddate, sel, content) VALUES(?,?,?,?,?)");
// error checking
if (!$stmt) echo "\nPDO::errorInfo():\n";
// SQL command check...
if ($stmt->execute(array($prname, $prsubject, $prend, $prmenu, $prcontent))){
header("Location: pr-pdf2.php");
}
else{
echo"Try again because of the SQL INSERT failing...";
};
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
Add the attribute action with the url you'd like to go to. In this case it'd be
<form id="pdf" method="post" action="page2.php">
EDIT: i missed you saying this method doesn't work. What part of it doesn't work?
You should keep the action to the same script, so the POST action is still performed and then redirect with header("Location: page2.php"); when the processing is done.
A basic structure like this will do it:
form1.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... process form data here ...
if (form data ok) {
... insert into database ...
}
if (data inserted ok) {
header("Location: form2.php");
}
}
?>
... display page #1 form here ...
And then the same basic structure for each subsequent page. Always submit the form back to the page it came from, and redirect to the next page if everything's ok.
You're probably better off separating the php code from the form. Put the php code in a file called submit.php, set the form action equal to submit.php, and then add the line header('Location: whateverurl.com'); to your code.
The easiest way is to post it to form2.php by giving the form the attribute action="page2.php". But there's a risk in that. It means that form2 must parse the posted data of form1. Also, if the data is wrong (verification) form1 must be shown instead of form2. This will make your code over complicated and creates dependencies between the two forms.
So the better solution (and quite easy as well) is to implement the post-redirect-get pattern.
You post to form1, verify all data and store it. If the data is ok, you redirect to form2. If the data is wrong, you just show form1 again.
Redirecting is done by a header:
// Officially you'll need a full url in this header, but relative paths
// are accepted by all browsers.
header('Location: form2.php');
Save already posted fields in hidden input fields, but don't forget to validate them every time user submits another step of the form as the user may change hidden inputs in source code.
<input type="hidden" name"some_name" value="submitted_value"/>
There are several ways handling the submitted data while jumping between steps.
You will find your reasons for /against writing data to session, database, whatever... after each step or not.
I did following approach:
The form includes always a complete set of input elements, but on page #1 the step-2-elements are hidden ... and other way round.
I built a 6-step-wizard this way. One large template, some JS /Ajax for validating input, additional hidden inputs that hold current step-ID and PHP deciding, which fields to show or hide.
The benfit in my opinion: Data can easily be saved completely, as soon as input is alright and complete. No garbage handling, if users abort after step 1.
I would store it all in a session array (or sub array)
a really rough example where I'm saving all the form names to an array (to be checked later of course):
<?
foreach($_POST as $k => $v){
$session['register'][$k]=$v;}
?>

Surely a foolish error, but I can't see it

I have a form (greatly simplified):
<form action='http://example.com/' method='post' name='event_form'>
<input type='text' name='foo' value='3'/>
<input type='submit' name='event_submit' value='Edit'/>
</form>
And I have a class "EventForm" to process the form. The main method, process() looks like this:
public function process($submitname=false){
$success=false;
if ($submitname && isset($_POST[$submitname])){ //PROBLEM: isset($_POST[$submitname] is always FALSE for some reason
if($success=$this->ruler->validate()){//check that dependancies are honoured and data types are correct
if($success=$this->map_fields()){//divide input data into Event, Schedule_Element and Temporal_Expression(s)
$success=$this->eventholder->save();
}
}
} else {//get the record from the db based on event_id or schedule_element_id
foreach($this->gets as $var){//list of acceptable $_GET keys
if(isset($_GET[$var])){
if($success= $this->__set($var,$_GET[$var])) break;
}
}
}
$this->action=(empty($this->eventholder->event_id))? ADD : EDIT;
return $success;
}
When the form is submitted, this happens: $form->process('event_submit'); For some reason though, isset($_POST['event_submit']) always evaluates to FALSE. Can anyone see why?
ETA: after working through the suggestions, it appears that JQuery.validate() is having an unexpected effect on the form submission. All the fields are submitted except the submit button. This appears to be the fault of this JQuery:
$("form[name='event_form']").validate({
submitHandler: function(form) {
form.submit();
}
}};
Any thoughts on how to make sure the submit button value gets sent?
Change your JQuery to this:
$("form[name='event_form']").validate({
submitHandler: function(form) {
$("form[name='event_form'] input[name='event_submit']").click()
}
}};
do a print_r on the $_POST array and see whats being submitted - it should output the whole array e.g.
print_r($_POST);
I broke your code out into a even simpler PHP file:
<?php
function process($submitname=false){
echo 'erg<br>';
$success=false;
if ($submitname && isset($_POST[$submitname])){ //PROBLEM: isset($_POST[$submitname] is always FALSE for some reason
echo 'bwah';
}
}
process("event_submit");
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="event_form">
<input type="text" name="foo"/>
<input type="submit" name="event_submit" value="Edit"/>
</form>
"erg" and "bwah" displayed as expected. Make sure that your class is being instantiated properly, that you're actually passing "event_submit" to it, and that some other piece of code isn't wiping out $_POST before you get a chance to read it.

Categories