Friday, August 30, 2013

Run JavaScript, CSS and HTML code online using jsfiddle.net



We can run JavaScript, CSS and HTML online on website:
http://jsfiddle.net/
In this website, the top left column is HTML code, right column CSS code, bottom left javaScript code. After clicking Run, the result will be shown in the right bottom.
In the left menu of Framework and extensions, we can select different JavaScipt libraries:
Mootools, jQuery, Prototype, YUI, Glow, Dojo, Processing.js, ExtJS, Raphael,  Right.JS, three.js, Zepto, Enyo, shipyear, knockout.JS,  The X Toolkit, AngulatJS, Ember and much more.

clear: both in CSS



In web design, we may have 1 header, 1 left menu bar, 1 content (right of menu) and 1 footer..
 <div id="header">Header</div>
<div id="menu">Left menu bar</div>

<div id="content">Some Content</div>
<div id="footer">Footer</div>

Normally we  use float:left  for  menu and content.
#menu, #content{
float: left;
}
Even we do not use float:left  for footer, it may stay the same row with content. 
We need to use clear: both in  footer CSS to move footer below the content and menu.
#footer{
clear: both;
}
We do not need to do this for header as the CSS after header will not impact header CSS.
clear:both syntax:
No floating elements allowed on the left or the right side of a specified paragraph:

PHP, to detect mobile device



The following PHP function is used to detect mobile device: ipod, iphone, blackberry and android
, if from mobile device, the function will return true.
function is_mobile_device() {
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    return ((stripos($agent, 'ipod') !== false && stripos($agent, 'ipod') >= 0) ||
            (stripos($agent, 'iphone') !== false && stripos($agent, 'iphone') >= 0) ||
            (stripos($agent, 'blackberry') !== false && stripos($agent, 'blackberry') >= 0) ||
            (stripos($agent, 'android') !== false && stripos($agent, 'android') >= 0))
            ? true : false;
}


Note: _SERVER['HTTP_USER_AGENT'] is used to retrieve information about the users browser, computer operating system and mobile type.
striposFind the position of the first occurrence of a case-insensitive substring in a string.
Returns FALSE if the needle was not found.

Wednesday, August 28, 2013

Difference between div and span in HTML tags



There are some similarity  between div and span. Both of them can be used to mark an element using id and class. But there are also some difference,  <div> is a block element, <span> is inline element..
We can put <span> inside <div>, but can not put <div> inside <span>
<div><span></span></div> OK;
<span><div></div></span> illegal.

Convert PHP associative array to javascript associative array



Convert PHP associative array to javascript associative array, example:
 <?php
$arr = array('price' => 2, 'high' => 3, 'low' => 1);
echo json_encode($arr);
?>
<script>
    var quote=<?php echo json_encode($arr); ?>;
    alert(quote["price"]);
    alert(quote.price);
</script>

PHP function json_encode is used to convert to the JSON representation of a value. Here
json_encode($arr) produce:
{"price":2,"high":3,"low":1}
Then we can create an associative array in JavaScript using
  var quote=<?php echo json_encode($arr); ?>;
We can assess the  array value either via quote["price"] or json_encode($arr).

PHP Savant template



Savant is a powerful but lightweight object-oriented template system for PHP.
Savant is used Atutor LMS etc.Savant3 can be downloaded from
http://phpsavant.com/
Example: example.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require($_SERVER['DOCUMENT_ROOT'].'/_classes/Savant3/Savant3.php');
$tpl = new Savant3();
// Directly assgn  $tpl->title
$tpl->title = 'My Page Title';
$tpl->display('assign.tpl.php');
?>

template file:  assign.tpl.php
<html>
    <head>
        <title><?php echo $this->eprint($this->title); ?></title>
        <?php echo $this->eprint($this->title); ?>
    </body>
</html
>

Video: PHP Savant template

Tuesday, August 27, 2013

PHP cron job in Windows



To run a PHP code daily in your Windows such as backup database and sending email notices etc, first create a file c:\cron\cron.php, for example:
<?php
require_once($web_root.'_includes/db_constants.inc.php');
require_once($web_root.'_includes/email_content.inc.php');
require_once($web_root.'_classes/PHPMailer_v2.0.0/class.phpmailer.php');

