Monday, 24 February 2014

How to Create a Contact Form for Your Website in an Easy Way : A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (10)


(For the latest PDF files Merger Software please have a look at the top of the left margin, inside the red box.)
Continues From Part 9
In the previous post I got  the IP of the visitor and displayed it on the bottom of the contact page as a courtesy. I also put it inside the messages they might send for me. To keep the IP of any visitor who might send a message or just click on my page, I keep a record of IP's of all the visitors. Allow me to advance further and add more elaborations to my contact form.
Remember that I am not addressing any security issue such as preventing SQL Injection or making PHP codes more accomplished by using advanced functions. Sometimes they are controversial even among the PHP experts. I have done many computer codes from Assembly and machine codes, Fortran, dos to Eifel. Now I only do assembly, C, and Java and sometimes Windows C++. I do not like to become engaged in PHP. See, it is advised to change $Name = $_POST['Name'] to $Name = filter_input(INPUT_POST, 'Name'). This works. but a similar trick, filter_input(INPUT_SERVER, "REMOTE_ADDR") in place of $_SERVER["REMOTE_ADDR"] does not work, uniformly (might work intermittently; mostly dispatches Server Error). It is due to the fact that as you might notice, parameters and references are not uniform. Hence, the interested readers might like to study manuals deeper.

How to make a simple basic database of visitors' IP's?

How to collect (put) visitors' IP records in a text file?

It is usual that web servers use MySQL to gather information in a systematic manner. I make a simple text to keep records of visitors IP. Please remember line (217) of contact form in previous post. This is where the visitors get their IP's upon landing on the page and the best time to catch a record of the visit. Therefore, add the following snippet after this line and before line (218). Hence Line (218) will become Line (228)

 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 $ip_file = 'save_ip.txt';
 $date_ti = date('Y-m-d H:i:s');
 if(file_exists($ip_file)){
       $file_content = file_get_contents($ip_file);
       file_put_contents($ip_file, $file_content . "\r\n" . $date_ti . "\t||\t" . $visitor_ip);  
 }
 else{//create text file and put header for the table
      file_put_contents($ip_file, "Date and Time" . "\t||\t" . "Visitors IPs"
               . "\r\n" . $date_ti . "\t||\t" . $visitor_ip);
 } 

(Download PHP code in Zip format here or open the code in text format here). On each landing, the code snippet checks if the text file  'save_ip.txt' is already created and exists. If it is the first ever reference to this file it creates the file and puts a simple header for its columns. Then goes to the next line and puts the date, time and IP of the first visitor in the second row. However, if the text file already exists code snippet gets contents of the text, rewrites it. Then goes to the next line and adds one new record to previous records. I tried to add some formatting and vertical bars to separate columns, nevertheless, readers might like to impose their own ways of doing that. Remember that, at the end, one needs to use MySQL to accumulate these information or to invoke third party tools and subscribed services.
Also, it is worth mentioning that one needs to become familiar with PHP tabs, new line, carriage-return, end-of-line and so on. I used the familiar "\t", "\r", "\n" for purposes of this article, but frequently, they do not behave in such a simple way as they should.
You can learn about PHP date and time formats, too, from their wikis.
After two visits you can open the text file in your browser to watch records of visitors IP's or you can download and read them with a text editor, or other ways that your web server allows.


