Saturday, March 30, 2013

PHP, copy entire folder



In PHP, we use recursive method to copy the entire folder file. We create a class CopyFile and create
a constructor CopyFile($fromFile,$toFile)
Code:
<?php
    class CopyFile{
        public $fromFile;
        public $toFile;
        function CopyFile($fromFile,$toFile){

           if(is_file($fromFile)){
                copy($fromFile,$toFile);
                return;
            }
            $this->CreateFolder($toFile);
            $folder1=opendir($fromFile);
            while($f1=readdir($folder1)){
                if($f1!="." && $f1!=".."){
                    $path2="{$fromFile}/{$f1}";
                    if(is_file($path2)){
                        $file = $path2;
                        $newfile = "{$toFile}/{$f1}";
                        copy($file, $newfile);
                    }elseif(is_dir($path2)){
                        $toFiles = $toFile.'/'.$f1;
                        $this->copyFile($path2,$toFiles);
                    }
                }
            }
        }

        function CreateFolder($dir, $mode = 0777){
            if (is_dir($dir) || @mkdir($dir,$mode)){
                return true;
            }
            if (!$this->CreateFolder(dirname($dir),$mode)){
                return false;
            }
            return @mkdir($dir, $mode);
        }
    }
    ?>

To apply this class
 $file = new CopyFile('C:/test','C:/test1');

Thursday, March 28, 2013

Save Google translate text to speech result in audio mp3



How can I save "Some Tips on Web Design" text to speech in audio mp3 usimg Google translate?
It is easy. Copy the following URL in your Firefox:
http://translate.google.com/translate_tts?tl=en&q="Some Tips On Web Design"
and click File and save as a mp3 file to your local computer.
For other language and text,
change the tl=en  to the language you want, and  change  "Some Tips on Web Design" to the text you want to convert. But the text can not be long.
The first two pages of the following video used Google text to speech, the rest using text to wav.

Popular font type and font size in HTML body in web design



According to studies, the popular font type is 'Arial' and.font size 13px in HTML body.
In CSS:
font-family: arial, sans-serif;
 font-size: 13px; 
color: black;
The conversion between between em, px, pt and percent in font size is as follows:
1em = 12pt (point) = 16px (pixel) = 100% (percent).
1 point =1/12 inch
"percent %" is recommended for fully scalable of mobile devices and for accessibility.
such as
 html { font-size: 150%; )
or
body { font-size: 150%; )

‘Three Click Rule’ in web design



According to ‘Three Click Rule’  in web design,  users will feel frustrated and leave the websites after no finding right information within three mouse click.  We need to put most important information within  'three mouse click'  distance in our homepage.  A shallow structure of websites and easily reaching all indexed page will be also good for SEO and Internet speed.

Wednesday, March 27, 2013

PHP, get relevant URL of the current page


 In PHP project development, we often need to get some of the relevant URL of the current page, below is some tip:
 test URL:
 http://localhost/jiansenlu/index.php?userid=2
/ / Get the domain name or host address  localhost
  echo $ _SERVER ['HTTP_HOST']. "<br>";

 / / Get the web address 
/jiansenlu/index.php 
echo $ _SERVER ['PHP_SELF']. "<br>";
 

 / / Get URL parameters userid=2 
 echo $ _SERVER ["QUERY_STRING"]. "<br>";
 

 / / Get user agent 
 echo $ _SERVER ['HTTP_REFERER']. "<br>";
 

 Get the full url 
 http://localhost/jiansenlu/index.php?userid=2
 echo 'http://'. $ _SERVER ['HTTP_HOST']. $ _SERVER ['REQUEST_URI'];
or  
 echo 'http://'. $ _SERVER ['HTTP_HOST']. $ _SERVER ['PHP_SELF']. '?'. $ _SERVER ['QUERY_STRING'];
 

 / / contains the port number of the complete url
http://localhost:80/jiansenlu/index.php?userid=2  
 echo 'http://'. $ _SERVER ['SERVER_NAME']. ':'. $ _SERVER ["SERVER_PORT"]. $ _SERVER ["REQUEST_URI"];

 / / only take the path 
http://localhost/jiansenlu
$ url = 'http://'. $ _SERVER ['SERVER_NAME']. $ _SERVER ["REQUEST_URI"]; 
echo dirname ($ url);

Thursday, March 21, 2013

MySQL transaction log in PHP



We may need to create a log table for recording  MySQL transaction in PHP.
 Below is  the log table edu_admin_log
CREATE TABLE  edu_admin_log (
  `login` varchar(30) NOT NULL default '',
  `time` datetime NOT NULL default '0000-00-00 00:00:00',
  `operation` varchar(20) NOT NULL default '',
  `table` varchar(30) NOT NULL default '',
  `num_affected` tinyint(3) NOT NULL default '0',
  `details` text NOT NULL,
  KEY `login` (`login`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Here 'details' is sql query. Operation is 1,2,3,4 or 5, corresponding to  update,  delete, insert, replace and other action.

Create write_to_log function  to record MySQL transaction:
function write_to_log($operation_type, $table_name, $num_affected, $details) {
    global $db;
    static $now;

    if (!$now) {
        $now = date('Y-m-d H:i:s');
    }
    if ($num_affected > 0) {
        $details = addslashes(stripslashes($details));
        $sql    = "INSERT INTO edu_admin_log VALUES ('$_SESSION[login]', '$now', '$operation_type', '$table_name', $num_affected, '$details')";
        $result = mysql_query($sql, $db);
    }
}

Usage:
    $sql    = "DELETE FROM edu_member_track WHERE member_id=$id";
    mysql_query($sql, $db);
    write_to_log(2, 'member_track', mysql_affected_rows($db), $sql);

Switch between MySQL databases in PHP



Suppose we have db1 and db2 database in MySQL, we may need to switch between db1 and db2 often.
First we connect to MySQl database in PHP
$db mysql_connect('localhost''mysql_user''mysql_password');

Then we create a function switch_db and call PHP function mysql_select_db (note from PHP 5.5.0,  all PHP MySQL function  mysql_* will need to be change to mysqli_*

function switch_db($new_db){
   global $db;
   return mysql_select_db($new_db, $db);
}
 

to switch to db1:
  switch_db('db1');

Tuesday, March 19, 2013

check if mysql query returns empty in PHP



We can use PHP  function mysql_num_rows to check if mysql query returns empty.
Example code:
$sql    = "SELECT * FROM cesei_member_extra WHERE member_id = $id";
  $result = mysql_query($sql, $db);

if ($result) {
     if (mysql_num_rows($result) == 0) {
        echo "No result returns";     }
     else {
        echo  mysql_num_rows($result).'  rows returned';
     }
}

else{
      echo "Query error";
}
If the query is not empty, we can use mysql_fetch_assoc to get the result
    $enrollment_list         = Array();
    while($row = mysql_fetch_assoc($result)){ 
                    $enrollment_list[] = $row['member_id'];
           
             }

Create photo slideshow using YouTube photo slideshow creator



You don't have to use Window Movie Make to create  photo slideshow. You can directly use YouTube photo slideshow  creator to create a slide-show and upload it to YouTube.
Below is the procedure to create Youtube slide-show.
1) Click  upload
2) Click create button under photo slide-show
3)  Drag one photo and click add more photos, and drag another one
4) adjust Slide duration, transition, slide effect. and publish
Video:  the slide-show from YouTube photo slideshow creator:


Monday, March 18, 2013

MySQL, add a new column with modify time



