Thursday, December 31, 2015

Problem Installing phpBB 3.1 Forum on IIS7 Machine


Anyone having this problem? I tried to install this latest phpBB free web forum into my Windows 7 IIS7 PC but I get this error page:



I then download the earlier version which is 3.0 by clicking on a small button on upper right corner:



After running 3.0 version in the localhost, it works fine:



Anyone having this problem on IIS7 machine before? Maybe switching back to older version is the only solution to this?

Read More »

Simple Captcha Verification Using Javascript and PHP with GD Lib


This is a simple version that uses minimal amount of codes. However, this practice is not suitable for websites that require stringent security protection.

The PHP codes make use of the GD library to generate a PNG image file that will be read by the HTML code. The PHP will randomly generate two characters and two numbers with first digit as character followed by a number, then a character and a number. Of course, you can change it to something more complicated like making it a mathematical problem to be solved by the visitor. The PNG image will be accompanied by a browser cookie with the answer to the captcha. The cookie will then be compared with the input by the user to see if they match. You can also send the answer back to the server to be verified in order to make it more secure. However, it is not the scope of this example as I try to make it as simple as possible so that it is easy to understand.

Here are the PHP codes:

<?php

// I name this file captcha.php
error_reporting(0); // this is important to turn off all the warnings if any

session_start();

$angle = rand(-10,10);
$fontSize = 20;

$captchaText = chr(97 + rand(0, 25)).rand(0,9).chr(97 + rand(0, 25)).rand(0,9);


$img = imagecreatetruecolor(120, 50);
$bgColor = imagecolorallocate($img, rand(50,150), rand(50,150), rand(50,150)); //background color - random dark coolor
$fgColor = imagecolorallocate($img, rand(200,255), rand(200,255), rand(200,255)); //foreground color - random light color
imagefill($img, 0, 0, $bgColor);

imagettftext($img, $fontSize, $angle, 25, 35, $fgColor, "./LiberationSerif-Bold.ttf", $captchaText);

setcookie("randomCharacterCookieName", $captchaText, time()+3600, '/'); // will expire in one hour

header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);

?>


Make sure your PHP has the GD library support before you proceed.

The tricky part is the one highlighted in red. You need to upload a font to your home directory to make this PHP script to work. Why don't we use the server font? Most of the time, the shared server won't have any TrueType font in it or the GD doesn't have the authority to run it. It is still better to upload your own font and you have more choice for the font as well. I chose the Liberation font as it is royalty free. You can change to your own font if you prefer.

And now comes the Javascript and HTML:

<html>

<script>

function checkCaptcha() {
 var ans = document.getElementById('answer').value;
 var tmp = document.cookie;
 var chunk = tmp.split('=');
 if (chunk[chunk.length-1] == ans) {
  alert("yes!");
  // proceed with your post verification codes such submitting the form etc.
 }
 else {
 alert("no!");
 }
}

</script>

<body>
<img src="captcha.php">
<br>
Type what you see above here:
<br>
<input type="text" id=answer size=4 maxlength=4> <a href="javascript:checkCaptcha()">Check</a>

</body>

</html>


After running the HTML, I captured this response from Chrome after a right answer is entered:



I captured this response from Chrome after entering a wrong answer purposely:



There are still many things you can improve from these codes. For example, you can still include capital letter or even some special characters to the captcha. You can also scramble the answer in the cookie and descramble it during verification with the answer embedded in the cookie.

Well, here is the Captcha tutorial! Finally!

Read More »

Tuesday, December 29, 2015

Sending Multiple MySQL Table Data from PHP to Javascript via AJAX


Note: Please run these codes from a web host, either it is a "localhost" or remote host from a web hosting server.

This is an expansion of my earlier post with sending data from only one MySQL table. For multiple table data channeling to browser from MySQL, a query string is used to differentiate the AJAX requirement. You can also create another PHP script to access data from other tables but it seems quite unnecessary as it can be easily achieved by sending different query strings to the AJAX PHP script.

Here we go again:

USE `testDB`;
DROP TABLE IF EXISTS `test`;

CREATE TABLE `test` (
 `a` tinyint(4) DEFAULT NULL,
 `b` tinyint(4) DEFAULT NULL,
 `c` tinyint(4) DEFAULT NULL,
 `d` tinyint(4) DEFAULT NULL,
 `e` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `test2`;

CREATE TABLE `test2` (
 `f` tinyint(4) DEFAULT NULL,
 `g` tinyint(4) DEFAULT NULL,
 `h` tinyint(4) DEFAULT NULL,
 `i` tinyint(4) DEFAULT NULL,
 `j` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into `test`(`a`,`b`,`c`,`d`,`e`) values (1,2,3,4,5),(6,7,8,9,10),(11,12,13,14,15),(16,17,18,19,20);
insert into `test2`(`f`,`g`,`h`,`i`,`j`) values (21,22,23,24,25),(26,27,28,29,30),(31,32,33,34,35),(36,37,38,39,40);


A new table 'test2' is added to the previous table setup (refer to my earlier post to check out the difference).

Here are the PHP codes for AJAX (or act as a JSON data generator):

<?php
 //I name this file ajax.php
 error_reporting(0);
 $db_name = "testDB";
 $db_server_name = "localhost";
 $db_usr_name = "xxxx"; // Please replace xxxx with your MySQL username
 $db_pw = "xxxxxxxx"; // Please replace xxxxxxxx with the password that came with it

 $dblink = mysql_connect($db_server_name, $db_usr_name, $db_pw);

 if (!$dblink) {
  array_push($error, "Failed to Connect to Database");
 }
 mysql_select_db($db_name);

 if ($_GET['tbl'] == '1') {
  $query = mysql_query("SELECT * from test");
 }
 else if ($_GET['tbl'] == '2') {
  $query = mysql_query("SELECT * from test2");
 }

 $all = array();

 $d = 0;
 while ($query_result = mysql_fetch_assoc($query)) {
  if ($_GET['tbl'] == '1') {
   $all[$d] = array("a"=>$query_result['a'],"b"=>$query_result['b'],"c"=>$query_result['c'],"d"=>$query_result['d'],"e"=>$query_result['e']);
  }
  else if ($_GET['tbl'] == '2') {
   $all[$d] = array("f"=>$query_result['f'],"g"=>$query_result['g'],"h"=>$query_result['h'],"i"=>$query_result['i'],"j"=>$query_result['j']);
  }
  $d++;
 }

 $encoded = json_encode($all);
 header('Content-type: application/json');
 exit($encoded);

?>


Finally here are the Javascript codes:

<!DOCTYPE html>
<html>

<script>

var data;

function loadJSON(path) {

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
   if (xhr.status === 200) {
    try {
     data = JSON.parse(xhr.responseText);

     for (var k in data) {

      alert(data[k].a+" "+data[k].b+" "+data[k].c+" "+data[k].d+" "+data[k].e);


    }
    catch(e) {
     alert("Data Error. Please contact the administrator.");
    }
   }
   else {
    console.error(xhr);
   }
  }
 };
 xhr.open("GET", path, true);
 xhr.send();
}

function loadJSON2(path) {

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
   if (xhr.status === 200) {
    try {
     data = JSON.parse(xhr.responseText);

     for (var k in data) {

      alert(data[k].f+" "+data[k].g+" "+data[k].h+" "+data[k].i+" "+data[k].j);


    }
    catch(e) {
     alert("Data Error. Please contact the administrator.");
    }
   }
   else {
    console.error(xhr);
   }
  }
 };
 xhr.open("GET", path, true);
 xhr.send();
}

loadJSON('ajax.php?tbl=1'); // This result will be the same as in the earlier post
loadJSON2('ajax.php?tbl=2'); // tell ajax.php that $_GET['tbl'] = 2;

</script>

The data from MySQL will prompt out as alerts, row by row.

</html>


Please note that the DOCTYPE declaration is important for IE browsers as it puts it into standards mode for AJAX to work.

You can also combine loadJSON with loadJSON2 by adding one more parameter to the function. Anyway, to make explanation less confusing, I added another JSON loading function to it.

After running the codes, you may get four alerts with the first time being '1 2 3 4 5' followed by '6 7 8 9 10' and so forth as in the earlier post. Then you may get the new alerts from the second table. Here is a screen shot of the first prompt from the second table running in Chrome:



Caveat: The data from the second table may prompt up before the first table. If you really want to make sure the first table come first, you will need to use the timer to delay the loadJASON2 function a bit.

Thanks for viewing!
Read More »

Large HTML Input Text and Space Suitable for Mobile Device Web Browsing