Please check permissions (three digits numbers such as 644) for the created file not to be accessible to unwanted visitors. (In the last snap-shot IP's painted with wrong numbers for privacy of visitors.)
Please click here to open the contact form and then open the saved text to see that your own IP has been added (many times a day I renew the text to keep privacy of previous visitors).

Download this tutorial as PDF format here
Download part 1 to part 10 as PDF format here

Monday, 10 February 2014

How to Create a Contact Form for Your Website in an Easy Way : A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (9)

(For the latest PDF files Merger Software please have a look at the top of the left margin, inside the red box.) 
Continues From Part 8

How to get IP addresses of visitors.

As promised, in this refinement I'll get the IP address of the visitor and show inside a formatted division to visitors who come to the contact page. You can use the code inside any other page of your choice. First let me put the final code here for your consideration  (download PHP code in Zip format here or open the code in text format here).

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
<!DOCTYPE html>
<!--
Created by Peter Joneses 10 February, 2014
www.codesforus.blogspot.com 
copyrights
-->
<html>
    <head>
        <title> Demo-Final: Dysprosium Contact Form, Get IP</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <script type= "text/javascript">
            var RecaptchaOptions = {
                theme: 'white'
            };
        </script>
        <style>            
            #contact-wrapper {
                margin: 20px auto;
                border: 2px solid #ccc;
                border-radius: 5px;
                padding: 20px 50px 20px 50px;
                background: transparent;
                width: 600px;
            }
            #contact-area {
                width: 600px;
                margin-top: 25px;
            }            
            #contact-area label {
                float: left;
                margin-right: 15px;
                padding-top: 5px;
                width: 100px;
                text-align: right;
                font-size: 100%;
            }
            #contact-area input, #contact-area textarea {
                margin: 0px 0px 10px 0px;
                border: 2px solid #ccc;
                border-radius: 5px;
                padding: 5px;
                width: 471px;
                font-family: Helvetica, sans-serif;
                font-size: 110%;
            }
            #contact-area textarea {
                height: 90px;
            }
            #contact-area textarea:focus, #contact-area input:focus {
                border: 2px solid #900;
            }
            #contact-area input.submit-button {
                float: left;
                cursor: pointer; 
                margin-top:10px;
                margin-left:112px;
                background: transparent;
                width: 100px;
                font-size: 100%;
                color: #024d8e
            }
            #contact-area input[type="submit"]:hover{
                border: 2px solid #900;
            } 
            #recaptcha_widget_div {
                margin-top: 20px;
                margin-bottom: 10px;
                margin-left: 112px;
            }            
            #recaptcha_fail_div {
                margin-top: 20px;
                margin-bottom: 10px;
                margin-left: 112px;
                border:medium groove #A00;
                border-radius: 5px;
                border:medium groove #A00;
                padding:3px;
                background-color:transparent;
                width:350px;
                color:#900;
                font-weight:bold;
                font-size:80%;
            }      
        </style>
    </head>
    <body>
        <div id="contact-wrapper">
            <div id="contact-area">
                <form method="post" action="">
                    <label for="Name"><span style="color: red; font-size: 100%">*&nbsp;</span>Name:</label>
                    <input type="text" name="Name" id="Name" value="<?php echo isset($_POST['Name']) ? $_POST['Name'] : '' ?>" />
                    
                    <label for="City">City:</label>
                    <input type="text" name="City" id="City" value="<?php echo isset($_POST['City']) ? $_POST['City'] : '' ?>" />
                    
                    <label for="Email"><span style="color: red; font-size: 100%">*&nbsp;</span>Email:</label>
                    <input type="text" name="Email" id="Email" value="<?php echo isset($_POST['Email']) ? $_POST['Email'] : '' ?>" />
                    
                    <label for="Subject">Subject:</label>
                    <input type="text" name="Subject" id="Subject" value="<?php echo isset($_POST['Subject']) ? $_POST['Subject'] : '' ?>" />
                    
                    <label for="Message"><span style="color: red; font-size: 100%">*&nbsp;</span>Message:</label>
                    <textarea name="Message" rows="20" cols="20" id="Message"><?php echo isset($_POST['Message']) ? $_POST['Message'] : '' ?></textarea>
                    
                    <p style="margin:20px auto 10px 112px;">Fields shown by <span style="color: red; font-size: 100%">*&nbsp;</span> are required.</p>
                        <div id="recaptcha_widget_div">
                            <?php
                                require_once('recaptchalib.php');
                                $publickey = "6LcJA-sSAAAAAPVPHLiHjGTlkhuWhLX2Luj3hS85"; // you got this from the signup page
                                echo recaptcha_get_html($publickey);
                            ?>
                        </div>
                    <input type="submit" name="submit" value="Submit" class="submit-button" />
                </form>
                <div style="clear: both;">
                </div>
                <?php
                    $visitor_ip = getVisitorIP();
                    $hdshake =null;
                    if( isset($_POST['submit']) ) { 
                        $error = null;
                        require_once('recaptchalib.php');
                        $privatekey = "6LcJA-sSAAAAABCEyOe_wqfheVwfxfu4L9idhqhv";
                        $Name = Trim(stripslashes($_POST['Name'])); 
                        $City = Trim(stripslashes($_POST['City'])); 
                        $Email = Trim(stripslashes($_POST['Email'])); 
                        $Subject = Trim(stripslashes($_POST['Subject']));
                        $Message = Trim(stripslashes($_POST['Message']));
                        $hdshake .= '<li>Your IP :&nbsp;'. $visitor_ip .'</li>';
                        $hdshake .= '<li>Your eMail :&nbsp;'.$Email.'</li>';
                        echo '<div id="recaptcha_fail_div"><ul>'. $hdshake .'</ul></div>'; 
                        if( !empty($Email) ){ 
                            list($emailPart, $domainPart) = explode('@', $Email);
                            $one=filter_var($Email, FILTER_VALIDATE_EMAIL);
                            $two=MailIPAddress($domainPart);
                            if (!(($one) && ($two))) {
                                $error .= '<li>Email is invalid .</li>';
                                echo '<div id="recaptcha_fail_div"> <ul>'. $error .'</ul></div>';
                                exit();
                            } 
                        }
                        $error .= ( empty($Name) )  ? '<li>Please enter your name.</li>' : null;
                        $error .= ( empty($Email) ) ? '<li>Blank Email is not accepted.</li>' : null;
                        $error .= ( empty($Message) ) ? '<li>Please enter some comments or questions.</li>' : null;
                        
                        $resp = recaptcha_check_answer ($privatekey, 
                                                        $_SERVER["REMOTE_ADDR"], 
                                                        $_POST["recaptcha_challenge_field"], 
                                                        $_POST["recaptcha_response_field"]);                        
                        $error .= ( !($resp->is_valid) ) ? '<li>The captcha code entered is incorrect .</li>' : null;
                        if (!empty($error)) {
                            // What happens when the CAPTCHA was entered incorrectly
                            echo '<div id="recaptcha_fail_div"> <ul>'. $error .'</ul></div>';
                            exit();
                        } 
                        //Next send contact to website admin.
                        $EmailToAdmin = "carlo.dj@messiahpsychoanalyst.org"; //Put your website admin email here. Don't forget quotes. 
                        // body of the email your own admin receives
                        $Body = "RE: Contact from visitors";
                        $Body .= "\n";
                        $Body .= "Name: ";
                        $Body .= $Name;
                        $Body .= "\n";
                        $Body .= "City: ";
                        $Body .= $City;
                        $Body .= "\n";
                        $Body .= "Subject: ";
                        $Body .= $Subject;
                        $Body .= "\n";
                        $Body .= "Email: ";
                        $Body .= $Email;
                        $Body .= "\n";
                        $Body .= "Visitor's IP: ";
                        $Body .= $visitor_ip;
                        $Body .= "\n";
                        $Body .= "Message: ";
                        $Body .= "\n";
                        $Body .= $Message;
                        $Body .= "\n";
                        // send email to admin
                        $posted = mail($EmailToAdmin, $Subject, $Body, "From: <$Email>");
                        // redirect to thanks page 
                        if ($posted){
                            echo '<div style=\'margin-top: 20px; margin-left:112px; border: 2px groove blue; border=radius:5px; padding-left: 10px; width:400px;\'>
                                     <p>Thanks By <a href="http://messiahpsychoanalyst.org">Dysprosium</a></p>
                                     <hr style=\'margin: 1px auto 1px auto; height: 1px; color: #fefefe; width: 82%;\'/> 
                                     <h1>Your message has been sent! Thanks for Your Message!</h1>
                                     <p><a href="Default.html">Click to go to Home page!</a></p>
                                  </div>';
                            //After thank you send an email containing his message to the visitor
                            // prepare email body text
                            $Body = " Madam/Sir,\n Thank you for your message.\n Dysprosium.\n";
                            $Body .= " ======================================================\n\n";
                            $Body .= "Name: ";
                            $Body .= $Name;
                            $Body .= ", Esq.";
                            $Body .= "\n";
                            $Body .= "From: ";
                            $Body .= $City;
                            $Body .= "\n";
                            $Body .= "Email: ";
                            $Body .= $Email;
                            $Body .= "\n";
                            $Body .= "Subject: ";
                            $Body .= $Subject;
                            $Body .= "\n";
                            $Body .= "Message: ";
                            $Body .= "\n";
                            $Body .= $Message;
                            $Body .= "\n";
                            // send email 
                            mail($Email, $Subject, $Body, "From: <$EmailToAdmin>");
                        }                        
                    }
                    else{
                        echo '<div id="recaptcha_fail_div">&nbsp;&nbsp;Your IP :&nbsp;'. $visitor_ip .'</div>';                                 
                    }
                ?>
            </div>
        </div>
        <?Php
            /**
             * http://www.electrictoolbox.com/php-get-mail-server-ip-address/
             * Get a mail server's IP address with PHP
             * Posted November 9th, 2012 in PHP by Chris Hope
             * Returns an IP address that mail can be delivered to for the passed in domain.
             *
             **/
            function MailIPAddress($domain) {
                $ip = false;
                $records = dns_get_record($domain, DNS_MX);
                $priority = null;
                foreach ($records as $record) {
                    if ($priority == null || $record['pri'] < $priority) {
                        $myip = gethostbyname($record['target']);
                        // if the value returned is the same, then the lookup failed
                        if ($myip != $record['target']) {
                            $ip = $myip;
                            $priority = $record['pri'];
                        }
                    }
                }
                if (!$ip) {
                    $ip = gethostbyname($domain);
                    // if the value returned is the same, then the lookup failed
                    if ($ip == $domain) {
                        $ip = false;
                    }
                }
                return $ip;
            }
        ?>
        <?php
            function getVisitorIP() {
                $client = @$_SERVER['HTTP_CLIENT_IP'];
                $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
                $remote = $_SERVER['REMOTE_ADDR'];
                if (filter_var($client, FILTER_VALIDATE_IP)) {
                    $ip = $client;
                } 
                else { 
                     if (filter_var($forward, FILTER_VALIDATE_IP)) {
                         $ip = $forward;
                     } 
                     else {
                         $ip = $remote;
                     }
                }
                return $ip;
            }
        ?>
    </body>
