Could I get some advice/help building a booking form in PHP?

sevenupcan

Junior Member
Hi there,

I'm trying to build a booking form but I'm having difficulty understanding how to get it functioning properly.

You can view what I have so far at JJN Amish Tours - Booking Form

[EDIT] The link may have not been working as I took some code out, sorry about that. It should work now.

What I'm not sure of is how to get it to submit to a PayPal URL if the radio button for PayPal is selected and submit to another page is the radio button 'Cheque' is selected.

I'm using PHP how would I achieve this with conditional statements?

Many thanks for your help.
 
Hay sevenupcan

Not sure if you have this sorted or not but if not lets run through it.

At the top of the page you want to see if the page has all ready been submitted.

We then check the post varaible to see what it is, we then redirect the user to the right page.

So:

<?php
if(isset($_POST['paymentType'])){
if($_POST['paymentType']=="paypal"){
header("Location: http://www.yoursite.com/paypal-page");
}elseif($_POST['paymentType']=="cheque"){
header("Location: http://www.yoursite.com/cheque");
}
}else{
?>

<doctype...
<html>
<head>
<title></title>
</head>

<body>
//page content goes in here.
</body>
</html>

<?php }?>

If you get an error let me know as I just wrote that off the cuff.

Jaz
 
You need to use javascript in combination with your form.

First clear the action="" attribute in the <form> tag, then add an onClick="" action to the submit button.

When the button is clicked call a javascript function, something like "setTarget()" which sets the form action="" parameter based on the radio button that is checked. Something like

if(myform.mycheckbox['paypal'].checked){
document.myform.action="PAYPAL URL";
} else {
document.myform.action="CHEQUE URL";
}

myform.submit();


sorry for being so crude, I should really take more time and code it up. Let me know if you get stuck.

p.s. something like this: CodeToad - Multiple submit buttons on a single form.

The problem with Jazajay's solution is that none of the POST parameters will be carried to the page you are redirected. So all Form input will be lost.

Darren
 
Hi forgive me. I did reply but I wasn't aware my post didn't submit properly. Not sure what happened there.

Jazajay - Thank you so much for this technique. I wasn't quite sure how to accomplish this but I have reached a solution.

I'm really glad you guys could help me, I appreciate it.

This is what I have so far...

Code:
// Check from has been submittedif(isset($_POST['submit'])) {    $errors = array();    $customer_name = $_POST['customer_name'];    $customer_email = $_POST['customer_email'];    $spam_question = $_POST['spam_question'];        // Start validating field inputs    if($customer_name == "") {        $errors[] = "The name field is empty";    }        if($customer_email == "") {        $errors[] = "The email field is empty";    }        if(!stripos($customer_email, '@')) {        $errors[] = "The email address was not valid";    }        if($spam_question != 4) {        $errors[] = "The spam question was answered incorrectly";    }        // Send email message    if(count($errors) == 0) {        $sendto = "[email protected]";        $title = "Contact Form";        $name = $_POST['name'];        $email = $_POST['email'];        $why = $_POST['why'];        $comment = $_POST['comment'];$message = <<<DATA<strong>Name:</strong> $name <br><strong>Email:</strong> $email <br><strong>Why:</strong> $why <br><strong>Comment:</strong> $comment<br>DATA;        if(mail($sendto, $title, $message)) {              // Validation has passed            $success = true;        }                // Validation has failed        else {                $success = false;        }    }        // Validation has failed      else {            $success = false;    }}// Check from has been submitted if(isset($_POST['submit'])) {        // If validation has worked and there are no errors process form    if($success == true && count($errors) == 0) {                // Display PayPal instructions        if($paymentType == 'paypal') {            echo '<h2>Display PayPal instructions here.</h2>';        }                // Display instructions for paying by cheque        if($paymentType == 'cheque') {            echo '<h2>Display Cheque instructions here.</h2>';        }    }        // If there no errors and but validation/email failed and form was submittted then display last resort error message    if(count($errors) == 0 && $success == false && isset($_POST['submit'])) {        echo '<h2>There was a problem with our form. Please email us directly via [email protected].</h2>';    }        // If validation failed and there are errors and form has been submitted show errors    if($success == false && count($errors) > 0 && isset($_POST['submit'])) {        echo "<ul>";        foreach($errors as $e) {            echo "<li>$e</li>";        }        echo "</ul>";        include('forms/order-config.php');    }}// Code when user first visits formif(!isset($_POST['submit'])) {include('forms/order-config.php');}
I'm really sure I could clean up the script but I'm not sure how. Could anyone give some tips?