With the popularity of tablets taking the center stage ever since the launch of the first iPad, web pages were being swayed towards simplicity and user-friendliness. The smartphone revolution then followed suit and mobile web browsing had then become a norm until today. As the screens of tablets and smartphones are a lot smaller than deskstops, web pages are being made simpler with the texts bigger to suit the smaller screens.

The obvious change to the web page is the login page. The login input text and space are now bigger. Here is an example of the HTML and CSS codes I use to follow this trend:

<html>

<table height=100% width=100% align=center valign=middle><tr><td>
<table width=520 height=160 align=center valign=middle style="border: solid #cccccc 1px; background-color: #ddeeff">

<tr><td width=20>&nbsp;</td><td align=right><font face=arial size=3 color=#888888>Login ID</td><td width=20><br></td><td><input type=text name=lg style="height: 40px; padding: 10px 0px 10px 8px;font-size:16px" maxlength=40 size=40></td></tr>

<tr><td width=20>&nbsp;</td><td align=right><font face=arial size=3 color=#888888>Password</td><td width=20><br></td><td><input type=password name=pw style="height: 40px; padding: 10px 0px 10px 8px;font-size:16px" maxlength=40 size=40></td></tr>

<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td><input type="submit" value="Log On Now!"></td></tr>

</table>
</td></tr>
</table>

</html>


The key to this effect is hightlighted in green. The style in CSS is important to make this work. The "height: 40px;" CSS is important to get this to work on IE browsers.

Here is the screenshot after running the HTML in Chrome:



Enjoy!
Read More »

Friday, December 25, 2015

Sending MySQL Data from PHP to Javascript via AJAX


This is done through AJAX. It should be well supported by most browsers including IE. Everything is quite straight forward. First you need to set up a dummy MySQL database to test out the following javascripts. Here is the SQL to set the database up:

USE `testDB`;
DROP TABLE IF EXISTS `test`;

CREATE TABLE `test` (
 `a` tinyint(4) DEFAULT NULL,
 `b` tinyint(4) DEFAULT NULL,
 `c` tinyint(4) DEFAULT NULL,
 `d` tinyint(4) DEFAULT NULL,
 `e` tinyint(4) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into `test`(`a`,`b`,`c`,`d`,`e`) values (1,2,3,4,5),(6,7,8,9,10),(11,12,13,14,15),(16,17,18,19,20);



The above SQL uses a database called 'testDB' with a table named 'test'. The 'test' table came with 5 columns namely 'a', 'b', 'c', 'd' and 'e'. Four rows of data are inserted with number incremented by one starting from 1. The first row contains 1, 2, 3, 4 and 5. The second row starts from 6 until 10 and so forth.

Here are the PHP codes for AJAX (or act as a JSON data generator):

<?php
 //I name this file ajax.php
 error_reporting(0);
 $db_name = "testDB";
 $db_server_name = "localhost";
 $db_usr_name = "xxxx"; // Please replace xxxx with your MySQL username
 $db_pw = "xxxxxxxx"; // Please replace xxxxxxxx with the password that came with it

 $dblink = mysql_connect($db_server_name, $db_usr_name, $db_pw);

 if (!$dblink) {
  array_push($error, "Failed to Connect to Database");
 }
 mysql_select_db($db_name);

 $query = mysql_query("SELECT * from test");

 $all = array();

 $d = 0;
 while ($query_result = mysql_fetch_assoc($query)) {
  $all[$d] = array("a"=>$query_result['a'],"b"=>$query_result['b'],"c"=>$query_result['c'],"d"=>$query_result['d'],"e"=>$query_result['e']);
  $d++;
 }

 $encoded = json_encode($all);
 header('Content-type: application/json');
 exit($encoded);

?>


Finally here are the Javascript codes:

<!DOCTYPE html>
<html>

<script>

var data;
var saveArr1 = new Array();
var saveArr2 = new Array();

function loadJSON(path) {

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
   if (xhr.status === 200) {
    try {
     data = JSON.parse(xhr.responseText);

     for (var k in data) {

      alert(data[k].a+" "+data[k].b+" "+data[k].c+" "+data[k].d+" "+data[k].e);

      // saveArr1.push(k); // if you want to save the array key to an array called saveArr1
      // saveArr2.push(data[k].b); // if you want to save the array data column 'b' to an array called saveArr2

     }
     // alert(data.length); // if you want to check the total length

    }
    catch(e) {
     alert("Data Error. Please contact the administrator.");
    }
   }
   else {
    console.error(xhr);
   }
  }
 };
 xhr.open("GET", path, true);
 xhr.send();
}