</html>

Look at lines (254) to (272). A function has been added that returns IP address using PHP standard methods. This is very crude implementation of PHP and those methods should be guarded, in principle, against access to any global. Nevertheless it works for now and interested individual can do better by gaining deeper knowledge of PHP.
At line (130) visitor's IP has filled variable  $visitor_ip  to be displayed later with an echo command. Line (131) defines a $hdshake variable to show a formatted phrase for $visitor_ip and $Email of the visitor.

130
131
 $visitor_ip = getVisitorIP();
 $hdshake =null;

If the visitor has attempted the contact form, then lines (141) to (143) display their IP and email.

141
142
143
 $hdshake .= '<li>Your IP :&nbsp;'. $visitor_ip .'</li>';
 $hdshake .= '<li>Your eMail :&nbsp;'.$Email.'</li>';
 echo '<div id="recaptcha_fail_div"><ul>'. $hdshake .'</ul></div>';

Otherwise, if the visitor has just landed on the contact form page, then the page only displays his IP. This is reflected in the else phrase in lines (216) to (218).

216
217
218
 else{
      echo '<div id="recaptcha_fail_div">&nbsp;&nbsp;Your IP :&nbsp;'. $visitor_ip .'</div>';                                 
 }

Meanwhile note that lines (174) to (176), where you have sent the visitor's IP back for yourself for having further information to keep in your own database.

174
175
176
 $Body .= "Visitor's IP: ";
 $Body .= $visitor_ip;
 $Body .= "\n";

This is the snap-shot of page when visitor lands on page.

Above IP has been painted to a wrong number to avoid coincidence with some people's real IP. You can check yours by clicking here, please. In the next article we collect IP's of every visit in a text file.

Download this tutorial as PDF format here
Download part 1 to part 9 as PDF format here

Saturday, 14 December 2013

How to Create a Contact Form for Your Website in an Easy Way : A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (8)

(For the latest PDF files Merger Software please have a look at the top of the left margin, inside the red box.)
Continues From Part 7
Section 1. Failure message.
Section 2. Success message.
We finished the entire code (download PHP code in Zip format here or open the code in text format here) we needed in Part (7). Now we start to understand each line. My first task is to keep the values entered into all fields as they are. That  is possible by keeping "Form inputs" of HTML parts valid and alive using PHP built-in functions.

Section 1 : How to receive contact form failure message in the same page?

First note that the form tag action is empty and won't dispatch any action to a server-side scripting page.

101 <form method="post" action="">

Next, please look at line (103) to see how PHP puts value in an HTML tag.

103 <input type="text" name="Name" id="Name" value="<?php echo isset($_POST['Name']) ? $_POST['Name'] : '' ?>" />

