Monday, January 31, 2011

Login multi gmail accounts in the same browser


I have two gmail accounts. It is inconvenient to logout one account and login another account to read
emails. The following trick will let you choose other Gmail without login-out from the first one.
Go to 
https://www.google.com/accounts/b/0/MultipleSessions.
Select all choices and click Save to  enable multiple sign-in (linking different Google accounts). Now you can see a drop-down along with your   different  Gmail id from the top-right corner of browser, you can add more accounts by selecting this option from the drop-down menu. Read email from different Gmail accounts via selecting  your email account  from the top right corner.

Sunday, January 30, 2011

Add a weather gadget in your blog


Go to:
http://www.widgetbox.com/widget/the-weather-channel-google
Enter your city and weather setting to get Javascript code and embed in your blog.
The example is in my blog right sidebar.

Saturday, January 29, 2011

MySQL data type and some useful commands


NUMBER TYPES
TINYINT( )-128 to 127 normal
0 to 255 UNSIGNED.
SMALLINT( )-32768 to 32767 normal
0 to 65535 UNSIGNED.
MEDIUMINT( )-8388608 to 8388607 normal
0 to 16777215 UNSIGNED.
INT( )-2147483648 to 2147483647 normal
0 to 4294967295 UNSIGNED.
BIGINT( )-9223372036854775808 to 9223372036854775807 normal
0 to 18446744073709551615 UNSIGNED.
FLOATA small number with a floating decimal point.
DOUBLE( , )A large number with a floating decimal point.
DECIMAL( , )A DOUBLE stored as a string , allowing for a fixed decimal point.
TEXT TYPES
CHAR( )A fixed section from 0 to 255 characters long.
VARCHAR( )A variable section from 0 to 255 characters long.
TINYTEXTA string with a maximum length of 255 characters.
TEXTA string with a maximum length of 65535 characters.
BLOBA string with a maximum length of 65535 characters.
MEDIUMTEXTA string with a maximum length of 16777215 characters.
MEDIUMBLOBA string with a maximum length of 16777215 characters.
LONGTEXTA string with a maximum length of 4294967295 characters.
LONGBLOBA string with a maximum length of 4294967295 characters.



DATE TYPES
DATEYYYY-MM-DD.
DATETIMEYYYY-MM-DD HH:MM:SS.
TIMESTAMPYYYYMMDDHHMMSS.
TIMEHH:MM:SS.

MISC TYPES
ENUM ( )Short for ENUMERATION which means that each column may have one of a specified possible values.
SETSimilar to ENUM except each column may have more than one of the specified possible values.

Counting Rows

SELECT COUNT(*) FROM pet;
SELECT owner, COUNT(*) FROM pet GROUP BY owner;
SELECT COUNT(score) AS n,
    -> SUM(score) AS sum,
    -> MIN(score) AS minimum,
    -> MAX(score) AS maximum,
    -> AVG(score) AS mean,
    -> STD(score) AS 'std. dev.'
    -> FROM testscore;

PHP, create a simple dynamic edit content without using MySQL


Put your dynamic web content in a file such as page1.txt and make sure  it can be written.
In this case, I put:
<h1><center>Welcome to My Homepage</centeer></h1><p /> This is the content
A better and complete version is "fast edit". You can download it for free from:
http://fast-edit.co.uk/ 
Fast Edit is o a Content Management System (CMS) where you can manage files, create and delete pages, change style, make and restore backups, and decide what to display in the automatic menu.
Below is to display the basic idea for editing and how to use login, logout and session.
Code:


<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);
$admin_name = 'admin';
$admin_password = 'admin';
?>
<?php
$page1 = "page1.txt";
$fh = fopen($page1, 'r');
$page1Data = fread($fh, filesize($page1));
fclose($fh);

if(isset($_POST['submit'])){
if( (($_POST['name'])==$admin_name) && (($_POST['pass'])==$admin_password) ) {
                   //  echo "correct combination of username and password";
                     $_SESSION['username'] = $admin_name;
$PHP_SELF=$_SERVER['PHP_SELF'];
                     echo "<h3>Edit Contents of File</h3>
<form action=$PHP_SELF?action=save method= 'post' >
<textarea name='newd' cols='100%' rows='30'> $page1Data </textarea>
<input type='submit' name='editContent' value='save'>
</form><BR />";
 }
               else echo "incorrect combination of username and password";
}
?>
<?php

