© Christos Karayiannis 2019
Christos KarayiannisWeb-Based Projects that Rock the Classhttps://doi.org/10.1007/978-1-4842-4463-0_4

4. Obtaining a Domain Name with DDNS

Christos Karayiannis1 
(1)
Karditsa, Thessaloniki, Greece
 
In the previous chapter, your site passed the borders of your LAN and became available to the whole Internet. URLs that were not exactly user-friendly like the following were used:
http://94.64.2.196:8080/

In this chapter, you will learn how to use the Dynamic DNS (DDNS) service to obtain and use a domain name for your site; for example, you can use webtoolsonline.servehttp.com instead of an IP address in the URL.

With a proper URL for your site, you can set up PHP to interface with the Linux shell and use an online service like WHOIS. Also, you will further improve your site’s appearance by creating a favicon icon, which is an icon that represents your site in clients’ browser tabs and in the list of bookmarks.

DNS and DDNS

The Domain Name System (DNS) service translates the domain name of a computer to the corresponding static IP address. Purchasing a static IP address from your ISP is usually more expensive than having a dynamic IP address that often changes, for instance every time your router reboots. Correlating a domain name to a dynamic IP address is still possible with DDNS. There are two ways to update the DDNS service provider data with your changed IP address. The method discussed in this chapter is to use a DDNS service in your router. Today most routers support DDNS services. The only drawback is that some router models support DDNS for only certain DDNS service providers. If your router does not support your DDNS provider, you can use a DDNS client program that runs in the background of your web server as a daemon process. This is the method implemented in Chapter 10, where you’ll use the program ddclient. The program ddclient checks in constant time intervals to see whether the public IP address of your router has changed. If it has, an update message is sent to your DDNS service provider.

DDNS services can be free or require a monthly fee. A nice feature offered by most DDNS service providers is web redirect. Consider, for instance, the following URL with an IP address:
http://94.64.2.196:8080/
Using a DDNS service, the client can replace the public IP address of the router with a domain name and use the following in the address bar of a browser:
http://christos.ddns.net:8080
The domain name is used instead of the IP address; however, the port number is present. Web redirect helps you hide the port number and enables your visitors to use a more readable URL, as shown here:
http://christos.ddns.net

Registering with a DDNS Service Provider

This section describes the steps to register with a no-IP DDNS service provider. This is one of the providers supported by the router that is used in the examples of this book. You can register with any other provider supported by your router following a similar process. As with most online services, you sign up by providing your e-mail address and a unique password. For a DDNS service provider, you can choose a third-level domain name. For instance, I chose christos under the configuration authority of the second-level domain name ddns (the DDNS service provider itself), which is under the configuration authority of the top-level domain (TLD) or first-level domain net. The fully qualified domain name (FQDN), used in the site, therefore becomes the following:
 christos.ddns.net

With this specific DDNS server provider, you can choose three hostnames and also implement web redirect for free.

Now visit the no-IP site.
http://www.noip.com
Once there, click the Sign Up button to begin the registration process (Figure 4-1).
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig1_HTML.jpg
Figure 4-1

The Sign Up button of the no-IP home page

The next page, shown in Figure 4-2, allows you to select a hostname (e.g., christos) and the second-level domain name (for instance, zapto.org or ddns.net ) from a drop-down list. You need also to provide your password and your e-mail. Click the Terms of Service and Privacy Policy box and then click the Free Sign Up button.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig2_HTML.jpg
Figure 4-2

Setting your preferences for your hostname with no IP

The next page, shown in Figure 4-3, asks you to confirm your account by clicking the link of the e-mail sent to the account you provided. This allows the DDNS provider to verify that your e-mail account is a real one.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig3_HTML.jpg
Figure 4-3

The web page requiring e-mail account confirmation

Figure 4-4 displays a snapshot of the e-mail received.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig4_HTML.jpg
Figure 4-4

The e-mail, including a Confirm Account button for validating the no-IP account

After clicking the Confirm Account button, the window shown in Figure 4-5 appears in a new tab of your browser with the message “Your account is now active!”
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig5_HTML.png
Figure 4-5

The web page informing you that the account is activated

