Saturday, June 30, 2012

Two hour video tutorial for CSS

This two hour CSS video tutorial gives an introduction to the basics of Cascading Style Sheets covering the structure of a CSS property, classes, element selectors, pseudo-classes, pseudo-elements, compound and simple selectors, the use of selectors, internal and external style-sheets, basic properties, CSS specificity, CSS Menus, CSS Navigation, and basic debugging of CSS with a Firefox web development tool (Firebug) and browser compatibility.

Thursday, June 28, 2012

Paypal currency code:

Paypal currency code can be found here:
 The dropdown menu of PaylPal currency:
 <select name="currency">
  <option value="CAD" selected>CAD - Canadian Dollars</option>
  <option value="AUD">AUD - Australian Dollars</option>
  <option value="BRL">BRL - Brazilian Reais</option>
  <option value="GBP">GBP - British Pounds</option>
  <option value="CZK">CZK - Czech Koruny</option>
  <option value="DKK">DKK - Danish Kroner</option>
  <option value="EUR">EUR - Euros</option>
  <option value="HKD">HKD - Hong Kong Dollars</option>
  <option value="HUF">HUF - Hungarian Forints</option>
  <option value="ILS">ILS - Israeli New Shekels</option>
  <option value="JPY">JPY - Japanese Yen</option>
  <option value="MYR">MYR - Malaysian Ringgit</option>
<option value="MXN">MXN - Mexican Pesos</option>
  <option value="TWD">TWD - New Taiwan Dollars</option>
<option value="NZD">NZD - New Zealand Dollars</option>
  <option value="NOK">NOK - Norwegian Kroner</option>
<option value="PHP">PHP - Philippine Pesos</option>
<option value="PLN">PLN - Polish Zlotys</option>
  <option value="SGD">SGD - Singapore Dollars</option>
<option value="SEK">SEK - Swedish Kronor</option>
<option value="CHF">CHF - Swiss Francs</option>
  <option value="THB">THB - Thai Baht</option>
<option value="TRY">TRY - Turkish Liras</option>
<option value="USD">USD - U.S. Dollars</option>


PHP, generate image from text

First you need to enable php_gd2.dll in (remove;)
Example code gd2.php:
(you need to copy arial.ttf from C:/Windows/Fonts/  to the same directory of gd2.php)
    $size = 30;
    $font = 'arial.ttf';
    $text = "";
    $img = imagecreate(600, 80);
    imagecolorallocate($img, 0xff, 0xcc, 0xcc);
    $black = imagecolorallocate($img, 0, 0, 0);
    imagettftext($img, $size, 0, 100, 50, $black, $font, $text);
    header('Content-Type: image/gif');

Result: gd2.gif

PHP Security

PHP security is mainly from:
 1、Command Injection
2、Eval Injection
3、Script Insertion
4、Cross Site Scripting, XSS
5、SQL injection
6、Cross Site Request Forgeries, CSRF
7、Session Hijacking
8、Session Fixation
9、HTTP Response Splitting
10、File Upload Attack
11、Directory Traversal
12、Remote Inclusion
13、Dynamic Variable Evaluation
14、URL attack
 15、Spoofed Form Submissions
16、Spoofed HTTP Requests

Wednesday, June 27, 2012

Cookie and Session in PHP

Cookie is similar to session to store temporary data. The difference is that cookie stores data in browser and user can block cookie setting in browser. For independent browser setting, session is better. Below are some tips:
1.  How long will my session  last  in PHP?
 This is set in php.ini:
session.gc_maxlifetime = 1440
which is 1440 seconds, i.e 24 minutes

We can also set it in PHP scripts: for example set it as 30 minutes
ini_set(’session.gc_maxlifetime’, 30*60);
In my LMS web design, I prefer to set session maximum time 10 hours so users have enough time to do exam on-line and browse content.
@ini_set('session.gc_maxlifetime', '36000'); /* 10 hours */
2, session example:
 To start a session:
