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:
 https://www.paypal.com/cgi-bin/webscr?cmd=p/sell/mc/mc_wa-outside
 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>
  </select>

Result:

PHP, generate image from text



First you need to enable php_gd2.dll in php.in (remove;)
extension=php_gd2.dll 
Example code gd2.php:
(you need to copy arial.ttf from C:/Windows/Fonts/  to the same directory of gd2.php)
<?php
   
    $size = 30;
    $font = 'arial.ttf';
    $text = "jiansenlu.blogspot.com";
    $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');
    imagegif($img);
    ?>

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:  
<?php
session_start();
echo "views = ". $_SESSION['views']; //retrieve data
?>
To destroy a session

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

3. Cookie example:
<?php
$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`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
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`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


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.
Code:
<?php
    $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="">
    <thead>
        <tr>
            <th scope="col">Module Title</th>
            <th scope="col">Module Fee </th>
            <th scope="col">Approved </th>
            <th scope="col">Date</th>
        </tr>
    </thead>';
 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:
http://www.tinymce.com/
To use TinyMCE:
<script type="text/javascript" src="tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "advanced"
});
</script>
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



Purpose:
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" />
</form>
<?php
  if(isset($_POST['submit_docs'])){
          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>";
          exit;
          }
?>

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
<?php
$amount=1.2;
echo number_format($amount,2);
?>
will produce 1.20 output.
similar function sprintf
example
<?php
$amount=1.2;
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`)
) ENGINE=MyISAM   DEFAULT CHARSET=utf8;


`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;
         $amount=27;
         $tran_id=1234;        
        $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:
Example
<?php
$mystring='test';
echo '\r\n';
echo '$mystring';
?>
will output
 \r\n$mystring

 Single quote(" ")  will  interpret more escape sequences for special characters:
Example:
 <?php
$mystring='test';
echo "\r\n";
echo "$mystring"
?>
will output
test
 echo "\r\n";  interpret as return key.

Review of Jiansenlu.blogspot.com




Check my site review via:
http://www.webstatsdomain.com 

Jiansenlu.blogspot.com 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. 
Jiansenlu.blogspot.com has 14% seo score.
Jiansenlu.blogspot.com is safe and can be available by 
children, contains no malicious software and is not used for phishing.

Summary statistics for jiansenlu.blogspot.com

Title: Jiansen Lu's Computing Blog
Alexa Rank: 8,718,986
Pagerank: Check google pagerank for jiansenlu.blogspot.com Take this button and put in your website
Website Worth:
SEO score:
Rating:
**** 4 out of 5 by
IP-address: 74.125.228.76
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:
 https://www.sandbox.paypal.com
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  http://www.zen-cart.com/index.php
(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 php.in add 
date.timezone = 'America/Vancouver' and restart webserver.
or
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']; ?>">
and 
 <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:  www.example.com/index.php?a=test

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

Reference:

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`)
) ENGINE=MyISAM AUTO_INCREMENT=82 DEFAULT CHARSET=utf8;

  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';
setTimeout("CheckTime()",999);
}
function CheckTime(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds' ;
if(total_seconds <=0){
setTimeout('document.quiz.submit()',1);
   
    } else
    {
total_seconds = total_seconds -1;
max_time = parseInt(total_seconds/60);
c_seconds = parseInt(total_seconds%60);
setTimeout("CheckTime()",999);
}

}
init();
</script>

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!");
document.quiz.submit();
}
window.onbeforeunload= function() {
setTimeout('document.quiz.submit()',1);
}
</script>

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

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="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<SCRIPT LANGUAGE="JavaScript"><!--
setTimeout('document.test.submit()',10000);
//--></SCRIPT>

</head>

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

test_timer3.php in action:
<?php 

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.

Note:
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 = Y.one('#quiznavbutton' + questionid);
    navlink.removeClass('flagged');
    if (newstate == 1) {
        navlink.addClass('flagged');
        navlink.one('.accesshide .flagstate').setContent(M.str.question.flagged);
    } else {
        navlink.one('.accesshide .flagstate').setContent('');
    }
};

Another way to define namespace:

var model = namespace(M.mod_quiz.nav);
model.update_flag_state = function(attemptid, questionid, newstate) {
 
}  
 
Reference:
 http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/

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:
http://yuilibrary.com/

YUI JS library can be downloaded from:
http://yuilibrary.com/download/yui3/

Or you can directly use:
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></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:
http://www.ultrapico.com/Expresso.htm

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:
http://jiansenlu.comze.com/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="http://www.youtube.com/embed/'.$VIDEO_ID.'" frameborder="0"></iframe>';
     return $ytcode;
}
add_shortcode('yt', 'yt_func');

the BBcode usage is [yt]Video_Id[/yt],
example:
[yt]JW5meKfy3fY[/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;
}

add_shortcode('ads','showads');

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:
http://wp.tutsplus.com/tutorials/theme-development/wordpress-shortcodes-the-right-way/