Click the “Get started with Dynamic DNS” link to continue. The window displayed in Figure 4-6 informs you to create a username and a security question to complete your account configuration. Click the Add Now button to proceed.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig6_HTML.jpg
Figure 4-6

The dialog for proceeding to the final step of creating a DDNS account

In the web page shown in Figure 4-7, you set your username, security question, and also some personal information.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig7_HTML.jpg
Figure 4-7

The final web page of the DDNS account setup process

Click the Save button to save the information entered and thus complete the account setup process. You can use the hostname obtained here to configure the router of your LAN to implement the DDNS service.

Configuring the Router’s DDNS

With a new domain name obtained in the previous section, you can now configure your router to relay its public IP address to the DDNS provider each time this IP address changes. Locate the DDNS section in the web-based configuration interface of your router. As shown in Figure 4-8, for the router used in the examples, you can view the DDNS configuration options by selecting Internet and then DDNS from the menu.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig8_HTML.jpg
Figure 4-8

The DDNS configuration section for the router used in the examples

Select the DDNS provider from the Provider drop-down list, which has all the DDNS providers that the router supports. Enter the details required: your username, your password, and the hostname you chose at the DDNS registration process. Complete also the Provider URL field, and select the On DDNS radio button. Click the Apply button to confirm the new settings.

Test your new domain name ( christos.ddns.net is used in the following examples). In this chapter, the Apache configuration created in Chapter 1 is used. You can test the URLs of the web pages created in the previous chapter, for instance geo5.php. Enter the following URL for geo5.php in the address bar of your browser, substituting the domain name used here with yours:
http://christos.ddns.net/geo5.php
If your ISP blocks inbound port 80, which is the default HTTP port, use an alternate port like 8080.
http://christos.ddns.net:8080/geo5.php
The web page geo5.php is displayed, as shown in Figure 4-9.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig9_HTML.jpg
Figure 4-9

Testing the web page geo5.php with the new domain name

The web page geo5.php loads with the URL that includes the previously acquired domain name. In the following section, you will implement web redirect so that if you do not utilize the default HTTP port number, but another one such as 8080, this number is hidden from the URL.

Implementing Web Redirect

If your ISP blocks the default HTTP port for incoming connections to your LAN, you can still use URLs that do not append a colon and the port number after the domain name, although behind the scenes the specific port number is actually used. To include this feature, you need to configure the web redirect service offered by DDNS providers.

By setting a specific port number, such as port 8080 in the web redirect option, you are enabling clients to use a port-free URL. The DDNS provider redirects visitors to another domain name, where the port number is already appended with a colon. To test the web redirect feature, another domain name is required, so this is a good chance to utilize the second of the three domain names offered from the DDNS provider.

Log in on the DDNS provider home web page and click the Dynamic DNS link in the left panel. The first domain name, e.g., christos.ddns.net , appears as a link that leads to the configuration web page of this domain name, as displayed in Figure 4-10.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig10_HTML.jpg
Figure 4-10

The Hostnames web page displays the hostnames created so far

Click the Create Hostname button to create your second domain name, the one used for web redirect. Enter the third-level domain name in the Hostname textbox, as shown in Figure 4-11. For instance, in this example, webtoolsonline was used. To also change the second-level domain name, select a different one from ddns.​net in the Domain drop-down list. In this example, servehttp.​com was used. The FQDN therefore becomes as follows:
webtoolsonline.servehttp.com
For the Record Type radio buttons, select Web Redirect to implement this service for the new domain name. By selecting this option, a new textbox URL/IP address appears. Type the first domain name with port 8080 appended after a colon.
christos.ddns.net:8080
Each time the new hostname webtoolsonline.servehttp.com is used from a client, the DDNS service redirects the request to christos.ddns.net:8080 .
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig11_HTML.jpg
Figure 4-11

Creating the second hostname with the Web Redirect option set

Click the Create Hostname button. As viewed in Figure 4-12, the new domain name is added in the Hostname list.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig12_HTML.jpg
Figure 4-12

The Hostnames web page displays the hostnames created so far