"echo"  is the PHP print command. Then, you can see the C language if-else style, common in many programming languages. You can put if-else if you prefer the longer style. Hence,

1
2
3
4
5
6
if (some_thing){
                do_some_job;
            }
            else{
                do_else;
            }

can be written in shorter form as,

some_thing ? do_some_job : do_else; 

PHP, used at that position, won't need the finishing semi-colon. Therefore, if the field is empty, e.g., when you first open the page, keeps it empty; otherwise, if it has some value keeps them as they are. Also there are warning and cautions accessing super-global such as $_POST['Name'] in carefully written PHP files. They need filtering functions such as using filter_input ( INPUT_POST, 'Name' ) . I avoided those details for enthusiasts in learning PHP, as I found them beyond a simple contact form. You also might like to guard fields of your form with PHP function htmlentities ( ).

Please note the difference of textarea tag. textarea is a legacy of ancient computing (I mean 1990's) and has its own specification. It accepts carriage-return, new-line, carriage-return and new-line, new paragraph, tab, Home, End, Page-Down, and Page-Up as it scrolls. These are not settled issues adding internationalisation problems to them ever increasingly. Anyway difference is not much. Value cannot be attributed  inside the tag, similar to other inputs. We put PHP code outside the tag.

115  <textarea name="Message" rows="20" cols="20" id="Message"><?php echo isset($_POST['Message']) ? $_POST['Message'] : '' ?></textarea> 

Now bring your server-side demoPoster.php file into your HTML contact form. Remember that you have saved your contact form as a PHP file with .php extension. Here I have called it demoFinal.php.

You may notice some changes from previous demoPoster.php. All the code becomes active on the condition that you "submit" the form. Otherwise when a user opens the page for the first time it will dispatch errors regarding empty fields and wrong reCaptcha. This is line (130),

130    if( isset($_POST['submit']) ) { 

and ends at line (223). 

In the next line (131) we have identified and initialised a place holder for errors of the visitor.

130
   $error = null; 

Call to recaptchlib.php library and introducing the "private key" is done in next two lines (132) and (133).

132
133
   require_once('recaptchalib.php');
   $privatekey = "xxxxx-xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx"; 

Logical flow here has been improved. At first stage we test if the "email" field is not empty then we test it to follow the correct format of email and we check that it originates from a really existing domain. In future, we test if the email account bounces or is notorious for spamming, then IP of the sender becomes blacklisted for our website. For now, those available tests have been moved to lines (139) to (148).

 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
  if( !empty($Email) ){ 
                            list($emailPart, $domainPart) = explode('@', $Email);
                            $one=filter_var($Email, FILTER_VALIDATE_EMAIL);
                            $two=MailIPAddress($domainPart);
                            if (!(($one) && ($two))) {
                                $error .= '<li>Email is invalid .</li>';
                                echo '<div id="recaptcha_fail_div"> <ul>'. $error .'</ul></div>';
                                exit();
                            } 
                        } 

For the first time, in line (144) our variable  $error  becomes filled, should the visitor's email not complying our criteria. Pay attention to PHP operator .= which adds the new error to previous value of  $error (it was  already null ). This error will be reflected in a formatted box. I have itemised it to be unified with the format of other occurring errors. Here, contact form dispatches the error and exits since it cannot accept the other fields without a valid email. Error box becomes activated by the echo command  of  PHP.  That happens in the line (145). Please have a look at this image.


Flow of the "if " test terminates the job by exit()  command in the line (146); therefore, it does not need any "else" phrase.

If the users email looks all right, then flow of the program continues to check other errors ($error at this point still is null ) for the required fields, through lines (149) to (151). Each line tests for an empty required field (remember that email already had not been checked for being empty) and in case will add one item to error box in an itemised format.

149
150
151
   $error .= ( empty($Name) )  ? '<li>Please enter your name.</li>' : null;
   $error .= ( empty($Email) ) ? '<li>Blank Email is not accepted.</li>' : null;
   $error .= ( empty($Message) ) ? '<li>Please enter some comments or questions.</li>' : null; 

Lines (153) to (157) get error of reCaptcha field. (It is believed reCaptcha solutions help improve artificial intelligence software that digitise scanned books and documents.) Should reCaptcha field not entered correctly then an error would be added to potential errors.

153
154
155
156
157
 $resp = recaptcha_check_answer ($privatekey, 
                                 $_SERVER["REMOTE_ADDR"], 
                                 $_POST["recaptcha_challenge_field"], 
                                 $_POST["recaptcha_response_field"]);
 $error .= ( !($resp->is_valid) ) ? '<li>The captcha code entered is incorrect .</li>' : null; 

Then we do check whether $error is null ( is empty) or not. Look at lines (158) to (162), please,

158
159
160
161
162
if (!empty($error)) {
                     // What happens when the CAPTCHA was entered incorrectly
                     echo '<div id="recaptcha_fail_div"> <ul>'. $error .'</ul></div>';
                     exit();
                    } 

At this stage again we do not need "else" for "if" since any error terminates flow of the job. Remaining lines are already explained. Result of errors are shown in the following snapshot.

Section 2 : How to receive contact form success message in the same page?

What happens if the form and reCaptcha all filled correctly? Then you receive your "thank you" message in the same page. Line (188) to line (193) guarantee the print of "thanks" message in a desired format.

188
189
190
191
192
193
echo '<div style=\'margin-top: 20px; margin-left:112px; border: 2px groove blue; border-radius:5px; padding-left: 10px; width:400px;\'>
           <p>Thanks By <a href="http://messiahpsychoanalyst.org">Dysprosium</a></p>
           <hr style=\'margin: 1px auto 1px auto; height: 1px; color: #fefefe; width: 82%;\'/> 
           <h1>Your message has been sent! Thanks for Your Message!</h1>
           <p><a href="Default.html">Click to go to Home page!</a></p>
       </div>';

 Please look at the result.
Please watch this contact form by clicking this link. In the next post I add code to get IP of the visitors and display it on the contact form.

Download this tutorial as PDF format here
Download part 1 to part 8 as PDF format here

Friday, 13 December 2013

How to Create a Contact Form for Your Website in an Easy Way : A Set of Step by Step Tutorials Using HTML5, CSS3 and PHP (7)

(For the latest PDF files Merger Software please have a look at the top of the left margin, inside the red box.)
Continues From Part 6.
Perhaps noticed that in the demoError page it requests to use browser back button to return to the half filled page; other wise, that page would be refreshed upon revisiting and loses edits of users. Hence, values of the contact form field should remain maintained as they already have been half filled and the visitor might become disappointed and frustrated filling them again. If this visitor be a potential customer you might lose them for good.

My goal is to reflect the "Thanks" message or any other error message including reCaptcha error in the same page, without leaving the page or without losing half filled forms.

I move everything to the single demoFinal.php

First, let's have a look at the final code (download PHP code in Zip format here or open the code in text format here).

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
<!DOCTYPE html>
<!--
Created by Peter Joneses 13 December, 2013
codesforus.blogspot.com
copyrights
-->
<html>
    <head>
        <title> Demo-Final: Dysprosium Contact Form</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <script type= "text/javascript">
            var RecaptchaOptions = {
                theme: 'white'
            };
        </script>
        <style>
            
            #contact-wrapper {
                margin: 20px auto;
                border: 2px solid #ccc;
                border-radius: 5px;
                padding: 20px 50px 20px 50px;
                background: transparent;
                width: 600px;
            }

            #contact-area {
                width: 600px;
                margin-top: 25px;
            }
            
            #contact-area label {
                float: left;
                margin-right: 15px;
                padding-top: 5px;
                width: 100px;
                text-align: right;
                font-size: 100%;
            }

            #contact-area input, #contact-area textarea {
                margin: 0px 0px 10px 0px;
                border: 2px solid #ccc;
                border-radius: 5px;
                padding: 5px;
                width: 471px;
                font-family: Helvetica, sans-serif;
                font-size: 110%;
            }

            #contact-area textarea {
                height: 90px;
            }

            #contact-area textarea:focus, #contact-area input:focus {
                border: 2px solid #900;
            }

            #contact-area input.submit-button {
                float: left;
                cursor: pointer; 
                margin-top:10px;
                margin-left:112px;
                background: transparent;
                width: 100px;
                font-size: 100%;
                color: #024d8e
            }

            #contact-area input[type="submit"]:hover{
                border: 2px solid #900;
            } 

            #recaptcha_widget_div {
                margin-top: 20px;
                margin-bottom: 10px;
                margin-left: 112px;
            }
            
            #recaptcha_fail_div {
                margin-top: 20px;
                margin-bottom: 10px;
                margin-left: 112px;
                border:medium groove #A00;
                border-radius: 5px;
                border:medium groove #A00;
                padding:3px;
                background-color:transparent;
                width:350px;
                color:#900;
                font-weight:bold;
                font-size:80%;
            }
      
        </style>
    </head>
    <body>
        <div id="contact-wrapper">
            <div id="contact-area">
                <form method="post" action="">
                    <label for="Name"><span style="color: red; font-size: 100%">*&nbsp;</span>Name:</label>
                    <input type="text" name="Name" id="Name" value="<?php echo isset($_POST['Name']) ? $_POST['Name'] : '' ?>" />
                    
                    <label for="City">City:</label>
                    <input type="text" name="City" id="City" value="<?php echo isset($_POST['City']) ? $_POST['City'] : '' ?>" />
                    
                    <label for="Email"><span style="color: red; font-size: 100%">*&nbsp;</span>Email:</label>
                    <input type="text" name="Email" id="Email" value="<?php echo isset($_POST['Email']) ? $_POST['Email'] : '' ?>" />
                    
                    <label for="Subject">Subject:</label>
                    <input type="text" name="Subject" id="Subject" value="<?php echo isset($_POST['Subject']) ? $_POST['Subject'] : '' ?>" />
                    
                    <label for="Message"><span style="color: red; font-size: 100%">*&nbsp;</span>Message:</label>
                    <textarea name="Message" rows="20" cols="20" id="Message"><?php echo isset($_POST['Message']) ? $_POST['Message'] : '' ?></textarea>
                    
                    <p style="margin:20px auto 10px 112px;">Fields shown by <span style="color: red; font-size: 100%">*&nbsp;</span> are required.</p>
                        <div id="recaptcha_widget_div">
                            <?php
                                require_once('recaptchalib.php');
                                $publickey = "xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // you got this from the signup page
                                echo recaptcha_get_html($publickey);
                            ?>
                        </div>
                    <input type="submit" name="submit" value="Submit" class="submit-button" />
                </form>
                <div style="clear: both;">
                </div>
                <?php
                    if( isset($_POST['submit']) ) { 
                        $error = null;
                        require_once('recaptchalib.php');
                        $privatekey = "xxxxx-xxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx";
                        $Name = Trim(stripslashes($_POST['Name'])); 
                        $City = Trim(stripslashes($_POST['City'])); 
                        $Email = Trim(stripslashes($_POST['Email'])); 
                        $Subject = Trim(stripslashes($_POST['Subject']));
                        $Message = Trim(stripslashes($_POST['Message']));
                        if( !empty($Email) ){ 
                            list($emailPart, $domainPart) = explode('@', $Email);
                            $one=filter_var($Email, FILTER_VALIDATE_EMAIL);
                            $two=MailIPAddress($domainPart);
                            if (!(($one) && ($two))) {
                                $error .= '<li>Email is invalid .</li>';
                                echo '<div id="recaptcha_fail_div"> <ul>'. $error .'</ul></div>';
                                exit();
                            } 
                        }
                        $error .= ( empty($Name) )  ? '<li>You must enter a name.</li>' : null;
                        $error .= ( empty($Email) ) ? '<li>Email is blank.</li>' : null;
                        $error .= ( empty($Message) ) ? '<li>You must enter some comments or questions.</li>' : null;
                        
                        $resp = recaptcha_check_answer ($privatekey, 
                                                        $_SERVER["REMOTE_ADDR"], 
                                                        $_POST["recaptcha_challenge_field"], 
                                                        $_POST["recaptcha_response_field"]);                        
                        $error .= ( !($resp->is_valid) ) ? '<li>The captcha code entered is incorrect .</li>' : null;
                        if (!empty($error)) {
                            // What happens when the CAPTCHA was entered incorrectly
                            echo '<div id="recaptcha_fail_div"> <ul>'. $error .'</ul></div>';
                            exit();
                        } 
                        //Next send contact to website admin.
                        $EmailToAdmin = "carlo.dj@messiahpsychoanalyst.org"; //Put your website admin email here. Don't forget quotes. 
                        // body of the email your own admin receives
                        $Body = "RE: Contact from visitors";
                        $Body .= "\n";
                        $Body .= "Name: ";
                        $Body .= $Name;
                        $Body .= "\n";
                        $Body .= "City: ";
                        $Body .= $City;
                        $Body .= "\n";
                        $Body .= "Subject: ";
                        $Body .= $Subject;
                        $Body .= "\n";
                        $Body .= "Email: ";
                        $Body .= $Email;
                        $Body .= "\n";
                        $Body .= "Message: ";
                        $Body .= "\n";
                        $Body .= $Message;
                        $Body .= "\n";
                        // send email to admin
                        $posted = mail($EmailToAdmin, $Subject, $Body, "From: <$Email>");
                        // dispatch thanks message using Boolean $posted
                        if ($posted){
                            echo '<div style=\'margin-top: 20px; margin-left:112px; border: 2px groove blue; border-radius:5px; padding-left: 10px; width:400px;\'>
                                     <p>Thanks By <a href="http://messiahpsychoanalyst.org">Dysprosium</a></p>
                                     <hr style=\'margin: 1px auto 1px auto; height: 1px; color: #fefefe; width: 82%;\'/> 
                                     <h1>Your message has been sent! Thanks for Your Message!</h1>
                                     <p><a href="Default.html">Click to go to Home page!</a></p>
                                  </div>';
                            //After thank you send an email containing his message to the visitor
                            // prepare email body text
                            $Body = " Madam/Sir,\n Thank you for your message.\n Dysprosium.\n";
                            $Body .= " ======================================================\n\n";
                            $Body .= "Name: ";
                            $Body .= $Name;
                            $Body .= ", Esq.";
                            $Body .= "\n";
                            $Body .= "From: ";
                            $Body .= $City;
                            $Body .= "\n";
                            $Body .= "Email: ";
                            $Body .= $Email;
                            $Body .= "\n";
                            $Body .= "Subject: ";
                            $Body .= $Subject;
                            $Body .= "\n";
                            $Body .= "Message: ";
                            $Body .= "\n";
                            $Body .= $Message;
                            $Body .= "\n";
                            // send email 
                            mail($Email, $Subject, $Body, "From: <$EmailToAdmin>");
                        }                        
                    }
                ?>
            </div>
        </div>
        <?Php
            /**
             * http://www.electrictoolbox.com/php-get-mail-server-ip-address/
             * Get a mail server's IP address with PHP
             * Posted November 9th, 2012 in PHP by Chris Hope
             * Returns an IP address that mail can be delivered to for the passed in domain.
             *
             **/
            function MailIPAddress($domain) {
                $ip = false;
                $records = dns_get_record($domain, DNS_MX);
                $priority = null;
                foreach ($records as $record) {
                    if ($priority == null || $record['pri'] < $priority) {
                        $myip = gethostbyname($record['target']);
                        // if the value returned is the same, then the lookup failed
                        if ($myip != $record['target']) {
                            $ip = $myip;
                            $priority = $record['pri'];
                        }
                    }
                }
                if (!$ip) {
                    $ip = gethostbyname($domain);
                    // if the value returned is the same, then the lookup failed
                    if ($ip == $domain) {
                        $ip = false;
                    }
                }
                return $ip;
            }
        ?>
    </body>
</html>

As this is a long piece of codes, I explain its detail in the next post. Please click here.

Download this tutorial as PDF format here
Download part 1 to part 7 as PDF format here