loadJSON('ajax.php?set=1'); // '?set=1' is optional and your PHP codes will receive this parameter as $_GET['set'] in PHP

</script>

The data from MySQL will prompt out as alerts, row by row.

</html>


Please note that the DOCTYPE declaration is important for IE browsers as it puts it into standards mode for AJAX to work.

After running the codes, you will get four alerts with the first time being '1 2 3 4 5' followed by '6 7 8 9 10' and so forth. Here is a screen shot of the first prompt running in Chrome:



Please let me know if you encounter any problem with these codes. I will be happy to answer any questions that you may have. Enjoy!
Read More »

Monday, December 21, 2015

Casting a Reflection Image Using Pure Javascript


This is mainly for fun or educational purposes only. This is inspired by a carousel javascript plugin with reflection at the bottom of each image which looks like they are standing on a solid marble. Since it is an awesome idea, I tried to do some coding if it is able to be done by just pure Javascript. Yes, they are done and the codes are presented as follows:

<html>
<body>


<a href="javascript:renderReflection()">Render Reflection</a>
<br><br>

<script>

var height,width;
var tmpDiv,tmpDiv2,i,j,k,l,m,n;
var img = new Image();
var file = 'img/phone_icon2.png';
img.src = file;
img.onload = function() {
 height = this.height;
 width = this.width;
}

tmpDiv = document.createElement("span");
tmpDiv.innerHTML = '<img id=img0 src="'+file+'">';
tmpDiv.style.position = 'absolute';
tmpDiv.style.left = '300px';
tmpDiv.style.top = '150px';
tmpDiv.id = "imgSpan";
document.body.appendChild(tmpDiv);


function renderReflection() {

 k=0, l=-0.25, m=50, n=1; // n=speed of fade, // m=percentage of fade, // l=reflection direction

 for (i=1; i<=height; i++) {
 tmpDiv = document.createElement("span");
 tmpDiv.id = "line"+i;
 tmpDiv.style.height = '1px';
 tmpDiv.style.width = width+'px';
 tmpDiv.style.position = 'absolute';
 tmpDiv.style.overflow = 'hidden';

 j = i*n+(height*((100-m)/100));
 if (j>height) { j=height; }

 tmpDiv.style.MozOpacity = ((height-j+1)/height*10)/10;
 tmpDiv.style.opacity = ((height-j+1)/height*10)/10;

 tmpDiv2 = document.createElement("span");
 tmpDiv2.innerHTML = '<img id=img'+i+' src="'+file+'">';
 tmpDiv2.style.position = 'absolute';
 tmpDiv2.style.marginTop = -1*(height-i-1)+'px';
 tmpDiv2.style.filter = 'alpha(opacity=' + Math.round((height-j+1)/height*100) + ')';

 k+=l;

 tmpDiv.style.left = document.getElementById('imgSpan').offsetLeft + k + 'px';
 tmpDiv.style.top = height + document.getElementById('imgSpan').offsetTop + i + 'px';
 tmpDiv.appendChild(tmpDiv2);
 document.body.appendChild(tmpDiv);

 }
}

</script>

</body>
</html>


You can adjust the style of the reflection by changing the value for l, m or n.

l is the control of the direction for the reflection. A negative value will move the reflection to the left and a postive value will move it to the right. A zero value will cast the reflection straight down.

m is the percentage of the reflection to be rendered. A value of 50 will only allow a maximum 50% of the reflection to be shown. The reflection image will look like being cut into half.

n is the fading speed of the reflection image. A value of 2 will double up the fading speed which result in only half of the reflection image being rendered. A value of 3 will triple up the fading speed which result in only a third of the reflection image being rendered.

The following is the screen capture of the trial runs.

The result of k=0, l=-0.25, m=50, n=1:





The result of k=0, l=0, m=100, n=1.25:





The result of k=0, l=1, m=85, n=2:





You can change the file name and path to something else by modifying var file = 'img/phone_icon2.png';! Enjoy!

P.S.: You need to click on the Render Reflection link to run the reflection rendering function in case you are not aware of.

Read More »