To try the new domain name, enter the following in the address bar of your browser:
http://webtoolsonline.servehttp.com
With the web redirect service enabled, the URL http://webtoolsonline.servehttp.com redirects to christos.ddns.net:8080 . The directory index of the Apache vhost listening to port number 8080 (used in Chapter 1) is displayed in the web browser, as shown in Figure 4-13.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig13_HTML.jpg

To visibly retain the original URL, you have to implement the Mask URL feature by configuring the DDNS provider. Edit the hostname on the Hostnames web page of the DDNS provider’s site and select the Mask URL box. Click the Update Hostname button to apply the configuration.

With the URL mask enabled, the DDNS service injects JavaScript into the source code of the web page to create an HTML frame that covers the entire browser window and includes the same content but a different URL in the address bar of the browser. The result, as displayed in Figure 4-14, is a web page with the same content; however, instead of the expected URL shown here where the client redirects:
http://christos.ddns.net:8080
the following URL appears in the address bar:
http://webtoolsonline.servehttp.com
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig14_HTML.jpg
Figure 4-14

Using the URL mask option to modify the URL displayed in the client browser

Hint!

To view the frame created with the Mask URL option, right-click the web page and select View Page Source for Chrome or the corresponding option for other browsers. In this case, the URL of the address bar is altered with JavaScript code.

You have so far created and used two hostnames for your registered DDNS account. You will use the third hostname, e.g., secureserver.ddns.net , in Chapter 8. In Chapter 9, you will find the steps to obtain and use your own second-level domain name, e.g., httpsserver.eu, required for running a secure site. In the following section, you will put the hostnames created so far to use to create your next project.

Implementing an Online Web Service

With such a catchy domain name like webtoolsonline.servehttp.com , it is tempting to implement an actual online web service. You can implement, for instance, the WHOIS service, which applies whois, a query and response protocol that is widely used for querying databases that store the assignees of Internet resources, such as domain names and IP addresses. You can run the whois command at the command line, but it is also offered as an online web service from various sites, e.g., whois.domaintools.com or ping.eu, which is shown in Figure 4-15.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig15_HTML.jpg
Figure 4-15

The web page of the ping.eu WHOIS service

Ping.eu, along with other similar sites, offers online web services, for instance DNS lookup, ping, traceroute, and port check. You will implement port checking in Chapter 10.

To create a site that offers WHOIS as an online service, you can use a web page with a form; the form will include a textbox to submit an IP address to the PHP program on the web server that interfaces with the Linux shell and returns information about the corresponding domain name.

The first step to implement the online service is to change the default web page that Apache sends in response to using port 8080. As explained in the previous sections of this chapter, the domain name webtoolsonline.servehttp.com resolves to christos.ddns.net:8080 and to the router’s public IP address through port 8080. The Apache vhost configuration file for serving port 8080 for any domain name was set up in Chapter 1 to example2.conf. The directory index used in this file for port 8080 is index3.html, which is actually the web page shown in the previous section with the URL http://webtoolsonline.servehttp.com . As a second step, edit example2.conf and replace index3.html with another HTML file, for instance onlineservice.html.

Create a new web page called onlineservice.html that includes a form similar to the one on the ping.eu page. This form will be used to submit the user’s data to the web server, and as viewed from ping.eu, two form elements are required at a minimum: the textbox that will receive the IP address or the hostname and a submit button. The form’s action attribute will refer to a PHP file that receives the user’s data, interfaces with the whois command-line program, and then passes the user’s data as arguments. Finally, the whois output is included on the web page generated by PHP and sent back to the user. With similar steps, you can implement any other online service such as the ones offered by ping.eu .

Editing the Apache Configuration File

In this section, you’ll edit the configuration file example2.conf used in Chapter 1 to implement two sites with two vhosts, one listening on port 8080 and one listening on port 8181. In this example, only the vhost listening to port 8080 is required; therefore, for this vhost the Apache DirectoryIndex directive is edited to set the file onlineservice.html as the new directory index of the site.

At the Linux terminal, enter the following:
$ cd /etc/apache2/sites-available
$ sudo gedit example2.conf
Replace index3.html with onlineservice.html.
Listen 8080
Listen 8181
# 1st vhost
<VirtualHost *:8080>
      ServerAdmin webmaster@localhost
      DocumentRoot /var/www/html
      DirectoryIndex onlineservice.html
      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