if(isset($_SESSION['username'])){
// end login session with logout
if($_GET['action']=='logout')
        {
        session_destroy();
        unset($_SESSION['username']);
        }
elseif($_GET['action']=='save'){
$fhw = fopen($page1, 'w') or die("can't open file");
fwrite($fhw, $page1Data);
fclose($fhw);

}
     }
?>
<?php if(!isset($_SESSION['username'])):?>
<form method="post" name="edit" action="<?php echo $_SERVER['PHP_SELF'];?>?action=login">
                Username:<br/><input type="text" name="name" size="15"/><br/>
                Password:<br/><input type="password" name="pass" size="15"/><br/>
<INPUT TYPE="submit" name="submit" VALUE="edit!">
</form>
<?php
echo $page1Data;
?>
<?php else: ?>
<form method="post" name="edit" action="<?php echo $_SERVER['PHP_SELF'];?>?action=logout">
<INPUT TYPE="submit" name="logout" VALUE="logout!">
</form>
<?php endif; ?>

Result: edit will not work due to no php in the blog
Username:


Password:



Welcome to My Homepage

This is the content

Friday, January 28, 2011

PHP, process multiple select from dropdown menu


Create a dropdown menu, select multiple items which are processed by PHP

multi_select.php



<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<select name="test[]" multiple="multiple">
 <option value="one">one</option>

 <option value="two">two</option>
 <option value="three">three</option>
 <option value="four">four</option>

 <option value="five">five</option>
</select>
<input type="submit" value="Send" />
</form>
 
<?php
 $test=$_POST['test'];
 if ($test){
  foreach ($test as $t){echo 'You selected ',$t,'<br />';}
 }
?> 
 
result:

PHP, load EXCEL/CSV file to mysql


Excel files can be saved as csv  format first.
1. First Create a database and table to match columns in csv, for example: first column name, then email and phone
CREATE DATABASE IF NOT EXISTS mydatabase;
USE mydatabase;
DROP TABLE IF EXISTS `user`;
CREATE TABLE user
(
    name VARCHAR(50)      NOT NULL DEFAULT '',
    email VARCHAR(50) NOT NULL DEFAULT '',
    phone int(11),
    PRIMARY KEY (`email`)
)ENGINE=InnoDB  DEFAULT CHARSET=utf8;


PHP script
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'mypasswd';

$database = 'mydatabase';
$table = 'user';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");


    if(isset($_POST['submit']))
    {
         $fname = $_FILES['sel_file']['name'];
         echo 'upload file name: '.$fname.' ';
         $chk_ext = explode(".",$fname);
       
         if(strtolower(end($chk_ext)) == "csv")
         {
       
             $filename = $_FILES['sel_file']['tmp_name'];
             $handle = fopen($filename, "r");
      
             while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
             {
                $sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
                mysql_query($sql) or die(mysql_error());
             }
      
             fclose($handle);
             echo "Successfully Imported";
           
         }
         else
         {
             echo "Invalid File";
         }  
    }
   
    ?>
    <h1>Import CSV file</h1>
    <form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
        Import File : <input type='file' name='sel_file' size='20'>
        <input type='submit' name='submit' value='submit'>
    </form>


Thursday, January 27, 2011

PHP/MySQL paging - showing your query result in multiple pages


To show the result of a query in several pages first you need to know how many rows you have and how many rows per page you want to show. By splitting the result in multiple pages you can save download time plus you don't have much scrolling to do.
Code: 


<?php
 ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'mypasswd';

$database = 'jiansen_db';
$table = 'user_table';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// sending query
$query = mysql_query("SELECT COUNT(val) AS numrows FROM {$table}");

$result  = mysql_query($query) or die('Error, query failed');
$row     =mysql_fetch_assoc($result);
$numrows = $row['numrows'];
$num_pages = 0;
  $page = 0;
  $results_per_page = 10;
     $num_pages = max(ceil($numrows/$results_per_page), 1);
    $page = intval($_GET['page']);
   if (!$page) {
     $page = 1;
    }  
$offset = ($page-1)*$results_per_page;
// print the link to access each page
$self = $_SERVER['PHP_SELF'];
 echo '<table border="1"><tr>';
    for ($i=1; $i<=$num_pages;$i++){
    if(!($i%10))  echo '</tr><tr>';
        echo "<td>";
          if  ($i != $page)
                    echo ' " <a href=\"$self?page=$page\">$page</a> "';
         else
                    echo "$page";
         echo "</td>";
 }
echo "</tr></table>";

$query = " SELECT val FROM {$table} " .
         " LIMIT $offset, $results_per_page";
$result = mysql_query($query) or die('Error, query failed');

// print output, depend on in which page
while($row = mysql_fetch_assoc($result))
{
   echo $row['val'] . '<br>';
}
?>


Saturday, January 22, 2011

Check the result of your HTML code

Type your HTML code, including Javascript but no PHP in the box and Click Show button to get results









Javascript Video tutorial


Click video to see Video, click tiny up arrow in control bar to return to menu.


References:
  1. http://programming.top54u.com/Samples/Sitemap/Default.aspx
  2. http://www.dynamicdrive.com/ 
  3. http://mootools.net/

Friday, January 21, 2011

Share files between Windows 7 and Windows XP


I have a Windows 7 and a Windows XP in my office local network. I setup to share files between these two computers.
Tips:
1) These two computers should have same work group name. I set it as JIANSEN-HOME.
2) The network setting in Windows 7 should be set as Work Network.
(Home network is used to set home group between two Windows 7)  
3) If you can see the remote computer, but can not see the share files in  it,  this may be
solved by set Firewall off.
Setting for Windows 7
1. Control Panel->->System
Advance System setting
Workgroup: WORKGROUP, change to the same work group name in Windows XP.
----------------------------------
2.Control Panel ->Network and Sharing Center
under view your active network, change it to work network.
3) in Home or work under Network and Sharing center
Turn on network discovery
Turn on file and printer sharing
Turn on sharing so anyone with network
caan read and write in public folders
turn off password protection
click my computer: network
----------------------------------------------------------------
Setting Windows XP.
1)Control Panel->->System
Advance System setting, check work group the same as in Windows 7.
2) Click My Computer, click setup home or small  network, following step by step,
set the group the same as in Windows 7.
3) Create a fold such as jiansen-share
right click mouse
select sharing and security
click sharing
Restart Windows 7 and XP to finish setup.

I also have a virtual box Windows server 2003 in my Windows XP.  The folder  C:\VMShare in Windows server 2003 shares with folder \\vboxsrv\VMShare in Windows XP. I  share this with my Windows 7.
So these 3 Windows share files each other.
Reference:

http://www.howtogeek.com/howto/windows-7/share-files-and-printers-between-windows-7-and-xp/

Wednesday, January 19, 2011

Some note about PHP functions


1) Error message: "Function ereg() is deprecated"
Add @ sign before ereg to solve the bug.
Example:
if ($depth >= $min_depth && ereg($mask, $file))
Now add @ sign before ereg($mask, $file)
if ($depth >= $min_depth && @ereg($mask, $file))
to solve eereg() deprecated problem.

2) htmlspecialchars
The translations performed are:

  • &' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'  

3)continue
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.


4) The explode() function breaks a string into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Result:
Array
(
[0] => Hello
[1] => world.
[2] => It's
[3] => a
[4] => beautiful
[5] => day.
)
5) PHP query string:
http://someurl.com/page.php?a=1&b=2&c=3
Then echo $_SERVER['QUERY_STRING'] will display: a=1&b=2&c=3, such data is no use to us, we need to parse it, or get it thru global array $_GET, in our case we could write:
echo $_GET['a'];
echo $_GET['b'];
echo $_GET['c'];
which would output:
1
2
3
 
6)  PHP variable names are case sensitive, but the names of functions are 
case insensitive.
 
7)  unlinkDeletes a file
 

Description

bool unlink ( string $filename [, resource $context ] )
Deletes filename. Similar to the Unix C unlink() function. A E_WARNING level error will be generated on failure. 

Example #1 Basic unlink() usage
<?php
$fh 
fopen('test.html''a'); 

fwrite($fh'<h1>Hello world!</h1>'); 
fclose($fh);
unlink('test.html'); 

?>
8) stdClass is php's generic empty class
Example:
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
9. Download as Word Document:
 header("Content-Type: application/ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("content-disposition: attachment;filename=test.doc");

print 
"Text Here"


10. Download as pdf:

<?php
 // We'll be outputting a PDF

 header('Content-type: application/pdf');
// It will be called downloaded.pdf 

header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf 

readfile('original.pdf'); 
?>
11.  $_SERVER['PHP_SELF'] 
in a script at the address http://example.com/test.php/foo.php would be /test.php/foo.php

12 .foreach
$employeeAges;
$employeeAges["Tom"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Lida"] = "30";
$employeeAges["Rachel"] = "46";

foreach( $employeeAges as $key => $value){
 echo "Name: $key, Age: $value <br />";
}

Result:
Name: Tom, Age: 28
Name: Jack, Age: 16
Name: Lida, Age: 35
Name: Rachel, Age: 46

13. MySQL, update:
SELECT * FROM cesei_help c;
update cesei_help set type="eP-ER" where type="lms";
(commit; rollback;)

14. Using colon instead of Curly Brackets
You can also use colon instead of curly brackets, this is done like below.
if($RandomNumber == '1'):
  echo 'The number was 1';
elseif($RandomNumber == '2'):
  echo 'The number was 2';
elseif($RandomNumber == '3'):
  echo 'The number was 3';
else:
  echo 'The number was 4';
endif; 
 
 
15.  What the "@" mean in php
The @ surpresses warning and error messages.

For example, if you run the command is_file("myfile.txt") nad myfile.txt does not exist, you get a warning message. If you run @is_file("myfile.txt") you wont get this warning message.

16. The "i" after the pattern delimiter indicates a case-insensitive search
Example:

<?php// The "i" after the pattern delimiter indicates a case-insensitive search
 if (preg_match("/php/i""PHP is the web scripting language of choice.")) {
    echo 
"A match was found.";
} else {
    echo 
"A match was not found.";
}
?>
17. Getting the domain name out of a URL
<?php 
// get host name from URL,@ ignore warningg; i,  case insensitive
 preg_match('@^(?:http://)?([^/]+)@i',
    
"http://www.php.net/index.html"$matches); 

$host $matches[1];
echo "host is $host \n"; //result: www.php.net
// get last two segments of host name

 preg_match('/[^.]+\.[^.]+$/'$host$matches);
echo 
"domain name is: {$matches[0]}\n";?>
The above example will output:
domain name is: php.net
18. pathinfo() 
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>

The above example will output:

/www/htdocs/inc
lib.inc.php
php
lib.inc


19. isset()
<?php
$a = ' ';
$b = NULL;

isset($a); // => TRUE
isset($b); // => FALSE
?>
20 echo
$foo "foobar";
echo 
"foo is $foo"// foo is foobar

// You can also use arrays
$baz = array("value" => "foo");

echo 
"this is {$baz['value']} !"// this is foo !

// Using single quotes will print the variable name, not the value
 

echo 'foo is $foo'// foo is $foo

// If you are not using any other characters, you can just echo variables
 

echo $foo;           
// foobar
 echo $_SESSION['name']; instead of   echo "$_SESSION['name']";
21 session
session_start(); 
 session_id();
session_name();
$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name'); 


A PHP session exists from the time that a PHP web page is opened until the web browser is closed. It is started by using the session_start method. Once the session has been started then variables can be passed from PHP page to PHP page by using the $_SESSION array.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser. 
To pass session variables from paage to page, you need to put  session_start() in each page.

Tuesday, January 18, 2011

Backup MySQL databases in Windows using task scheduler


1. In Windows 7, Start->Control Panel->Administrative tools->task Scheduler
2. Click basic task
3. Following instructions step by step until Start a program: program/script
4. First of all you will need 7-zip for archiving SQL dumps, you can download it and use for free, from here

Then create text file with extension .bat let say mybackup.bat, and copy paste following code:
(there is no line break for 3 lines before  echo Done...)

@echo offset backupdir="d:\temp"
set mysqldir="c:\WebServers\usr\local\mysql5\"
set mysqldatadir="c:\WebServers\usr\local\mysql5\data"
set dbuser="root"
set dbpass=""
set zip="c:\Program Files\7-Zip\"
set endtime=0

:DODIR
DIR %backupdir%

:GETTIME
for /F "tokens=2-4 delims=/ " %%i in ('date /t') do (
set mm=%%i
set dd=%%j
set yy=%%k
)

for /F "tokens=5-8 delims=:. " %%i in ('echo.^| time ^| find "current" ') do (
set hh=%%i
set ii=%%j
set ss=%%k
)

if "%endtime%"=="1" goto END
set fn=_%dd%-%mm%-%yy%_%hh%-%mm%-%ss%
pushd %mysqldatadir%
for /d %%f in (*) do (
if not exist %backupdir%\%%f\ (
echo Making Directory %%f
mkdir %backupdir%\%%f
) else (
echo Directory %%f Exists
)
echo Backing up database %%f%fn%.sql.zip
%mysqldir%\bin\mysqldump.exe --user=%dbuser% --password=%dbpass% 
--databases %%f --opt --quote-names --allow-keywords --complete-insert 
 | %zip%\7z.exe a -tgzip -si%%f%fn%.sql %backupdir%\%%f\%%f%fn%.sql.zip
echo Done...
)
set endtime=1
goto :GETTIME
:END
popd
EXIT
--------------------------------------------------------------------------
5. Another method is to create cron.php and the script is "php cron.php". 

Saturday, January 15, 2011

online video chat room

Usage:
1) You and your friend can use guest login.
2) Click at the top left webcam picture to activate your
webcam.
3) If your friend used a webcam, you can see a web picture near his login
name, click that you can see him in video.
4) If you are alone, you can switch to room list at the right top to see others chat.

Using smtp.gmail.com to sent mail in php


When you test Apache, PHP and MySQL in localhost, you may find mail function does not work in PHP. Below is my experience using smtp.gmail.com to send email in php in Windows 7.
1) We need Mail.php installed from PEAR.
cd C:\php\PEAR
php go-pear.phar
I downloaded Mail package from http://pear.php.net/package/Mail/download
put it under C:\php\PEAR\Mail-1.2.0
I download  Net_SMTP-1.4.4 from http://pear.php.net/package/Net_SMTP/download/
rename it as Net and put it under: C:\php\PEAR\Mail-1.2.0\Mail\Net
I download Net_Socket from http://pear.php.net/package/Net_Socket/download/
copy  Socket.php to C:\php\PEAR\Mail-1.2.0\Mail\Net
2.) In php.in, add following:
extension=php_openssl.dll
include_path = ".;c:\php\includes;c:\php\PEAR\pear;c:\php\PEAR\Mail-1.2.0\Mail"
3) mytest_mail.php (replace to your gmail account and password)
----------------------------------------------------------------
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
 //require_once "Mail.php";
 require_once "c:/php/pear/Mail-1.2.0/Mail.php";
 $from = "Sender <mygmailaccount@gmail.com>";
 $to = "Recipient <mygmailaccount@gmail.com>";
 $subject = "Hi!";
 $body = "Hi,\n\nHow are you?";

 $host = "ssl://smtp.gmail.com";
 $port = "465";
 $username = "mygmailaccount@gmail.com";
 $password = "mygmailpassword";

 $headers = array ('From' => $from,
   'To' => $to,
   'Subject' => $subject);
 $smtp = Mail::factory('smtp',
   array ('host' => $host,
     'port' => $port,
     'auth' => true,
     'username' => $username,
     'password' => $password));

 $mail = $smtp->send($to, $headers, $body);

 if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
  } else {
   echo("<p>Message successfully sent!</p>");
  }
 ?>
 
4) Done! You will receive an email in gmail account when you run mytest_mail.php in localhost.
--------------------------------------------------------------------------------------------------------------------------
Another method is to use PHPMailer. The code is as follows:

<?phprequire("class.phpmailer.php"); 


$mailer = new PHPMailer();$mailer->IsSMTP();


 $mailer->Host = 'ssl://smtp.gmail.com:465'; 


$mailer->SMTPAuth = TRUE;


 $mailer->Username = 'myname@gmail.com';  


 // Change this to your gmail adress


 $mailer->Password = 'mypassword';  // Change this to your gmail password 


$mailer->From = 'myname@gmail.com';  // This HAVE TO be your gmail adress 


$mailer->FromName = 'MyName'; // This is the from name in the email, you can put anything you like here


 $mailer->Body = 'This is the main body of the email';


 $mailer->Subject = 'This is the subject of the email';


 $mailer->AddAddress('myname@gmail.com');  


 // This is where you put the email adress of the person you want to mail 


if(!$mailer->Send())
{
   echo "Message was not sent<br/ >";
   echo "Mailer Error: " . $mailer->ErrorInfo;
}
else
{
   echo "Message has been sent";
}?>


Thursday, January 13, 2011

Using recaptcha in PHP in localhost


Reference:
http://code.google.com/apis/recaptcha/docs/display.html
reCAPTCHA Library for PHP - v1.11 
reCAPTCHA quick start
A CAPTCHA is a program that can tell whether its user is a human or a computer. reCAPTCHA is a free CAPTCHA service.
1. go to
https://www.google.com/recaptcha/admin/create?app=php
type localhost (select  is not important here.)
click create key to get  public key and private key.
2. Download reCAPTCHA library, I put it under directory recaptcha-php-1.11 in my test directory
3. test_rec.html (replace the key after k= to your public key)
<html>
 <script type= "text/javascript">
    var RecaptchaOptions = {
    theme: 'clean'
    };
    </script>
  
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->

      <form method="post" action="verify.php">
    
      <script type="text/javascript"
     src="http://www.google.com/recaptcha/api/challenge?k=6LcfdsASAAAAAIse5zmAapM1Tcx-xedplk6MjvBF">
  </script>
  <noscript>
     <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LcfdsASAAAAAIse5zmAapM1Tcx-xedplk6MjvBF"
         height="300" width="500" frameborder="0"></iframe><br>
     <textarea name="recaptcha_challenge_field" rows="3" cols="40">
     </textarea>
     <input type="hidden" name="recaptcha_response_field"
         value="manual_challenge">
  </noscript>
     
        <input type="submit" />
      </form>

      <!-- more of your HTML content -->
    </body>
  </html>

4. verify.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
  require_once('recaptcha-php-1.11/recaptchalib.php');
    //localhost
  $privatekey = "6LcfdsASAAAAAPSluWN47bx8I_dwfYC_ggMx0gt9 ";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
     echo " test successfully";
    // Your code here to handle a successful verification
  }
  ?>

5. A demo:




Detect Internet Explorer Version using PHP and JavaScript


1. Using PHP:

<?php
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
function ae_detect_ie()
{
   $browser = $_SERVER['HTTP_USER_AGENT'];
  // echo $browser.'<BR>';
 // yank the version from the string
// $browser = substr("$browser", 25, 8);
    $browsertype = substr("$browser", 25, 8);
//    echo $browsertype;
    $browserversion_str = substr("$browser", 30, 3);
    $browserversion_float = floatval($browserversion_str);
//    echo $browserversion_str;
    if (isset($_SERVER['HTTP_USER_AGENT']) &&
    (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)
    && ($browserversion_float < 9.0)
    )
        return true;
    else
        return false;
}
?>

<!-- Using function ae_detect_ie  -->

<?php
 if (ae_detect_ie()) {
   $browser = $_SERVER['HTTP_USER_AGENT'];
    $browsertype = substr("$browser", 25, 8);
    echo '<div style="border: 2px solid #FF0000; width: 100%;  overflow: auto;">';
    echo "<font color='red'> Please note: </font> This site requires Internet Explorer 8.0 or higher. ";
    echo "It seems that your are using $browsertype.";
    echo "  Please update your Internet Explorer to 8.0 or higher. Please follow the links below to upgrade your browser.";
    echo '<BR /> Click <a href="http://www.microsoft.com/canada/windows/internet-explorer/">HERE</a> to upgrade your Internet Explorer. ';
    echo 'You can also use <a href="http://www.mozilla.com/firefox/">Firefox</a> instead.';
    echo "</div>";
//    exit(0);
    }
?>
2. Using Javascript:

<html>
<body>

<script type="text/javascript">

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
function checkVersion()
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    if ( ver >= 8.0 )
      msg = "You're using a recent copy of Internet Explorer."
    else
      msg = "You should upgrade your copy of Internet Explorer.";
  }
  alert( msg );
}
checkVersion();
</script>

</body>
</html>

Wednesday, January 12, 2011

Setup and run webinar using Vyew for free


Using webinar, you can share your desktop and presentations while you may speak over a standard telephone line, while pointing out information being presented onscreen, and the audience can respond over their own telephones, speaker phones allowing the greatest comfort and convenience. There are web conferencing technologies on the market that have incorporated the use of VoIP audio technology, to allow for a completely web-based communication.
Adobe Acrobat Connect is great one, but is not for free to use.
Using Vyew,  you can connect 10 people for free version.
 1) Sign up Vyew here  using your email.
2) login Vyew here.
3) You can create a new room, invite your friends (through email) and share your local computer, files, screenshot, online drawing  and much more. The new interface of Vyew has webcam and talk function built in.

Saturday, January 8, 2011

Remote access your PC for free -LogmeIn

You can sign in logmein for free to access your local PC or Mac for Free. The website is
https://secure.logmein.com/
Comparing to VPN, logmein is faster and more functions.
Another website is gotomypc, 30 days free trial, the website is as follows:
http://www.gotomypc.com

You can
  • Work on your office computer from home.
  • Travel anywhere and work remotely.

Another topic not related to this, but for e-learning software management using  SC|ORM 2004.
Sharable Content Object Reference Model (SCORM) is a collection of standards and specifications for web-based e-learning. It defines communications between client side content and a host system called the run-time environment, which is commonly supported by a learning management system. SCORM also defines how content may be packaged into a transferable ZIP file called "Package Interchange Format".

SCORM 2004 is the current version,

Create a new user and give him access a database in mysql


//
create database UserDB;
//under mysql, use the following to create User1 with password User1Pass in localhost
CREATE USER 'User1'@'localhost' IDENTIFIED BY 'User1Pass';
//Giving User1 to access database UserDB with permission of
//SELECT,INSERT,UPDATE,DELETE,CREATE,INDEX
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,INDEX ON UserDB.* TO 'User1'@'localhost'
;
test under command prompt:
mysql -h localhost -u User1 -p
under mysql:
show databases;

Debug php code


1) Add the following at the top of your code:
ini_set('display_errors', 1);
error_reporting(E_ALL);
2) you can also check phpinfo
<?php
phpinfo();
?>
3) check php.ini
Some important setting:
extension module location
extension_dir = "C:\php\ext"
upload_tmp_dir, session_save_path and upload_max_filesize setting
extension=php_gd2.dll
for mysql
extension=php_mysql.dll
extension=php_xmlrpc.dll
4) check httpd.conf:
#PHP
LoadModule php5_module "C:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
AddType application/x-httpd-php .php-source .phps
PHPIniDir "C:/php" 

Friday, January 7, 2011

XAMPP and old APACHE


Before I install XAMPP in my Windows XP, I already install Apache server 2.2.
When I run XAMPP,  the default homepage in http://localhost will not show the index.html
under C::\xampp\htdocs
It shows the index.html in old Apache2.2
C:\Program Files\Apache Software  Foundation\Apache2.2\htdocs
You can use portcheck in xampp to see which apache is used.

Important files for configuration files in xampp:
Apache Conf File (httpd.conf): C:\xampp\apache\conf\httpd.conf
( if another Apache 2.2 is used, go to Apache 2.2 httpd.conf, if you don't want the wwwroot 

under htdocs, change DocumentRoot in httpd.conf. In my case, I use:
DocumentRoot "C:\test\CESEI"
<Directory "C:\test\CESEI"> )
PHP Conf File (php.ini): C:\xampp\apache\bin\php.ini
MySQL Conf File (my.cnf): C:\xampp\mysql\bin\my.cnf

Thursday, January 6, 2011

Share folder between local machine and virtual box


My local machine is Windows XP and virtual box is Windows server 2003.
I need to map my local share folder to the virtual box.
1) Click virtual box,  in Windows Server 2003 power off, select General, select setting
and share folders, add C:\VMShare
2)Power  on virtual box  (Windows Server 2003)
3)  in Machine menu, click insert ctrl+Atl+Del, input Windows Server 2003 password
4) Right click My Computer, click map network Drive, Drive Z: Folder
\\vboxsrv\VMShare
5) Click My Computer, you can see the z: drive