Now too look at getting javascript to validate the page too for a better user experience... thanks Darren.

Thanks again.
 
sevenupcan said:
Now too look at getting javascript to validate the page too for a better user experience... thanks Darren.

Hi sevenupcan,

My post was to provide a possible solution to your scenario i.e post the form to a different URL based on which radio button was selected, not for validation.

Looking at your code it looks like your validation is currently done via PHP, which is great. Any data that is posted to a server should be validated server side, ALWAYS. So leave this in, although it does need to be improved upon.

For example, the following fuction allows you to properly validate the structure of an email address;

PHP:
function validate_email($string)
    {
     if($this->is_empty($string)){ return false; }
     else{
         $reg_ex = "/"                       // start pattern
                  . "^[a-z0-9_-]+"           // valid chars (at least once)
                  . "(\.[a-z0-9_-]+)*"       // dot valid chars (0-n times)
                  . "@"                      // at
                  . "[a-z0-9][a-z0-9-]*"     // valid chars (at least once)
                  . "(\.[a-z0-9-]+)*"        // dot valid chars (0-n times)
                  . "\.([a-z]{2,6})$"        // dot valid chars
                  . "/i";                    // end pattern, case insensitive
         return preg_match($reg_ex, $string);
     }
    }

At the moment your code simply looks for an @ sign in the string, this is not secure at all. The other validation done i.e. == "" is really bad, you should have a function such as;

PHP:
function validate_general_text($string)
 {
  if($this->is_empty($string)){ return false; }
     else{
         $reg_ex = "/^[0-9a-zA-Z\.\-\ ()&;]+$/";
         return preg_match($reg_ex, $string);
     }
 }

This would allow you to stop a user from inserting special characters that they dont need. Which may be quite "tight" but can be loosened up by modyfing the regular expression.

Another approach is to clean the input and strip anything malicous such as "<script>" tags, if you need example of this code let me know.

The mail code also needs a lot of work, you ahve no header tags which most certainly means that any emails sent by this system will be rejected as spam by most corporate email systems, as well as many other problems. In this case, the best idea here is to use a class such as phpmailer.class.php which you can find information on here;

PHPMailer | Get PHPMailer at SourceForge.net

I was going to say that you may need to make some changes to the class such as change the split() functions for explode() etc as these are deperciated now but it looks like they have released a PHP5 version :) great!

Aside from your PHP validation and the email, as you mention Javascript validation would enhance the user experience. This is true and it would also provide an additional level of parsing. However, javascript validation should never be solely relied upon. i.e. whats to stop me copying the page and removing the javascript then sending whatever I like with the form. Or simply turning off javascript in my browser. Its as easy as that to avoid this type of validation. So always include proper server side validation i.e. PHP.

Overall, It looks like you have changed your solution so that you do not need to post to different pages anymore? It looks like you simply take the information from the form that was posted, email this to someone and then display two links on the page for a user to click. One that shows the cheque instructions and one that shows the paypal instructions.

To be totally honest and at the risk of souding cheeky, it looks like you copied and pasted this code from the web. Although, its a great basis for you to build upon.

Darren
 
I just noticed that these functions include;

if($this->is_empty($string)){ return false; }

is_empty is another function of the class that I have these functions in, all it does is check that the string contains some chars. Easy enough to add in.
 
Hi Darren,

Your good! Very good! I don't have a any experience in PHP and understanding how logic works has been quite hard for me. So yes I have copied this script from a tutorial and adapted it to suit my own needs. So you weren't being cheeky at all, your quite right. :)

I was aware of using == "" to determine an empty field and have been meaning to change this. Thanks so much for your suggestions to help improve my validation techniques further.

When I first created this post the biggest thing I had trouble grasping was how I could accomplish the radio button functionality. But now I've realised there is a lot more I must do to make sure this form is safe and performs well.

Something else I've had to add into the form is a function which calculates the total cost of the order. I've never created my own function before so please correct me if I'm not doing things the best way possible.

PHP:
$tour_name = $_POST['tour_name'];
$qty = $_POST['qty'];
$price = $_POST['price'];
$fee = 250;

function doTotal(){

    global $qty;
    global $price;
    global $fee;
    
    if ($qty==1) {
        $total = ($qty * $price) + $fee;
    } else {
        $total = $qty * $price;
    }
    return $total;
}

$total = doTotal();
One thing I have noticed is that my variables which are posted from the page before aren't being echoed when the user reaches the PayPal/Cheque section of the form and I'm not sure why. It's almost as if they are being forgotten when the form is submitted. Do I need to re-include these values to carry them on?

I decided to change my solution from posting to a new page to simply changing the code displayed because I had a lot of others tasks to figure out on my plate and felt confident this way. I think though that if I get time I will change this.

So to re-iterate.I know next to nothing of PHP and JavaScript but am willing to learn. My main skills are in CSS and HTML. I am very grateful for everyone's help.
 
Hi sevenupcan,

Sorry I have been really busy and have not been around the forums.

Your code above is absolutely fine but I have re-written it just to give you some ideas about other things you can do...

PHP:
// These functions can potentially be in another includes file or class
function validate_numeric($testme) {
 $reg_ex = "/^[0-9]+$/";
 return preg_match($reg_ex, $testme);
}
function doTotal($qty, $price, $fee = 250){
 $total = $qty * $price;
 if($qty == 1){ 
  $total += $fee;
 }
return $total;
}
// Process the cost
$totalcost = 0;
// first validate that the qty and price are only numerical as these have been "posted"
if(!validate_numeric($_POST['qty']) || !validate_numeric($_POST['price'])){
 // do something here to inform the user that invalid data was entered
 // you could redirect the page, display error message etc
} else {
 $totalcost = doTotal($_POST['qty'], $_POST['price']);
}

You might notice that there are 2 big changes with the method doTotal(), one is that I have removed the need to announce the variables as global and the other is that I have added this "$fee = 250" in the method parameters.

Adding a default value for a variable in the method call means that you dont need to pass it in every time. You can now call doTotal in two ways ..

PHP:
$total = doTotal(1, 10); // this means that fee will be 250 by default
 
$total = doTotal(1, 10, 450); // this means we just set "fee" to 450.

The reason to remove the need for global variables is that with your doTotal method, you will always need to have the variables $fee, $price and $qty defined in your script. Whereas, as you can see in my example usage above, you could pass any parameters you like in.

sevenupcan said:
One thing I have noticed is that my variables which are posted from the page before aren't being echoed when the user reaches the PayPal/Cheque section of the form and I'm not sure why. It's almost as if they are being forgotten when the form is submitted. Do I need to re-include these values to carry them on?

This is the exact problem that I mentioned above, and why I mentioned that Jaz's solution wont work.

When you POST a HTML form the values from the form are entered into the $_POST array and sent to the server. If you then go to another link or page, these posted values are lost. You either need to repost manually using something like cURL or fsockopen() which is just a pain in the butt and a little too much.

If you "pass on the values" again via GET instead of POST i.e. adding them to the url like mypage.php?value1=x&value2=x this is not a good solution when working with payment processors since browsers have limitations to the length of a string. You also need to encode the URL properly.

So, my original solution is still the one that I would go for. I have worked with paypal intergration a lot and it is very easy to work with but I would always POST the data.


One other solution which might be the best for you, is to include the values that were posted into another form with hidden fields (final confirmation page comes to mind) and then have that post to paypal or whatever you need.

Something like

1. (payment.php) User -> Payment Page (selects payment type here ex paypal or cheque)
2. (payment.php) User -> clicks on Send which takes them to
3. (confirm.php) Details in the POST data are entered into hidden fields in another HTML Form and the URL for the FORM is changed based on the selection that the user made (cheque/paypal)
4 (confirm.php) User clicks on Submit/Send/Confirm
5. User either arrives at paypal or the cheque page.

Darren
 
Back
Top