# 2nd vhost
<VirtualHost *:8181>
      ServerAdmin webmaster@localhost
      DocumentRoot /var/www/html
      DirectoryIndex index4.html
      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Click the Save button in the gedit window to confirm the changes. To reflect the configuration changes for the vhost listening on port 8080, the Apache web server needs to be reloaded. At the Linux terminal, enter the following:
$ sudo service apache2 force-reload

Hint!

In this example, an existing configuration file was used. Consider the case that you implement the site with a new configuration file for a vhost that listens to the default HTTP port, which is 80. You can create the configuration with the following commands:

$ cd /etc/apache2/sites-available

$ sudo gedit onlineservice.conf

Enter the following directives and save the file:

Listen 80

<VirtualHost *:80>

ServerAdmin webmaster@localhost

DocumentRoot /var/www/html

DirectoryIndex onlineservice.html

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

Then use the following:

$ sudo a2ensite onlineservice

$ sudo service apache2 force-reload

To test the site, you create the first file called onlineservice.html as described in the following section, and you enter the first hostname, christos.ddns.net , in the address bar of the browser. The second one, webtoolsonline.servehttp.com , redirects to christos.ddns.net:8080 , which listens to port 8080 instead of the default port.

The next step is to create the directory index used from the vhost. This is called onlineservice.html and is the web page that contains the form for submitting an IP address.

Editing the Web Page for Submitting the User’s Data

The HTML file that includes the form used by the user to provide the data to the web server is onlineservice.html, which was set in the previous section in the vhost configuration file as the directory index for the site webtoolsonline.servehttp.com . Figure 4-16 displays the directory index.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig16_HTML.jpg
Figure 4-16

The browser displays onlineservice.html, the directory index of the site

Create the file onlineservice.html in the document root of the vhost. At the Linux terminal, enter the following:
$ cd /var/www/html
$ sudo gedit /var/www/html/onlineservice.html
Enter the following lines and save the file:
<!DOCTYPE html>
<html>
<head>
<title>
Online WHOIS service
</title>
<style>
p.large {
font-size:32px;
color:red;
background-color:blue;
display:inline;
}
p.small {
font-size:16px;
color:white;
background-color:black;
display:inline;
padding: 15px 32px;
}
input {
    background-color: black;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    font-size: 16px;
}
</style>
</head>
<body>
<p class="large">Online WHOIS service</p>
<br><br>
<form method="POST" action="result.php" name="f1" onsubmit="return validate()">
<p class="small">IP address: </p>&nbsp;&nbsp;
<input type="text" name="user_data">&nbsp;&nbsp;
<input type="submit" value="Go">
</form>
<script>
function validate() {
var f = document.forms["f1"]["user_data"].value;
f=f.trim();
var ipformat = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]).){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/
if(!(f.match(ipformat))){
alert("Enter a valid IP address");
return false;
}
}
</script>
</body>
</html>

The HTML source code includes a form that implements the method POST for submitting the data and sets the value of the action attribute to result.php. This is the program on the server side that will accept and process the data submitted.

There are two more attributes in the form element, both required for the form validation, which is implemented locally by JavaScript. The name attribute is used by the JavaScript function validate() , which validates the form, to refer to this form. The return value of validate() is set as the value of the fourth attribute of the form, the onsubmit event. Events are actions applied to the web page that JavaScript responds to. The onsubmit event defines the form submission as the exact instant in time that the source code bound to this event will run.

By setting the onsubmit event value to return validate(), the function validate() will run when the form is submitted, and also the form will be submitted only when validate() returns true. The function validate() is implemented in the following script:
<script>
function validate() {
var f = document.forms["f1"]["user_data"].value;
f=f.trim();
var ipformat = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]).){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/
if(!(f.match(ipformat))){
alert("Enter a valid IP address");
return false;
}
}
</script>

The name attribute of the form is used next to refer to the specific form in the HTML file and then return the value of the user_data textbox to variable f. For the variable f, which is an object of class string, the trim() method removes whitespace from both sides of the string. If the user accidentally enters spaces in the user_data textbox with the IP address, trim() is used so that validate() won’t reject the IP address.

The ipformat regular expression (regex) is used next to check whether the value of variable f matches the pattern of a valid IP address according to ipformat. The details of this regex are explained in the following section.

The match string() method is used to search string f for a match against the regular expression. The following if command uses match() to verify whether the ipformat regex does not (!) match string f :
if(!(f.match(ipformat))){

If a match is not met, the IP address is considered invalid, and validate() returns false. In that case, the form is not submitted, and the user is asked to enter a valid IP address with a pop-up window message, created by alert().

Working with Regular Expressions

Expressions are character sequences that define search patterns. They are extremely useful in validating or extracting information from text. The regular expression assigned to the JavaScript variable ipformat is used to describe the pattern for a valid IP address and validate the user data. The following command assigns the regex to the ipformat variable:
var ipformat = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]).){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/

A regex usually uses two slash characters, e.g., /abc/, to delimit the search pattern. The caret (^) and the dollar sign ($) anchors match the start and the end, respectively, of the string the regex pattern is applied to.

The first block is repeated three times, as indicated by the quantifier {3}. A valid IP address consists of four numbers from 0 to 255, separated with three periods. Each repetition validates one number from 0 to 255 with a period appended. The bracket expressions ([]) are replaced by one of the characters specified in the range. The following expressions are used:
  • 25[0-5] matches text numbers (in text form) from 250 up to 255.

  • 2[0-4][0-9] matches numbers (in text form) from 200 up to 249.

  • 1[0-9][0-9] matches numbers (in text form) from 100 up to 199.

  • [1-9][0-9] matches numbers (in text form) from 10 up to 99.

  • [0-9] matches numbers (in text form) from 0 to 9.

The or (|) operator is used to include just one number of the previous expressions. With the quantifier {3}, three numbers are required, each followed by a period. Here’s an example:
89.4.100.
For the fourth number, a period is not allowed. An example of matching text is as follows:
223
The total regex validates the IP addresses in this form:
89.4.100.223

Testing the JavaScript Form Validation

You’ll now test the form validation in the HTML file onlineservice.html using JavaScript. In the address bar of your browser, enter the URL of the site, as shown here:
http://webtoolsonline.servehttp.com
Enter in the textbox an invalid IP address, for instance:
256.5.46.7
or the following:
1.2

Click the Go button, which submits the IP address to the web server. A web server program to receive the data is not defined yet, but you can still view the warning message the JavaScript creates for an invalid IP address.

A pop-up window with the message “Enter a valid IP address” appears, as displayed in Figure 4-17. In the message, the domain name of the server is included as christos.ddns.net:8080 , which is the domain name that webtoolsonline.servehttp.com actually redirects to.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig17_HTML.jpg
Figure 4-17

Testing the web page using an invalid IP address

Next you will create the action program for the form, result.php, which receives that IP address and uses it with the whois command-line program. But first you can try to run whois from the command line to find out how it outputs data and comments. The latter will be excluded from the output of the PHP program for the WHOIS service.

Running whois from the Command Line

The IP address entered by the user in the textbox of form f1 will be submitted to program result.php on the web server. The PHP engine that processes result.php will run the whois shell utility with this specific IP address as an argument. The output of whois will be entered in the web page the user receives from the echo PHP command.

Before using PHP to interface with the whois utility, try to run whois directly from the Linux terminal. To install whois at the command line, enter the following:
$ sudo apt install whois
Test whois with an IP address. You can try a random IP address, for instance:
$ whois 1.2.3.4
Figure 4-18 displays the whois output at the Linux terminal.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig18_HTML.jpg
Figure 4-18

The whois output with percent symbols indicating comments

Notice that some lines include comments starting with the percent (%) symbol. In the evaluated result.php, it is probably a good idea to remove those comments and make the output appear more professional.

Try another IP address, for instance 4.3.2.1:
$ whois 4.3.2.1
Figure 4-19 displays the whois output for the second IP address.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig19_HTML.jpg
Figure 4-19

The whois output with hash symbols indicating comments

Notice in this case that the hash symbol is also used to indicate the start of the comments. Now it’s time to create result.php, the program that receives the IP address entered by the user, processes it with the whois command, and returns to the user the output with the comments excluded.

Editing the File That Processes the User Data

You create next result.php in the document root (/var/www/html) of the vhost used.

At the Linux terminal, enter the following:
$ sudo gedit /var/www/html/result.php
Enter the following lines and save the file:
<!DOCTYPE html>
<html>
<body>
<span style="color:red;text-align:left;font-size:32px;background-color:blue;float:left">
Online WHOIS Service
</span>
<span style="color:yellow;text-align:right;font-size:32px;background-color:blue;float:right">
<?php echo "Your IP address: " . $_SERVER['REMOTE_ADDR']; ?>
</span>
<?php
echo '<h1 style="color:blue;text-align:center"> whois ' . $_POST['user_data'] . '</h1>';
echo '<p style="font-family:monospace;font-size:16px;background-color:black;color:white">';
$user_data = $_POST['user_data'];
if (isset($user_data)) {
   $exec_string = "whois $user_data";
   $output = shell_exec($exec_string);
   $stream = fopen('data://text/plain,' . $output,'r');
   while(! feof($stream)) {
       $x = fgets($stream);
       if((strpos(trim($x), '%') === 0) || (strpos(trim($x), '#') === 0))
       continue;
       echo $x;
       echo "<br>";
   }
}
echo '</p>';
?>
</body>
</html>

In the result.php source code, the global PHP variable $_SERVER, set by the PHP engine, includes the element $_SERVER['REMOTE_ADDR'], which holds the visitor’s IP address. This information is not required by the WHOIS service but could be used as additional info for users who view your site.

With the following source code, the IP address entered by the user in the user_data textbox in the file onlineservice.html is now received by the PHP engine as $_POST['user_data']. This IP address is part of the message displayed when result.php is evaluated. For instance, for the IP address 1.2.3.4, the message is whois 1.2.3.4, which indicates the query whois performed. This information is included as a header, because it consists of the content of an h1 HTML element.
echo '<h1 style="color:blue;text-align:center"> whois ' . $_POST['user_data'] . '</h1>';
The $_POST['user_data'] valus is assigned then to the  PHP variable $user_data.

The variable $exec_string is set to the string that represents the command that will be executed from the terminal at the web server. It is set to whois $user_data. This evaluates to whois <IP address>, where <IP address> is the specific value provided by the user, e.g., 87.202.116.192.

Hint!

To implement a different service, you could change the command assigned as a value to $exec_string. For instance, for the ping service, you could use the following:

$exec_string = "ping –c 3 $user_data";

This sends three ICMP echo messages to the destination IP address and receives the reply. ICMP stands for Internet Control Message Protocol. It is part of the TCP/IP protocol suite and is used for diagnostic purposes.

The command defined in exec_string is passed to the Linux terminal with the function shell_exec().
   $output = shell_exec($exec_string);
The value stored in shell_exec is the output of the whois command that you ran previously at the terminal. The output of the command executed is returned to the $output variable. This is a long string that usually includes multiple lines. To process this string, one approach is to store it in a file. Another approach is to process it on the fly using the notion of a Unix stream. A stream treats a string like a file. To access the $output string as a stream, for a read (r) operation, the file descriptor $stream is used in the following command:
   $stream = fopen('data://text/plain,' . $output,'r');

For this stream, the data wrapper specifies the stream type, and the text/plain target specifies the stream format.

The following while loop is used to read one line at a time of the $stream and output all noncomment lines:
   while(! feof($stream)) {
       $x = fgets($stream);
       if((strpos(trim($x), '%') === 0) || (strpos(trim($x), '#') === 0))
       continue;
       echo $x;
       echo "<br>";
   }
The while condition, ! feof($stream), is true, while the end of the stream is not reached. Each line of the stream is returned in each while iteration by the fgets() function to variable $x.
       $x = fgets($stream);
The following command ignores all the lines starting with the percent (%) or the hash (#) symbol:
       if((strpos(trim($x), '%') === 0) || (strpos(trim($x), '#') === 0))
       continue;

The function trim() is used to remove the characters specified in its second argument. Since in this example no second argument exists, it returns a string stripped of any space, tab, or newline characters at the start and the end of the string. This is the corresponding PHP function to the JavaScript trim() method used previously in file onlineservice.html.

The two strpos() functions receive the returned string and check whether the character at position 0 (first position) is either the percent or the hash character. If this is the case, the command continue executes, and as a result, the while loop proceeds without executing the last two while commands in the current iteration. If the current line starts with the percent or hash character, this line is therefore ignored.

Hint!

To check the result of the functions trim() and strpos() and of other string functions of PHP, use the PHP CLI utility. CLI stands for command-line interface, and if this program is not installed on your system, install it now by using this:

$ sudo apt-get install php7.0-cli

In the current directory, create a PHP file, for instance test.php.

$ gedit test.php

Enter the following code snippet and save the file:

<?php$str = " Hello World!";echo $str;echo " Position of character H: ";echo strpos($str, 'H');echo " ";$str2 = trim($str);echo "$str2";echo " Position of character H: ";echo strpos($str2, 'H');?>

The value of variable $str is prepended with two newline characters ( ), which have the effect of pressing the Enter key of the keyboard, and two tab characters ( ), which have the effect of pressing the Tab key. The first strpos() call returns the position of character H in the string. The return value is 5 because character H is in the sixth position, which is position 5 starting counting from 0. Next, trim() is used to strip the tab and newline characters at the start of the string. The second strpos() therefore returns 0 because now H is the first character.

To run the program, use the following:

$ php test.php

The output in the Linux terminal is as follows:

christos@pc:~$ php test.php            Hello World!Position of character H: 5Hello World!Position of character H: 0

If the current line is not a comment, it is printed with the echo command, and also a break tag is used to change the line.
echo $x;
echo "<br>";

All not-commented lines are thus included in the output generated by the PHP engine and returned to the user from the web server.

Testing the WHOIS Online Service

You can test next your online WHOIS service at webtoolsonline.servehttp.com . Enter one of the IP addresses previously tested with the whois command from the terminal, e.g., 1.2.3.4, as viewed in Figure 4-20 .
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig20_HTML.jpg
Figure 4-20

Testing a valid IP address with the online service

Click the Go button to submit the IP address to the web server.

The result.php evaluated web page for the IP address 1.2.3.4 is displayed in Figure 4-21.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig21_HTML.jpg
Figure 4-21

The online WHOIS service output

You will notice that the style of this web page resembles the Linux terminal. At the top of the web page, the message whois 1.2.3.4 appears in the center, and the public IP address of the client is displayed on the right. The output differs from the whois terminal command because it lacks comment lines.

In the next section, you can add a favicon image to the web site to make the site instantly recognizable.

Adding a Favorite Icon to the Site

A favorite icon, referred as a favicon in its filename, is the tiny icon you see on the left of your browser tab when a web page loads. It makes a site recognizable because you can easily locate it when lots of tabs are open in the browser. Even before the web page loads, the favicon icon appears in the address bar of the browser, next to the address, which is completed with the autofill feature. This ensures that the address you are about to enter is the correct one. Favicons appear also in the bookmark list, where the URLs of your favorite sites are saved.

The first step of including a favicon image is to design it. In the Linux locate an image editor program or download and install one if necessary. The example shown here uses the mtPaint editor, which is the default image editor on the Linux system I’m using. Open mtPaint, and from the File menu select New. Favicons require a size of 16×16 pixels; therefore, in the dialog that appears (Figure 4-22), set the dimensions of the new image to 16 pixels width by 16 pixels height.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig22_HTML.jpg
Figure 4-22

Setting the dimensions of the favicon icon to 16x16 pixels

mtPaint displays a black-colored canvas, sized 16×16 pixels, for the new image (Figure 4-23).
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig23_HTML.jpg
Figure 4-23

The tiny favicon image with a 16×16 pixel size

This is a tiny canvas to work with, so zoom in to enlarge it. To do this, in the zoom percentage drop-down, use a bigger zoom than 100%, for instance 1200% (Figure 4-24).
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig24_HTML.jpg
Figure 4-24

Zooming in on the image for detailed drawing

You can start by applying your ideas to the canvas. For instances, you can click the Flood Fill button (the paint bucket), select a white color (e.g., color 7 from the color list on the left), and click next any pixel of the canvas to turn the background of your image to white. Using the Paint button (the blue pencil), select a color from the list and click any pixel to color it. In Figure 4-25, the blue and red colors are being used. The image displayed includes two letters, OT, for “online tools.” The letter T strives to look like a hammer.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig25_HTML.jpg
Figure 4-25

The favicon image completed

From the File menu, choose Save As to save the image to one of your directories, e.g., Pictures, and in the dialog that appears, provide the Pictures file path and favicon file name. Select also PNG as the image format in the File Format list and click the OK button .

Although you can use the PNG file type for the favicon files, the default one used for the whole site defaults to the name favicon.ico. The ICO file type is not supported by mtPaint. You can, however, change the file type from the terminal using the convert command included in the imagemagick package. Install imagemagick using the following:
$   sudo apt-get install imagemagick
Change then the file type using:
$ convert -background transparent "favicon.png" -define icon:auto-resize=16,24,32,48,64,72,96,128,256 "favicon.ico"
Copy next the favicon.ico file to the document root:
$ sudo cp ~/Pictures/favicon.png /var/www/html
Test your site next. As viewed in Figure 4-26, the favicon image appears on the left of the web page tab in your browser.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig26_HTML.jpg
Figure 4-26

The site’s home page includes a favicon image on the browser’s tab

To use a different favicon image for another web page of your site, make explicit reference from the web page to another favicon image. Create a second favicon file, favicon2.png, that includes for simplicity just a yellow background, and copy it to the document root directory. Edit a web page, for instance the result.php file, and add in the head section a link reference to favicon2.png. Specifically, in the head section of the HTML source code, enter the following tag :
<link rel="icon" href="favicon2.png"/>
Because this is a specific reference where the file name is provided, the file type used can be of a different type than ICO; e.g., in this example PNG is used. The source code of result.php becomes the following:
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="favicon2.png"/>
</head>
<body>
<span style="color:red;text-align:left;font-size:32px;background-color:blue;float:left">
Online WHOIS Service
</span>
<span style="color:yellow;text-align:right;font-size:32px;background-color:blue;float:right">
<?php echo "Your IP address: " . $_SERVER['REMOTE_ADDR']; ?>
</span>
<?php
echo '<h1 style="color:blue;text-align:center"> whois ' . $_POST['user_data'] . '</h1>';
echo '<p style="font-family:monospace;font-size:16px;background-color:black;color:white">';
$user_data = $_POST['user_data'];
if (isset($user_data)) {
   $exec_string = "whois $user_data";
   $output = shell_exec($exec_string);
   $stream = fopen('data://text/plain,' . $output,'r');
   while(! feof($stream)) {
       $x = fgets($stream);
       if((strpos(trim($x), '%') === 0) || (strpos(trim($x), '#') === 0))
       continue;
       echo $x;
       echo "<br>";
   }
}
echo '</p>';
?>
</body>
</html>
Test the onlineservice.html file using, for instance, the following URL:
127.0.0.1:8080.
As shown in Figure 4-27, the home page of the site loads with the default favicon image.
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig27_HTML.jpg
Figure 4-27

The home page of the site loads with the default favicon image

Enter in the form textbox an IP address and click the Go button. The result.php web page is displayed in your browser. As shown in Figure 4-28, result.php includes the yellow favicon2.png icon on the left of its tab .
../images/468152_1_En_4_Chapter/468152_1_En_4_Fig28_HTML.jpg
Figure 4-28

The web page result.php uses a different favicon image

You can create a favicon icon in a few steps to provide an image that personalizes your site and even become the motivation for an inspired logo for the web content of the site .

Summary

In this chapter, you did the following:
  • You used the DDNS service to provide a user-friendly domain name to your site.

  • You created a web project with an online web service, specifically WHOIS.

  • You created a favicon.ico image for your site.

In the next chapter, the source code of another web service is displayed, which creates a site that allows web server administrators and web designers find how their site looks from a remote location. But first you are introduced to another popular open source web server, the Lighttpd server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.207.129