Reference:
1) http://news.softpedia.com/news/How-to-Fix-Windows-7-Sharing-in-VirtualBox-123021.shtml
2) http://stevesmithblog.com/blog/shared-folders-in-virtualbox-on-windows-7/

Wednesday, January 5, 2011

Flash Media Interactive Server 4



Flash Media Interactive Server 4 can be downloaded from
http://www.adobe.com/products/flashmediaserver/
Flash Media Interactive Server 4 is for medium and large business and social media companies
requiring multi-users experience, while  Flash Media Streaming server 4 for basic streaming and blogger.
For trial version, you can only get Adobe Flash Media Development Server 4 for a limitation of 10 RTMP connection.
Video:  Webcam Basics in ActionScript 3

Tuesday, January 4, 2011

swfobject




Swfobject can be download from HERE.
(Reference website: http://blog.deconcept.com/swfobject/)
Copy swfobject.js to your working directory, embed swf code as follows:


<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
// <![CDATA[
var so = new SWFObject("so_tester.swf", "sotester", "300", "300", "9", "#FF6600");
so.addVariable("flashVarText", "this is passed in via FlashVars for example only"); 
  // ]]>
</script>
My Result:

CDATA in JavaScript in XHTML


Example 1: Script between  <! [CDATA[  and  ]]>  is ignored
-------------------------------------------------------------------
<script type="text/javascript">
<! [CDATA[
alert('Javascript working!');
   ]]>

</script>
-----------------------------------------------------------
Example 2: CDATA is commented out, JavaScript returns to work
----------------------------------------------------------------------
<script type="text/javascript">
 <!--//--><![CDATA[//><!--
alert('Javascript working!');
 //--><!]]>
</script>
----------------------------------------------------------------------------
Example 3:  CDATA is commented out, JavaScript returns to work
-----------------------------------------------------------------------------
<center style="background-color:green"><form NAME="clock_form">
<input TYPE=TEXT NAME="banner" SIZE=50>
</FORM></center>
<script type="text/javascript">
 <!--//--><![CDATA[//><!--
var position=0;
var msg=" Hi, thank you for visiting my blog. Happy New Year! Have a nice day! "
var i = 0;
while (i ++ < 10)
    msg = " "+msg;
function banner() {

  document.clock_form.banner.value=msg.substring(position,position+50);

  if(position++==msg.length) {

      position=0;
  }
  setTimeout("banner()",100);
}
banner();

 //--><!]]>
</script>

---------------------------------------------
Result of example 1: Alert is not shown.

Result of example 3: Javascript is working



Saturday, January 1, 2011

Canadian S&P/TSX Composite Index and world stock index Forecast toward Dec 2011


Happy New Year! The year 2010 is not bad for stock market. Canadian S&P/TSX index increased 14%! How about Canadian S&P/TSX index and world index performance toward Dec 2011?


From forecast-chart.com , it predicts Canadian S&P/TSX composite index will go to 14242 (the prediction will be kept updated) in Dec 2011. Considering today value 13443 (Dec 30,2010), that will be 5.9% increase. Let's keep an eye on this prediction. (My right sidebar of this blog has Globe Investor - Market Blog RSS feed and Stock Market Timing and trend - Podcasts, updated daily)

It also predicts Dow Jones Industrial Average (DJIA) will go to 11102 in Dec 2011, considering today value 11577, that will be -4.0% change. ( I do not agree with this prediction, I think Dow will end with positive change.)

It also predicts Hang Seng Stock Index  will go to 26226 in Dec 2011, considering today value 23035, that will be 14% increase.

It also predicts IPC Mexico stock index will go to 46423 in Dec 2011, considering today value 38230, that will be 21% increase.

It also predicts FTSE 100  Stock Index (UK) will go to 5409 in Dec 2011, considering today value 5809,  that will be -6.9% change.( I do not agree with this prediction, I think FTSE will end with positive change)

What do you think about this market prediction? Leave your comments as you like.

Software tester job market and future


Software testers test the computer program to ensure that the software will perform well in all conditions. Software testers need to have knowledge of modern test methodologies, good analytical skills, problem solving skills, computer languages,
database, report writing and quality assurance.


Video: Software testing job market research:


Video:what is software testing job?


Video: Software Testing vs. Software Quality Assurance


Video:Software Testing Tutorial: Writing Bug Reports