<?php session_start(); // start up your PHP session! ?>
To store some data in session: for example test_session.php
<?php session_start(); $_SESSION['views'] = 1; // store session data ?>
To retrieve session data: retrieve_session.php, remember to add session_start(); at the beginning:  
echo "views = ". $_SESSION['views']; //retrieve data
To destroy a session

<?php session_start(); session_destroy(); ?>

3. Cookie example:
$value = 'Test';
setcookie("MyCookie", $value, time()+3600);  /* expire in 1 hour */
$MyCookie = $_COOKIE['MyCookie'];

Monday, June 25, 2012

Joint two tables in MySQL

We have table edu_payments:
CREATE TABLE  `cnsh_lms`.`edu_payments` (
  `payment_id` smallint(5) unsigned NOT NULL auto_increment,
  `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
  `approved` tinyint(4) NOT NULL default '0',
  `transaction_id` char(100) NOT NULL,
  `member_id` mediumint(8) unsigned NOT NULL,
  `course_id` mediumint(8) unsigned NOT NULL,
  `amount` decimal(7,2) NOT NULL default '0.00',
  PRIMARY KEY  (`payment_id`)
We have another table edu_courses
CREATE TABLE  `cnsh_lms`.`edu_courses` (
  `course_id` mediumint(8) unsigned NOT NULL auto_increment,
  `member_id` mediumint(8) unsigned NOT NULL default '0',
  `title` varchar(255) NOT NULL,
  PRIMARY KEY  (`course_id`)

They have same course_id. Final display is  title in the second table and timestamp, approved and amount in the first table. I use LEFT JOIN in this example.
    $sql = 'SELECT p.course_id, p.approved, p.amount, p.timestamp, c.title  FROM edu_payments p LEFT JOIN edu_courses c  ON  p.course_id =c.course_id WHERE p.member_id ='.$_SESSION['member_id'].' AND  p.course_id = '.$module_id;
 $result = mysql_query($sql, $db);
 $page_content .= '   
     <br /><br />
      <b>My  payments:</b>
        <table class="data static" rules="rows" summary="">
            <th scope="col">Module Title</th>
            <th scope="col">Module Fee </th>
            <th scope="col">Approved </th>
            <th scope="col">Date</th>
 while($row = mysql_fetch_assoc($result)){
        $page_content  .= '<tr>';      
        $page_content  .= '<td>'.substr($row['title'],0,8).'</td><td>$'.$row['amount'].'</td>';
        $page_content  .= '<td>'.$row['approved'].'</td>';
         $page_content  .= '<td>'.$row['timestamp'].'</td>';
         $page_content  .= '</tr>';
      $page_content  .= '</table>';
      echo  $page_content ;

PHP, Extract data array in MySQL

Below is the step to extract data array of MySQL in PHP
1) Define an array:
 $modules_payment = Array();
2)  Example Query
 $sql = 'SELECT * FROM edu_payments WHERE member_id ='.$_SESSION['member_id'];
  $result = mysql_query($sql, $db);
   while($row = mysql_fetch_assoc($result)){
      // Assign  MySQL result to a multi-dimensional array
       $modules_payment[] = $row;
3) Extract data from the multi-dimensional  array
foreach($modules_payment as $my_payment){
       foreach($my_payment as $key=>$payment) echo  $payment.'<br />';

Friday, June 22, 2012

Using tinyMCE as an editor in PHP

TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor. TinyMCE can be downloaded from:
 TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor.
TinyMCE can be downloaded from:
To use TinyMCE:
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
mode : "textareas",
theme : "advanced"
TinyMCE editor will be shown in the form starting with textarea: Example:
<textarea name="body" style="width:30%" rows="15" cols="10"> </textarea> 

A Serious Bug in Fireftp

When I used fireftp transfer files, I found sometimes whole directory files missing, sometimes file size not consistent.  This is quite annoying. I found this is due to that I used  Automated Mod (ASCII file type) and compress in Options->Tools->Uploads/Downloads. After I unchecked these two and use Binary Mode, the problem is fixed. But these should not happen.

Below is the correct options for Fireftp:

Export html form content to Word documents

In HTML form, when users type  the content and click  "Export as MS Word" button, the content will be exported   in Word documents.
Code in PHP:
<form name="proposal_form" action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post"">
 <textarea name="doc_body" id="doc_body" rows="5" class="mce-editor" style="width:100%; height:700px;"></textarea>
  <input type="submit" name="submit_docs" value="Export as MS Word" class="input-button" />
          header("Content-Type: application/vnd.msword");
          header("Expires: 0");
          header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("content-disposition: attachment;filename=sampleword.doc");
         echo "<html>";
          $doc_body = $_POST['doc_body'];
           echo "$doc_body";
          echo "</html>";

PHP function number_format

Sometimes we may require the output number is formated in PHP.  For example we need format
$ 1.2 to $1.20 and $1.223 to $1.22.  We can use PHP function  number_format.
PHP function number_format  sets the number of decimal points.
for example
echo number_format($amount,2);
will produce 1.20 output.
similar function sprintf
sprintf("%01.2f", $amount);
will produce the same result.

Thursday, June 21, 2012

PHP default time stamp in MySQL

When I created a edu_payments table in MySQL
CREATE TABLE  `cnsh_lms`.`edu_payments` (
  `payment_id` smallint(5) unsigned NOT NULL auto_increment,
  `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
  `approved` tinyint(4) NOT NULL default '0',
  `transaction_id` char(100) NOT NULL,
  `member_id` mediumint(8) unsigned NOT NULL,
  `course_id` mediumint(8) unsigned NOT NULL,
  `amount` decimal(7,2) NOT NULL default '0.00',
  PRIMARY KEY  (`payment_id`)

`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
will  automatically  set to the current timestamp when the record is created if the column is set to NULL or is not specified at all.

For example
 INSERT INTO edu_payments VALUES ('', NULL, 0, '', '{$_SESSION['member_id']}', '$module_id', 0)
I put the NULL in timestamp and  the time display as 2012-06-21 16:25:22
1, 2012-06-21 16:25:22, 1, '1234', 16, 104, 27.00

When you insert the time, the timestamp should have similar format.
      $payment_id =1;
        $data=date('y-m-d G:i:s ');
        $sql = "UPDATE edu_payments SET  timestamp='$data', approved=1, transaction_id=$tran_id, amount=$amount WHERE payment_id=$payment_id";

i.e. input date should have   $data=date('y-m-d G:i:s '); where G is for 24 hours and g is for 12 hours

Difference between single quote and double quote in PHP

Single quote(' ') and double quote (" ")  both specify strings in PHP. But there some difference.
Single quote(' ')  will not  interpret more escape sequences for special characters:
echo '\r\n';
echo '$mystring';
will output

 Single quote(" ")  will  interpret more escape sequences for special characters:
echo "\r\n";
echo "$mystring"
will output
 echo "\r\n";  interpret as return key.

Review of

Check my site review via: is ranked 8,718,986 in the world 
(among the 30 million domains). This site is estimated worth 
$966USD. This site has a low Pagerank(1/10). It has 10
  backlinks. It's good for seo website. has 14% seo score. is safe and can be available by 
children, contains no malicious software and is not used for phishing.

Summary statistics for

Title: Jiansen Lu's Computing Blog
Alexa Rank: 8,718,986
Pagerank: Check google pagerank for Take this button and put in your website
Website Worth:
SEO score:
**** 4 out of 5 by
Description: Share experience on computer coding, courses, job interview questions make money on Internet and blogger FAQ
Alexa backlinks: 10
Magestic Backlinks: Picture shows the External Backlinks found over the last month

Friday, June 15, 2012

Delete Cookie in Firefox

When I test paypal code in paypal sandbox:
Due to that I typed wrong password, I can not access Paypal Sandbox anymore due to cookie set.
To remove cookie stored in Firefox,
1) Go to Firefox->Options
2) Select the Privacy panel.
3) Set Firefox will: to Use custom settings for history, select show cookies.
or click the link: remove individual cookies
4) Type sandbox in search box
5)  Select the cookie(s) in the list to remove and click Remove Cookie.

To remove all cookies:

1) Go to Firefox->Options
2) Select the Privacy panel.
3) Click the link: Clear Recent History....
4)  Set Time range to clear to Everything.
5) Click check-box of Cookies  and Click Clear Now

Thursday, June 14, 2012

Set date.timezone in php.ini

 When I installed zen cart
(Zen Cart® truly is the art of e-commerce; free, user-friendly, open source shopping cart software written in PHP).)There is an error message:
ERROR: date.timezone not set in php.ini. Please contact your hosting company to set the timezone in the server PHP configuration before continuing.

There are to ways to fix this:
1) in add 
date.timezone = 'America/Vancouver' and restart webserver.
2) going to zc_install/includes/application_top.php and add following line on the top:
ini_set('date.timezone', 'America/Vancouver');

Tuesday, June 12, 2012

PHP, difference between $_SERVER['PHP_SELF'] and $_SERVER['REQUEST_URI']

What is the difference  between $_SERVER['PHP_SELF'] and   $_SERVER['REQUEST_URI'] in PHP?
For example
 <form method="post" action="<?php  echo $_SERVER['PHP_SELF']; ?>">
 <form method="post" action="<?php  echo $_SERVER['REQUEST_URI'];  ?>">

  $_SERVER['PHP_SELF'] returns the file of current webpage,   $_SERVER['REQUEST_URI'] return the file name with variables.

For Example:

$_SERVER['PHP_SELF'] returns  index.php, while
$_SERVER['REQUEST_URI'] returns index.php?a=test.


Online quiz timer using JavaScript and PHP

To Design an online quiz timer using JavaScript and PHP:

1) To create a table to store  timer in minutes
CREATE TABLE  `cnsh_lms`.`edu_tests_extra` (
  `test_id` mediumint(8) unsigned NOT NULL auto_increment,
`timer` tinyint(4) unsigned NOT NULL,
`num_timer` bigint(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`test_id`)

  2)  To display a count down timer, the initialized  minutes  from $row_2['num_timer']  in above table. When down to 0, the form quiz is submitted.
 <div style="font-weight: bold" id="quiz-time-left"></div>
<script type="text/javascript">
var max_time = <?php echo $row_2['num_timer'] ?>;
var c_seconds  = 0;
var total_seconds =60*max_time;
max_time = parseInt(total_seconds/60);
c_seconds = parseInt(total_seconds%60);
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds';
function init(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds';
function CheckTime(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds' ;
if(total_seconds <=0){
    } else
total_seconds = total_seconds -1;
max_time = parseInt(total_seconds/60);
c_seconds = parseInt(total_seconds%60);


3) If you click refresh or go to another webpages, the for will be submitted auotomatically
<script type="text/javascript">
 function finishpage()
alert("unload event detected!");
window.onbeforeunload= function() {

4. The form
 <form method="post" name="quiz" id="quiz_form" action="take_test1.php" >

Thursday, June 7, 2012

Submit a HTML Form Using JavaScript

Normally we submit a HTML form by pressing a button. Sometimes we may need to submit thr form using JavaScript, for example online exam timer.

Example code: test_timer.html
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<SCRIPT LANGUAGE="JavaScript"><!--


<form name="test" id="form1" method="post" action="test_timer3.php">
    <input name="pattern" type="text" id="pattern" />
    <input name="show" type="hidden" id="show" value="quickref" />
  <p><input type="submit" name="SubmitForm" value="Submit Form" />
&nbsp;  </p>

test_timer3.php in action:

echo $_POST['SubmitForm'];
echo isset($_POST['SubmitForm']);
echo 'The form is submitted! '.$_POST['pattern'];

When you type you, after 10 seconds, the result: "The form is submitted! you" is produced.

1) when using JavaScript submits a form, $_POST['SubmitForm'] is not set.
2) The form name can not be "submit," i.e <input type="submit" name="submit" value="Submit Form" />
will cause JavaScript  document.test.submit()' confused.

Tuesday, June 5, 2012

JavaScript namespace

A lot of applications, such as Moodle LMS, YUI and the Dojo Toolkit use namespace in their JavaScript code. Namespace can  be used to mange JavaScript code and avoide conflict.

Example of namspace in Moodel LMS:
 Declare a name space M.mod_quiz.nav
M.mod_quiz.nav = M.mod_quiz.nav || {};
 Define a function  update_flag_state in namespace M.mod_quiz.nav
M.mod_quiz.nav.update_flag_state = function(attemptid, questionid, newstate) {
    var Y = M.mod_quiz.nav.Y;
    var navlink ='#quiznavbutton' + questionid);
    if (newstate == 1) {
        navlink.addClass('flagged');'.accesshide .flagstate').setContent(M.str.question.flagged);
    } else {'.accesshide .flagstate').setContent('');

Another way to define namespace:

var model = namespace(M.mod_quiz.nav);
model.update_flag_state = function(attemptid, questionid, newstate) {

YUI, a JavaScript library

Yahoo User Interface Library (YUI) is a free, open source JavaScript and CSS framework for building richly interactive web applications.  YUI can be used to build online graph and calendar easily. Moodle LMS uses YUI library.
Yui website:

YUI JS library can be downloaded from:

Or you can directly use:
<script src=""></script>
Go to YUI website for more examples. 

Clear Firefox history and cache

You may need to have a private moment in Firefox browser, especially in library or other public computers. You can clear Firefox history for your browsing.

At the top of the Firefox window, click the Firefox button, go over to the History menu and select Clear Recent History. You can select clear history in this hour, today or  all.

To clear Firefox cache, go to Options->advanced and click clear now button.

Another way is to use to "start private browsing" button in Firefox, then you do not need to clear Firefox history.

Friday, June 1, 2012

Simplify Regular Expression Using Expresso

Regular expression is a way to match string with particular characters, words, or patterns of characters. It is difficult to remember the match pattern syntax.

Now you can use Expresso to design your regular expression without too much memory.  You can down Expresso from:

After you install Expresso, you can do a test as following:
* Select the "Test Mode" tab
* Open the sample project from the File menu
* Click the "Run Match" button
* Observe the Search Results pane
* Expand the tree for details and click an item
* See it highlighted in the input text
* Click on the Expression Library tab and double-click on another expression
* "Run Match" again

Video: Understanding Regular Expressions
Series for the web administrator. Understanding Regular Expressions with a focus on URL Rewrite.

Add new BBcode in WordPress

You may  need to add new BBcode after you install WordPress.  This will speed your posting a lot.
Below is how I add newBBCode in my Wordpress:

Go to directory: wordpress/wp-content/themes/fresh-ink-magazine
(I used the theme fresh-ink-magazine, you need to go to your customized theme directory)
in functions.php
1) Add following code for youtube BBcode:

function yt_func($atts, $VIDEO_ID="") {
$ytcode='<iframe class="youtube-player" type="text/html" width="100%" height="390" src="'.$VIDEO_ID.'" frameborder="0"></iframe>';
     return $ytcode;
add_shortcode('yt', 'yt_func');

the BBcode usage is [yt]Video_Id[/yt],

The BBcode will not be shown in the editor menu. But you can use it in the post body.

2) The following is to create an Adsense BBcode:

function showads()
{$ad_code = 'put your your ad sense code here';
return $ad_code;


Replace   'put your your ad sense code here';   to your Adsense code.
The BBcode usage: [ads]

More on how to add the BBcode in the editor menu can be found: