viperfx07 is here to blog about hacking, cracking, website, application, android, and many more.

Wednesday, September 15, 2010

Week 7 Practice Challenges

2:43 PM Posted by viperfx07 No comments
There are 2 challenges this week:
1. Using PHP database functions
2. Regular Expression using PHP
Find the codes below...

For the first challenge, you just need to:
1. Add field to input form (line 274 -275)
2. Add column to the database (done using MySQL)
3. Modify code to update the column from the field (line 134, 139-141, 180, 243, 248, 250)
4. Display the country of the guest. (line 55, 60-64)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

 <title>Guestbook</title>
 
</head>

<body>

 <script language="JavaScript" type="text/javascript">
 function checkGB()
 {

 if ((document.forms.myGB.name.value == '') || (document.forms.myGB.message.value == ''))
 {
 alert('Fill in required fields!');
 }
 else {
                 document.forms.myGB.submit();
                 }
 }
 </script>
 <div align=center>
   <strong>::Guestbook - A::</a></strong><br>
   </div>
 <?php
 /******************************************************************************/
 /*                     HERE WE DEFINE OUR GUESTBOOK CLASS                     */
 /******************************************************************************/
 class Guestbook {
       var $result;             // Main query result;
       var $count_result;       // Count query result;
       var $dbc;                // Database connection;
       var $total_entries;      // How many records in database;
       var $table = "guestbook"; // Guestbook table;
       /* LET'S CONNECT TO OUR DATABASE */
       function connect_db($server, $database, $user, $password)
       {
               $this->dbc = mysql_connect($server, $user, $password) or die ("Connection failed!");
               mysql_select_db($database) or die ("Database failed!");
       }
       /* DISPLAY RECORDS */
       function display_records($offset, $entries_per_page)
       {
               $this->result = mysql_query("SELECT id, name, email, message, date, country FROM $this->table ORDER BY id DESC LIMIT $offset, $entries_per_page") or die ("Query failed!");
               while ($row = mysql_fetch_array($this->result)) {
                     // SOME NICE FORMATTING HERE;
                     $display_name = nl2br(htmlspecialchars($row["name"]));
                     $display_email = nl2br(htmlspecialchars($row["email"]));
      $display_country = nl2br(htmlspecialchars($row["country"]));
                     $display_message = nl2br(htmlspecialchars($row["message"]));
                     // THIS ALLOWS USING SMILIES AND IS NOT DANGEROUS;
                     $display_message = str_replace ("&lt;img src=smiles/", "<img src=smiles/", $display_message);
                     $display_message = str_replace ("&gt;", ">", $display_message);
                     // DISPLAY WHAT WE HAVE AT LAST;
                     echo "<hr>Name: <b>[" . $display_name . " ]</b>, <i>" . $row["date"] . "</i><br>" . "Email: <a href=mailto:" . $display_email . ">" . $display_email . "</a><br>Country: ". $display_country ."<br>" . $display_message;
               }
 /******************************************************************************/
 /*  This code here handles pages stuff, number and next/previous links, etc.  */
 /*  If you don't need some of the features, just delete corresponding parts.  */
 /******************************************************************************/
               $this->count_result = mysql_query("SELECT count(id) AS number FROM $this->table") or die ("Query failed!");
               while ($count = mysql_fetch_array($this->count_result)) {
                     $total_entries = $count["number"];
               }
               // HOW MANY PAGES OF RECORDS WE HAVE;
               // THIS BLOCK IS ESSENTIAL FOR FURTHER PARTS;
               $pages = $total_entries / $entries_per_page;
               if ($pages < 1) {
                    $pages = 1;
               }
               if ($pages / (int) $pages <> 1) {
                    $pages = (int) $pages + 1;
               }
               else {
                    $pages = $pages;
               }
              if (($offset > $total_entries) or (!is_numeric($offset)))
           $offset = 0; 
       // CURRENT PAGE NUMBER;
        $pagenow = ($offset/$entries_per_page + 1);
               echo "<div align=center><br>* * *<br>Page " . $pagenow . " of " . $pages;
               // NEXT/PREVIOUS PAGE LINKS DISPLAY
               $next = $offset + $entries_per_page;
               $previous = $offset - $entries_per_page;
               if ($pages <> 1) {
                  echo " || ";
                  if ($previous < 0) {
                     echo "<a href=gb.php?offset=" . $next . ">";
                     echo "<acronym title='Next " . $entries_per_page . " records'>>>></acronym></a>";
                  }
                  elseif ($next >= $total_entries) {
                     echo "<a href=gb.php?offset=" . $previous . ">";
                     echo "<acronym title='Previous " . $entries_per_page . " records'><<<</acronym></a>";
                  }
                  else {
                    echo "<a href=gb.php?offset=" . $previous . ">";
                    echo "<acronym title='Previous " . $entries_per_page . " records'><<<</acronym></a>";
                    echo " | ";
                    echo "<a href=gb.php?offset=" . $next . ">";
                    echo "<acronym title='Next " . $entries_per_page . " records'>>>></acronym></a>";
                  }
                  echo "</div><br>";
               }
               // DISPLAY LINKS TO ALL PAGES SEPARATELY;
               echo "<div align=center>Pages: ";
               $i = 0;
               while ($i < $pages) {
                     $ri = $i + 1;
                     $showpage = $i * $entries_per_page;
                     if ($ri == $pagenow)
                        echo $ri . " ";
                     else
                        echo "<a href=gb.php?offset=" . $showpage . ">" . $ri . "</a> ";
                     $i++;
               }
               echo "</div>";
       }
 /******************************************************************************/
 /* End of pages code, this section is the longest, but you get pages features */
 /******************************************************************************/
       /* ADD RECORDS TO DATABASE */
       function add_record($name, $email, $message, $smilies="on", $webmaster, $message_length, $language_filter, $bad_words, $country)
       {
             if ($email == "") {
                $email = "no_email";
             }
    if ($country == "")
    {
     $country = "-";
    }
    
             // IF LANGUAGE FILTER IS ENABLED AND WEBMASTER EMAIL ADDRESS DEFINED DO THIS;
             if (($language_filter == 1) and (strlen($webmaster) <> 0)) {
                for ($i=0;$i<sizeof($bad_words);$i++) {
                    if ((strstr($name, $bad_words[$i])) or (strstr($email, $bad_words[$i])) or (strstr($message, $bad_words[$i]))) {
                       $warningmessage = "Name: " . $name . "\nEmail: " . $email . "\nMessage: " . $message;
                       @mail($webmaster, "Bad language in the guestbook", $warningmessage);
                    }
                }
             }
                // IF THERE ARE LIMITS ON MESSAGE LENGTH CUT IT TO DEFINED LIMIT;
                if ($message_length <> 0) {
                   $message = substr($message, 0, $message_length);
                }

                // IF USER USES SMILIES DO THIS;
                if ((isset($smilies)) and ($smilies == "on")) {
                   $format_smilies = array (
                                        ":-)", "<img src=smiles/icon_smile.gif alt=\'Smile\'>",
                                        "8-)", "<img src=smiles/icon_smile_8ball.gif alt=\'Glasses\'>",
                                        ":(", "<img src=smiles/icon_smile_angry.gif alt=\'Angry\'>",
                                        ":-D", "<img src=smiles/icon_smile_big.gif alt=\'Big smile\'>",
                                        "%-)", "<img src=smiles/icon_smile_cool.gif alt=\'I am cool\'>",
                                        ">8-|", "<img src=smiles/icon_smile_evil.gif alt=\'Evil\'>",
                                        ":-o", "<img src=smiles/icon_smile_kisses.gif alt=\'Kiss you\'>",
                                        "?", "<img src=smiles/icon_smile_question.gif alt=\'Question\'>",
                                        ":-(", "<img src=smiles/icon_smile_sad.gif alt=\'Sad\'>",
                                        "[$-)", "<img src=smiles/icon_smile_sleepy.gif alt=\'Sleepy\'>",
                                        ":-P", "<img src=smiles/icon_smile_tongue.gif alt=\'Tongue\'>",
                                        ";-)", "<img src=smiles/icon_smile_wink.gif alt=\'Wink\'>"
                                            );

                    for ($i=0;$i<sizeof($format_smilies);$i=$i+2) {
                        $message = str_replace($format_smilies[$i], $format_smilies[$i+1], $message);
                    }
                }

                $this->result = mysql_query("INSERT INTO $this->table (name, email, message, date, country) VALUES ('$name', '$email', '$message', NOW(), '$country')");
                // When guestbook is signed a message is emailed
                // to webmaster if this feature is enabled;
                if (strlen($webmaster) <> 0) {
                  $sendmessage = "Name: " . $name . "\nEmail: " . $email . "\nMessage: " . $message;
                  @mail($webmaster, "Guestbook signed", $sendmessage);
                }
                if (!$this->result)
                   echo "Error!";
       }
       /* DISCONNECT FROM DATABASE */
       function disconnect_db()
       {
               mysql_close($this->dbc);
       }
 }
 /******************************************************************************/
 /*                              END OF GUESTBOOK CLASS                        */
 /******************************************************************************/


 /******************************************************************************/
 /* INSTALLATION:             */
 /* 1) create a table in the MYSQL database with a query:        */
 /* CREATE TABLE guestbook (            */
 /*              id int(5) NOT NULL auto_increment,         */
 /*              name varchar(50),           */
 /*              email varchar(50),           */
 /*              message text,            */
 /*  date datetime,            */
 /*              PRIMARY KEY (id)           */
 /*                        )            */
 /* 2) define some variables below as they suit your environment;       */
 /* 3) possibly change any formatting in the display_records() function;       */
 /* 4) copy gb.php to your server and enjoy;          */
 /******************************************************************************/
 // Let's define some variables;
 $webmaster = '';    // EMAIL ADDRESS TO SEND WARNINGS TO
                                         // WHEN GUESTBOOK IS SIGNED; LEAVE
                                         // EMPTY IF YOU WANT THIS FEATURE 
                                         // DISABLED;
 $server = 'localhost';                  // DATABASE SERVER;
 $database = 'test';               // DATABASE NAME;
 $user = 'root';                             // USER TO CONNECT TO DATABASE;
 $password = '';                         // USER PASSWORD;
 $entries_per_page = 5;                  // HOW MANY RECORDS PER PAGE;
 $message_length = 1024;                 // MESSAGE LENGTH ALLOWED, LEAVE 0
                                         // IF YOU WANT ANY SIZE MESSAGES,
                                         // THIS CUTS MESSAGE TO DEFINED SIZE;
 $language_filter = 1;                   // 1 - enable language filter;
                                         // 0 - disable language filter;
 $bad_words = array (                    // Bad words vocabulary (add your own);
            'bottom', 'trousers'
                    );
 // Let's spawn an instance of guestbook class;
 $myGB = new Guestbook;
 $myGB->connect_db($server, $database, $user, $password);
 
 // aw- put the POST variables into the variables used in the script 
 $message = $_POST['message'];
 $email = $_POST['email'];
 $name = $_POST['name'];
 $smilies = $_POST['smilies'];
 $country = $_POST['country'];
 
 // If user submitted form, add a record;
 if (isset($message)) {
    if (!isset($smilies))
       $myGB->add_record($name, $email, $message, "no", $webmaster, $message_length, $language_filter, $bad_words, $country);
    else
       $myGB->add_record($name, $email, $message, $smilies, $webmaster, $message_length, $language_filter, $bad_words, $country);
 }
 // If opened without $offset variable defined, it is zero;
 if ((!isset($offset)) or ($offset < 0) or (!is_numeric($offset))) $offset = 0;
 $myGB->display_records($offset, $entries_per_page);
 $myGB->disconnect_db();
 ?>
 <div align=center>
 <table border=0 cellspacing=10 cellpadding=10 width=85% align=center>
 <tr>
 <td valign=top align=center width=60%>
 <p><strong>Add your message:</strong><br>
 (*) Required fields
 <form name=myGB action=gb.php method=post>
 * Name:<br><input type='text' name='name' maxlength=30><br>
 Email:<br><input type='text' name='email' maxlength=30><br>
 * Message:<br><textarea name='message' rows=10 cols=30></textarea><br>
 Country:<br><input type='text' name='country' maxlength=30></input><br>
 <input type=checkbox name='smilies' value='on' checked> Use image smilies<br><br>
 <input type=button value=' Leave message ' onClick="javascript:checkGB();">
 </form>
 </td>
 <td valign=top width=40%>
 <b>Smilies:</b><br><br>
 <table border=1 cellpadding=5>
 <tr><td>
 <img src=smiles/icon_smile.gif alt='Smile'> :-)
 </td><td>
 <img src=smiles/icon_smile_8ball.gif alt='Glasses'> 8-)
 </td><td>
 <img src=smiles/icon_smile_angry.gif alt='Angry'> :(
 </td></tr><tr><td>
 <img src=smiles/icon_smile_big.gif alt='Big smile'> :-D
 </td><td>
 <img src=smiles/icon_smile_cool.gif alt='I am cool'> %-)
 </td><td>
 <img src=smiles/icon_smile_evil.gif alt='Evil'> >8-|
 </td></tr><tr><td>
 <img src=smiles/icon_smile_kisses.gif alt='Kiss you'> :-o
 </td><td>
 <img src=smiles/icon_smile_question.gif alt='Question'> ?
 </td><td>
 <img src=smiles/icon_smile_sad.gif alt='Sad'> :-(
 </td></tr><tr><td>
 <img src=smiles/icon_smile_sleepy.gif alt='Sleepy'> [$-)
 </td><td>
 <img src=smiles/icon_smile_tongue.gif alt='Tongue'> :-P
 </td><td>
 <img src=smiles/icon_smile_wink.gif alt='Wink'> ;-)
 </td></tr></table>

 </td>
 </tr>
 </table>
 </div>

</body>
</html>

Second challenge:
If you don't know about Regular Expression, go to http://www.regular-expressions.info/tutorial.html to get better understanding how Regular Expression works.

PHP has a function that performs a regular expression match called preg_match.

The challenge is to check whether the number entered is a valid Australian number and whether it's a mobile or land line number.

Regular expression for valid Australian phone number can be found on http://regexlib.com/REDetails.aspx?regexp_id=66. You can also copy the regex from the code below.

<?php
if(!empty($_GET['phone']))
{
 $pattern = '/(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)/';
 $subject = $_GET['phone'];
 if(preg_match($pattern, $subject)>0)
 {
  echo "Your phone number is Australian.";
  if(substr($subject,0,2) == "04")
   echo " It's a mobile phone";
  else
   echo " It's a land line / premium number.";
 }
 else
  echo "Not an Australian number";
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

 <title>Phone REGEX</title>
 
</head>
<body>
<form name="form1" action="phone.php" method="get">
<input type="text" name="phone"/>
<input type="submit" name="submit" value="Press me" />
</form>
</body>

0 comments:

Post a Comment