I have a table cesei_member_extra:
CREATE TABLE cnsh_lms.`cesei_member_extra` (
  `member_id` mediumint(8) unsigned NOT NULL,
`dept_type` tinyint(4) NOT NULL DEFAULT '0',
`edu_type` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`member_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  Now I want to add a modification time, i.e. new column modify_date
 ALTER   TABLE  cnsh_lms.`cesei_member_extra` ADD COLUMN  modify_date datetime default '0000-00-00 00:00:00';
which equal to:
CREATE TABLE cnsh_lms.`cesei_member_extra` (
  `member_id` mediumint(8) unsigned NOT NULL,
`dept_type` tinyint(4) NOT NULL DEFAULT '0',
`edu_type` tinyint(4) NOT NULL DEFAULT '0',
`modify_date` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY (`member_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
 To get current time stamp with format '0000-00-00 00:00:00' in PHP:
 $modify_date = date('Y-m-d H:i:s');
To insert the new vaules in table cesei_member_extra :
    $sql = "REPLACE INTO cesei_member_extra VALUES ($member_id,$dept,$edu,  '$modify_date')";                                       
    mysql_query($sql, $db);


Note:  using '$modify_date' instead of  $modify_date as it is a string or an error will be produced.

Saturday, March 16, 2013

Check your Firefox plugins updated



We often find Firefox plugins not updated. For example I often found my Java and Acrobat reader not working properly and need to be updated. To check your Firefox plugins update status:
 https://www.mozilla.org/en-US/plugincheck/
Click update button for individual plugin and restart Firefox.

Friday, March 15, 2013

PHP, input verification



In this PHP example, we allow input as ubc, vch, others. The input is not case sensitive and allow users some typo, such as add . between letters such as u.b.c., also type others as other.
//First remove all . and convert to lower case, using PHP function trim to ignore white spaces.
$site=strtolower(str_replace(".", "",trim($_POST['site'])));
//Create an array containing strings allowed
 $site_allow = array("ubc","vch","others","other");
//Using PHP function in_array to check string $site match any element of the array
  if(!in_array($site,$site_allow)){
     $record['error'][] = 'Invalid site category';
   }

Friday, March 8, 2013

PHP form submission with check box, radio button and dropdown menu



1. For PHP checkbox form submission,  we still can only need one column in MySQL using PHP bitwise function &. (note we can have multi-choice in checkbox). Example code :
<input type="checkbox" name="competency[]" value="4" <?php if(($row['competency']&4) == 4){ echo('checked="checked"'); } ?>  />  Hard skill &nbsp;
<input type="checkbox" name="competency[]" value="2" <?php if(($row['competency']&2) == 2){ echo('checked="checked"'); } ?>  />  Soft skill &nbsp;
<input type="checkbox" name="competency[]" value="1" <?php if(($row['competency']&1) == 1){ echo('checked="checked"'); } ?>  />  Others

In the action side:
      $comp    =0;
     foreach($_POST['competency'] as $pc) {
      $comp = $comp + intval($pc);
     }

and insert $comp in database as column competency, which  will be used in $row['competency']

2. For dropdown menu:
 <select name="competency" id="competency">
     <option value="">- select  -</option>
     <option value="3" <?php if($row['competency'] == 3){ echo('selected="selected"'); } ?>  >  Hard skill </option>
     <option value="2" <?php if($row['competency'] == 2){ echo('selected="selected"'); } ?>  > Soft skill </option>
     <option value="1" <?php if($row['competency'] == 1){ echo('selected="selected"'); } ?>  > Others </option>
     </select>

In the action side:, we can insert $_POST['competency'] as it is a unique  value.


3. For radio button:
    <input type="radio" id="c1" class="input-radio" name="competency" value="3" <?php if($row['competency'] == 3){ echo('checked="checked"'); } ?>  />
   <label for="c1">Yes, with hard skill</label>
  
   <input type="radio" id="c2" class="input-radio" name="competency" value="2" <?php if($row['competency'] == 2){ echo('checked="checked"'); } ?>  />
   <label for="c2">Yes, with soft skill</label>
 
   <input type="radio" id="c3" class="input-radio" name="competency" value="1" <?php if($row['competency'] == 1){ echo('checked="checked"'); } ?>  />
   <label for="c3">No</label> <br />

In the action side:, we can insert $_POST['competency'] as it is a unique  value.

Thursday, March 7, 2013

MySQL: select one table from another table



Suppose MySQL tables edu_courses and edu_extra1_study have a smae primary key: course_id, to select from edu_courses based on the condition in edu_extra1_study, we can use following MySQL statement if requiring order by title:
SELECT * FROM edu_courses   WHERE course_id In (SELECT course_id FROM edu_extra1_study) ORDER BY title;
If  edu_extra1_study selection is based on the variable in url
data_export.php?c1=1&c2=0&c3=0
where c1, c2 and c3 from checkbox, i.e, the value equal to if  the checkbox is checked.
We we defined an arry in PHP:
$q1= Array();
If the checkbox is checked., we can add a condition, such as:
$q1[]='competency=3';
 finally we can use PHP implode to join all the conditions:
implode(' AND ',$q1);
Final code:
<?php
$querystring='SELECT course_id FROM edu_extra1_study  ';
$q1= Array();
if(isset($_GET['c1'])){
 if($_GET['c1']==1) { $q1[]='competency=3';}
 }
 if(isset($_GET['c2'])){
 if($_GET['c2']==1) {$q1[]='competency=2';}
 }
if(isset($_GET['c3'])){
 if($_GET['c3']==1) {$q1[]='cognitive=1';}
 }
if(!empty($q1))$querystring=$querystring.'WHERE '.implode(' AND ',$q1);
if(empty($q1))
{$sql = "SELECT * FROM edu_courses ORDER BY title";}
else
{$sql = "SELECT * FROM edu_courses WHERE course_id in (".$querystring.")ORDER BY title";}

?>




Redirect a link using button



Below is the example to redirect a link using a button.  We  can also pass checkbox value to the link.
code:
<script type="text/javascript">
<!--
function redirectlink(){
    vc1=document.form1.c1.value;
    vc2=document.form1.c2.value;
    vc3=document.form1.c3.value;
   if (document.form1.c1.checked == false) vc1=0;
   if (document.form1.c2.checked == false) vc2=0;
   if (document.form1.c3.checked == false) vc3=0;
    window.location = "http://jiansenlu.blogspot.com/?c1="+ vc1+"&c2="+vc2+"&c3="+vc3;
}
//-->
</script>
<form action="export.php" method="post"  name="form1">
  <button  type='button' id="filter2"  onclick="redirectlink()"> Redirect a link </button>
    <input type="checkbox"  id="c1"  name="c1" value="1"   />Pass c1
   <input  type="checkbox" id="c2" name="c2" value="1"   />Pass c2
   <input type="checkbox"  id="c3"  name="c3" value="1"   />Pass C3
   </form>

Demo:

Pass c1 Pass c2 Pass C3

Tuesday, March 5, 2013

JavaScript: enable or disable radio buttons



Sometimes in HTML form, when users answer yes, they can continue for more selections. If they answer no, the next selection is disabled. In the following example, if you select yes under competency,   you can continue to select hard skill or soft skill. If you select no, the hard skill and soft skill selections are disabled.
Example code:
 <script type="text/javascript">
    function disablecheckbox()
{
document.getElementById('skill').disabled=true;
document.getElementById('skill2').disabled=true;
document.getElementById('skill').checked=false;
document.getElementById('skill2').checked=false;
}
function enablecheckbox()
{
document.getElementById('skill').disabled=false;
document.getElementById('skill2').disabled=false;
}
</script>
Competency<br />
 <input type="radio"  name="c1" onfocus="enablecheckbox();"   />
  Yes
 
   <input type="radio" name="c1"  onfocus="disablecheckbox();"/>
   No<br />
   If yes:
   <input type="radio" id="skill" name="s1"  disabled="disabled"    />
   hard skill
 
   <input type="radio" id="skill2" name="s1"  disabled="disabled" />
   soft skill<br />


Demo: when you click no, hard skill and soft skill selections are disabled.
Competency
Yes No
If yes: hard skill soft skill