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

Tuesday, September 21, 2010

Week 8 Challenge: Javascript

5:42 PM Posted by viperfx07 No comments
This week's challenge is about JavaScript. Specifically, it's about a Date() function to how many days old you are and pop up this value in an alert box on an html page as it opens. Find out the codes below...


<!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>
 <title>My Blog</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
 <script type="text/javascript">
  //Reference: http://www.javascriptkit.com/javatutors/datedifference.shtml
  function calcDate()
  {
  var today = new Date();
  var mybirthday = new Date(2010, 9, 5); //month is 0-11 in Javascript

  //Set 1 day in milliseconds
  var one_day=1000*60*60*24;

  //Calculate difference btw the two dates, and convert to days 
  alert("You are "+Math.ceil((today.getTime()-mybirthday.getTime())/(one_day))+" days old!");
  }   
 </script>
</head>
<body onload="calcDate()">
</body>
</html>

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>

Tuesday, September 7, 2010

Week 6 Practical Exercise (Challenge Only)

4:21 PM Posted by viperfx07 No comments
Challenge week 6 is about CSS layout.
To get the same result is impossible, but I guess I do it OK.
Below is the code...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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>Week 6's Challenge</title>
<style type="text/css">
<!--
#right-insert
{
    float:right;
 background-color: #909090;
    font-size: 35px;
    color: #ED4623;
    padding: 10px 2px 10px 5px;
 text-align:justify;
    width: 190px;
 font-family: "Times New Roman", sans-serif;
 letter-spacing: 1px;
    margin-right: 500px;
}
p
{
 margin-right: 600px;
 text-align:justify;
}
-->
</style>
</head>
<body>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sem sapien, bibendum ut tincidunt sit amet, dapibus a augue. Vivamus iaculis malesuada velit sit amet euismod. Integer feugiat nisi at enim mattis at feugiat libero pretium. Nunc porta porttitor varius. Vivamus non felis quis magna bibendum varius. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus tincidunt justo dictum nisi fermentum ut facilisis libero ultrices. Maecenas lobortis interdum magna, sed convallis felis convallis eget. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi tincidunt purus sit amet neque suscipit tempor. Nunc sem eros, ullamcorper nec pulvinar nec, placerat bibendum lorem.
</p>
<div id="right-insert">
this is some text in a box text text text text
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sem sapien, bibendum ut tincidunt sit amet, dapibus a augue. Vivamus iaculis malesuada velit sit amet euismod. Integer feugiat nisi at enim mattis at feugiat libero pretium. Nunc porta porttitor varius. Vivamus non felis quis magna bibendum varius. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus tincidunt justo dictum nisi fermentum ut facilisis libero ultrices. Maecenas lobortis interdum magna, sed convallis felis convallis eget. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi tincidunt purus sit amet neque suscipit tempor. Nunc sem eros, ullamcorper nec pulvinar nec, placerat bibendum lorem.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sem sapien, bibendum ut tincidunt sit amet, dapibus a augue. Vivamus iaculis malesuada velit sit amet euismod. Integer feugiat nisi at enim mattis at feugiat libero pretium. Nunc porta porttitor varius. Vivamus non felis quis magna bibendum varius. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus tincidunt justo dictum nisi fermentum ut facilisis libero ultrices. Maecenas lobortis interdum magna, sed convallis felis convallis eget. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi tincidunt purus sit amet neque suscipit tempor. Nunc sem eros, ullamcorper nec pulvinar nec, placerat bibendum lorem.
</p>
</body>
</html>

Wednesday, September 1, 2010

Week 5 Practical Exercise (Challenge only).

12:37 AM Posted by viperfx07 1 comment
The practical exercise is quite easy so I just went straight to the challenge
The challenge:
If you have time at the end, experiment with the :hover pseudo-class to make the page interactive. Make the text of a post get bigger if you hover over it. Make the contents of the posts appear only when you hover the mouse over the title.

I decided to divide the challenge into 2 sections:
1. Making the post get bigger (easiest)
2. Make the contents of the posts appear only when you hover the mouse over the title. (the trickiest one)


And, I was a bit stuck with the second one, but finally got it after Googling.

1. For the first challenge, it is pretty straightforward. The workflow is when you hover the ".entry" class, you get bigger font-size. The CSS code:
.entry:hover 
{
 font-size:30px; /*You can change the size to whatever you want*/
}

2. For the second challenge, we have to use the indirect sibling selector to get the effect that we want. The CSS code:
p
{
 visibility: hidden; /*set default p as hidden*/
}

h2:hover ~ p
{
 visibility: visible; /*when you hover h2, you will get p visible (as well)*/
}