$db = @mysql_connect(DB_HOST . ':' . DB_PORT, DB_USER, DB_PASSWORD);
if (!$db) {
   $mail = new PHPMailer;
   $mail->From     = MAIL_CESEI_ADMIN;
   $mail->FromName = $_mail_from_name_cesei;
   $mail->AddAddress(MAIL_CESEI_ADMIN);
   $mail->Subject = 'Cron DB connect error';
   $mail->Body    = 'DB failure - @mysql_connect('.DB_HOST . ':' . DB_PORT.' '.DB_USER.' '.DB_PASSWORD.');';
   $mail->Send();
   unset($mail);
   exit;
}
if (!@mysql_select_db(DB_NAME, $db)) {
   $mail = new PHPMailer;
   $mail->AddAddress(MAIL_CESEI_ADMIN);
   $mail->Subject = 'Cron DB connect error';
   $mail->Body    = 'DB failure - @mysql_select_db('.DB_NAME.');';
   $mail->Send();
   unset($mail);
   exit;
}

?>
To run cron.php daily, using Windows scheduler.
Schedule task:
php c:\cron\cron.php
Schedule:
Daily start time 12:00 am every 1 day

Wednesday, August 21, 2013

Single quotes for strings in MySQL query



In MySQL query,   single quotes should be added for strings.
Wrong MYSQL syntax: (need to put a single quote in string test@gmail.com)
SELECT revision FROM cesei_new1.cesei_review_new WHERE module_id=127 AND email=test@example.com ORDER BY revision ASC 
Right  MYSQL syntax:
SELECT revision FROM cesei_new1.cesei_review_new WHERE module_id=127 AND email='test@example.com' ORDER BY revision ASC


We are easy to make this mistake in PHP MYSQL programming. PHP right syntax example:
        $module_id=mysql_real_escape_string(trim($_POST['module_id']));
         $email=mysql_real_escape_string(trim($_POST['email']));
       $sql = "SELECT revision  FROM cesei_review_new WHERE module_id=$module_id AND email='$email' ORDER BY revision ASC";
       $result = mysql_query($sql, $db);
       while ($row = mysql_fetch_assoc($result)) {  
        $revision = $row['revision']+1;
       }


wrong syntax:
       $sql = "SELECT revision  FROM cesei_review_new WHERE module_id=$module_id AND email=$email ORDER BY revision ASC";

 $module_id is a number, we do not have to add single quotes, while $email is a string and we have to add single quotes.

Tuesday, August 20, 2013

A simple way to validate email address using filter_var



A simple way to validate email address is to use filter_var, for example:
 if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
      {echo ''Your email address is not a valid email address";}

There are other options for filter_var function:
PHP function filter_var — Filters a variable with a specified filter

option: FILTER_VALIDATE_EMAIL,FILTER_VALIDATE_IP,FILTER_VALIDATE_URL, FILTER_VALIDATE_INT,  FILTER_VALIDATE_BOOLEAN, FILTER_VALIDATE_FLOAT, FILTER_VALIDATE_REGEXP

Video: PHP, verify email address and IP address using filter_var

mysql_real_escape_string and htmlspecialchars in PHP



mysql_real_escape_string
  prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

htmlspecialchars performed translations:
  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' (or &apos;) only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'  
Should we use mysql_real_escape_string(htmlspecialchars( $value )) to prevent sql injection?

To prevent mysql injection, mysql_real_escape_string is enough. It is better to preserve the original data not using htmlspecialchars. But when we extract the data from mysql database and present them in HTML file, we need to  add  htmlspecialchars.

HTM5 input type



In HTML4, we have following input types:
submit: 
<input name="submit_form" type="submit" value="Submit this form" />
 text:
<input name="comments" size="50" type="text" />.
 Check boxs
<input name="color[]" type="checkbox" value="yellow" />yellow
 Radio box:
<input name="class" type="radio" value="1" />1
file, password, button, hidden, image, reset.

In HTML5, more types are added:
color, date, datetime,datetime-local, email, month, number,range,search, tel,time, url, week.

More reading:

 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input