Archive for May, 2007

Filed Under (Javascript Code Samples) by Anoop on May-19-2007
Code (javascript)

<html>
<head>
<script type="text/javascript">
function check(browser)
{
document.getElementById("answer").value=browser
}
function showans()
{
document.getElementById("ans").innerText = document.getElementById("answer").value;
}
</script>
</head>

<body>

What's your favorite website:
<form>
<input type="radio" name="browser" onclick="check(this.value)" value="wallpapers.yah.in">wallpapers.yah.in
<input type="radio" name="browser" onclick="check(this.value)" value="sms.yah.in">sms.yah.in
<input type="radio" name="browser" onclick="check(this.value)" value="techjunk.websewak.in">techjunk.websewak.in
<input type="radio" name="browser" onclick="check(this.value)" value="websewak.in">websewak.in
<input type="text" id="answer" size="20">

Your favorite website is: <span id='
ans'></span>

<input type='
button' onclick='showans();' name='Show' Value='Show Answer'>
</form>

</body>

</html>


Filed Under (Javascript Code Samples) by Anoop on May-18-2007
Code (javascript)

<script>
function playfx(sound) {
        var loop = true;
        surl = '<embed src="'+sound+'" loop="'+loop+'" hidden="false" autostart="true" height="0" width="0" type="audio/mpeg">';

        document.getElementById("fxsound").innerHTML = surl;
}
</script>
Example Usage:

<div id='fxsound'></div>

<a href='#' onclick="playfx('ringring.wav')" id='fxsound'>Play Sound</a>

<a href='#' onclick="playfx('')" id='fxsound'>Stop Sound</a>
 

Note: For sounds to work in firefox, you need to install QUICKTIME plugin.



Filed Under (PHP Code Samples) by Srikanta on May-17-2007
Code (php)

<?php
// Function to convert Minutes to Hours : Minutes format
function to_hour_string($MM)
{
        $Hour=floor($MM/60);
        $Min=($MM%60);
        If($Hour>0)
        {
                $str = $Hour."hr";
                if ($Hour > 1)
                        $str .= "s";
                if ($Min > 0)
                        $str .= " ".$Min."min";
                if ($Min > 1)
                        $str .= "s";
        }
        else if ($Min > 0)
        {
                $str = " ".$Min."min";
                if ($Min > 1)
                        $str .= "s";
        }
        else
        {
                $str = "-";
        }
        return $str;
}

//Example
$MM=98; //$MM is Minutes

echo to_hour_string($MM); //displays 1hr 38mins

?>
 


Filed Under (Articles, LAMP) by Anoop on May-17-2007

We have already discussed, how to install apache and php on windows. Now in this post we are going to tell you that how can you install and configure mysql and server to make it work.

Download
Package(win32 binary, non-installer version) : Select mysql-noinstall-4.1.21-win32.zip

Our Configuration

  • %SYSTEMROOT% : Win2000 -> C:\WINNT, WinXP -> C:\Windows
  • Install to : C:\www\mysql (or wherever you want to install, only for advance users)

Setup

  • Unpack as C:\www\mysql-4.1.21
  • Rename directory C:\www\mysql-4.1.21 to C:\www\mysql
  • Copy MySQL configuration file C:\www\mysql\my-medium.ini (or your choice of one of the other included my-*.ini files) to your %SYSTEMROOT% directory
  • Rename file %SYSTEMROOT%\my-medium.ini (or the copied over my-*.ini file) to my.ini
  • Edit %SYSTEMROOT%\my.ini
  1. Under Sections "[client]" and "[mysqld]", edit…
    socket = C:/www/tmp/mysql.sock
  2. Under Section "[mysqld]", insert…
    basedir = C:/www/mysql/
    datadir = C:/www/mysql/data/

MySQL Server Binaries

MySQL ships with a number of server binaries to choose from. For standard/typical use and functionality, the preference is for server binary ‘mysqld-nt’. Server binaries with the ‘-nt’ suffix should only be used under Windows NT/2000/XP/2003.

  • mysql-debug.exe : Compiled with full debugging and automatic memory allocation checking, symbolic links, and InnoDB and BDB transactional tables.
  • mysqld.exe : Support for InnoDB transactional tables.
  • mysqld-nt.exe : Support for named pipes.
  • mysqld-max.exe : Support for symbolic links, and InnoDB and BDB transactional tables.
  • mysqld-max-nt.exe : Support for symbolic links, InnoDB and BDB transactional tables, and named pipes.

Startup

MySQL can be installed as a Service (automatic or manual start-up) or started as a standalone console application. The MySQL server can be configured to listen (and communicate) on all interfaces (0.0.0.0), the loopback (127.0.0.1), or any other address. The MySQL server can also be configured to skip networking (TCP/IP) and/or connect via named-pipes (sockets).

Install the MySQL process as a Service.

[Default] Listen on all interfaces (0.0.0.0)…
C:\www\mysql\bin> mysqld-max-nt

–install
[automatic start (but not this first time)]
Or
–install-manual
[manual start only]

Other options (edit my.ini), section ‘[mysqld]‘, insert…
Listen on loopback only (127.0.0.1)…
bind-address=127.0.0.1
Do not use TCP/IP (IP addresses and ports) for connections, use named-pipes…
bind-address=localhost
skip-networking
enable-named-pipe
[Note option socket=C:/www/tmp/mysql.sock (default is 'socket=MySQL' for mysql and php) under sections '[client]‘ and ‘[mysqld]‘; Make sure the specifed dir exists; Make sure to fill php.ini options mysql[i].default_socket = C:/www/tmp/mysql.sock and mysql[i].default_host = localhost; Use mysql[i]_connect(’localhost:/www/tmp/mysql.sock’, ‘user’, ‘password’)]

Start the MySQL Service…
…> NET START MySQL

Start MySQL as a standalone console application. C:\www\mysql\bin> mysqld-max-nt –standalone –console
[option '--standalone': Dummy option to start as a standalone server; can be omitted and have the same effect]
[option '--console': Write error output on screen (as opposed to error log)]
Other command line arguments… –bind-address=127.0.0.1
[Note that any IP address can be specified]
–skip-networking –enable-named-pipe –socket=mysql.sock
[option '--skip-networking': do not use TCP/IP -- only valid for localhost]
[option '--enable-named-pipe': allows connections to other NT machines without being dependant on a specific network layer (TCP/IP or IPX)]
[option '--socket=...': name of nt-pipe/socket to use for option '--enable-named-pipe']

Cleanup

Create a password for the ‘root’ mysql account…

C:\www\mysql\bin> mysqladmin -u root password set-root-password-here
Delete all insecure users… Access the MySQL prompt… C:\www\mysql\bin> mysql -u root -p

Display all databases, accounts, and access controls to individual databases…

mysql> SHOW DATABASES;
mysql> SELECT User, Host, Password FROM mysql.user;
mysql> SELECT Host, Db, User, Select_priv FROM mysql.db;

Remove all initial accounts except ‘root@localhost’; remove ‘test’ database and privileges set…

mysql> DELETE FROM mysql.user WHERE User=”;
[Remove anonymous users]

mysql> DELETE FROM mysql.user WHERE User=’root’ AND Host != ‘localhost’;
[Remove remote root]

mysql> DROP DATABASE test;
[Remove test database]

mysql> DELETE FROM mysql.db WHERE Db = ‘test’ OR Db = ‘test\\_%’;
[Remove privileges on test database]

mysql> FLUSH PRIVILEGES;
Exit. mysql> quit;

Note: Cleanup only if you are a advance user. Any extra modification can result in the mysql startup failer. Because mysql also consists of additional information with itself. Cleanup processor is not a neccassory task.

Running MySQL

All commands are run from the command line and directory C:\www\mysql\bin (unless the mentioned dir is under the PATH)

Enter the command-line interface…
> mysql -u root -p

Stop the MySQL Service (one of two ways)…
> NET STOP MySQL
> mysqladmin -u root -p shutdown

Uninstall the MySQL Service…
> mysqld-max-nt –remove

Shutdown the standalone console MySQL application (one of two ways)…
> mysqladmin -u root -p shutdown [Note that this is done from another cmd.exe window]
Ctrl-C under the cmd.exe window it was started from

Help

All commands are run from the command line and directory C:\www\mysql\bin (unless the mentioned dir is under the PATH)
Display the MySQL command-line interface (shell) options…
> mysql –help

Display mysql-max-nt options…
> mysqld-max-nt –help

Display MySQL version information…
> mysqladmin -V

See what values a running MySQL server is using…
> mysqladmin -u <user> -p<password> variables

Display information…
> mysqladmin -u <user> -p<password> version status proc

Update password for MySQL user ‘root’ (from the MySQL shell)…
mysql> UPDATE mysql.user SET Password=PASSWORD(’root-password’) WHERE User=’root’;
mysql> FLUSH PRIVILEGES;

Source : http://www.devside.net



Filed Under (Javascript Code Samples) by Anoop on May-16-2007
Code (javascript)

<html>
<head>
<script type="text/javascript">
function changeLink()
{
        document.getElementById('myLink').innerHTML="WebSewak";
        document.getElementById('myLink').href="http://www.websewak.com";
        document.getElementById('myLink').target="_blank";
}
</script>
</head>
<body>

<a id="myLink" href="http://www.yah.in">Yah.in Collection</a>
<input type="button" onclick="changeLink()" value="Change link">

</body>
</html>
 


Filed Under (PHP Code Samples) by AJ on May-15-2007
Code (php)

<?php
function check_email($email) //Function to check email validity
{
// First, we check that there's one @ symbol, and that the lengths are right
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
{
// Email invalid because wrong number of
//characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg(
"^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i]))
{
        return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
{ // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
                {
                        return false; // Not enough parts to domain
                }
        for ($i = 0; $i < sizeof($domain_array); $i++)
                {
                if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$",
 $domain_array[$i]))
                        {
                        return false;
                        }
                }
}
return true;
}
// Example Usage

$good_email = "sd@example.com";
$bad_email = "al.c";

$a = check_email($good_email);// returns true
$b = check_email($bad_email);// returns false
?>
 


Filed Under (PHP Code Samples) by Anoop on May-13-2007

I hope this regular expression helps somebody…

Code (php)

<?php

//Function to check an email address

function check_email($Email)
{
        // Let's check the good e-mail address
        if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $Email))
        {
                return 1;
        }
        else
        {
                return 0;
        }
}

// Example Usage

$good_email = "sd@example.com";
$bad_email = "al.c";

echo check_email($good_email);// displays 1
echo check_email($bad_email);// displays 0

?>
 

If somebody finds a bug in the above function, please don’t comment, otherwise my boss will deduct my salary ;) Just kidding. Please post your feedback in comments on the function.



Filed Under (Articles, LAMP) by Anoop on May-12-2007

Step 1 - Download the Latest stable snapshot version.

Although this is a ‘Stable’ snapshot - it is still a snapshot and not a recommended release for production purposes. I am providing this tutorial because all stable production release versions from 5.1.x and below do not work with the latest stable release of Apache 2.2.2.

Go to http://snaps.php.net/ and download the latest stable Win32 Package. This tutorial assumes you will want to install the latest version 5 snapshot build which at the time of writing is 5.2. For this tutorial I used the snapshot built on 29th June 2006. You should use the latest snapshot dated the same day as you download it.

Click on the latest version ‘ php5.2 (zip) ‘ to download  the file named ‘ php5.2-win32-2006xxxxxx.zip ‘ - 8.4MB, save it to your hard drive in a suitable temporary location. (In case of re-installs being necessary I have a permanent location called ‘Master Programs’ where I download to and extract from there). [xxxxxx being the date of the latest version]

Step 2 - Install PHP

Following on from our previous related tutorial on Apache, extract/copy all files and sub-folders to ‘C:\Apache2\php5′ - if you extract elsewhere e.g - ‘D:\PHP5\’ , please remember to substitute this file path in any future references.

Note: PHP5 Installation is slightly different to PHP4 installations. You can find install.txt in PHP4 directory which will help you to install PHP 4 very easilly. The php5 install.txt has this to say :-

Upgrading from a previous PHP version: Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you’ll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.

Locate C:\Apache2\php5\phi.ini-recommended and make a copy of this file, rename it to php.ini and make sure it is saved in the same folder.

 

Step 3 - Configure PHP 5.2-dev for Apache 2.2.2

Edit your newly copied php.ini in notepad and scroll down to the ‘Paths and Directories’ section.

  • Replace doc_root=
    with doc_root= “c:\apache2\apache2\htdocs” ——–> Change file path accordingly if needed to whatever your Apache Servers document_root is. (In httpd.conf)

Save and Close php.ini.

Step 4 - Configure Apache 2.2.2 for PHP 5.2-dev

————–
Edit your Apache config file ‘httpd.conf’

Locate all the LoadModule entries near the top of the file and just below them add :-

# For PHP 5 do something like this:
LoadModule php5_module “d:/PHP5/php5apache2_2.dll”
# configure the path to php.ini
PHPIniDir “D:/PHP5″
AddType application/x-httpd-php .php

Ensure the path to the php5apache2_2.dll and to the PHP directory reflect your setup, not neccessarily what I have above. Note that the dll we want here is called php5apache2_2.dll and not the php5apache2.dll that earlier versions of PHP came with.

The rest of ‘httpd.conf’ should be ok if the earlier tut was followed, so Save and Close this file then ‘Stop and Start’ or ‘Restart’ the Apache Server service.

Ok, so lets get testing!

Step 5 - Testing your Installation.

Open Notepad (or whatever) and paste the following code into it:-

<?php phpinfo(); ?>

and save the file as phpinfo.php Open your browser and go to ‘ http:\\localhost\phpinfo.php ‘ With a bit of luck you should have a screen full of Server related information and variables.

php_52_1.jpg

If not, something has gone wrong with the installation somewhere, It is usually a simple config error or path related problem and nothing serious. Thanks for listening, the next article in this series of Articles is to install and configure mySQL for use with Apache 2.2.2 and PHP 5.2-dev.

Important Note: This tutorial recommends and uses php.ini-recommended as a starting point when learning PHP. It has a lot of ’safe’ features & settings by default. In particular the ’short_open_tags’ setting is off meaning you can not open a PHP tag with just a <? but you must you the full <?php to start off any PHP code segments.



Filed Under (Articles) by Anoop on May-11-2007

Step 1 - Download the latest version of Apache.

Goto http://httpd.apache.org/download.cgi and look for the latest stable release. This is currently 2.2.2 and is the version we will use here. Click the link "apache_2.2.2-win32-x86-no_ssl.msi" and Save to an appropriate part of your hard drive. The hard part is done ;)

Step 2 - Install Apache

Double-click the downloaded MSI to launch the installer. You will be presented with the welcome screen.

apache_222_1.jpg

apache_222_2.JPG

apache_222_3.JPG

apache_222_4.JPG

apache_222_5.JPG

apache_222_6.JPG

apache_222_7.JPG

apache_222_8.JPG

apache_222_10.JPG

Step 3 - Lets Configure our new Server.

These instructions configure the Server for SSI as well as taking the ‘VirtualHosts’ approach. This enables you to then add more web sites as needed just by configuring a new ‘VirtualHost’ for each. PHP config options will be added in the PHP tutorial section . Below instructions assume ‘yoursite.com’ as the site name, change to suit yours!!

Locate and edit ‘httpd.conf’ file (should be in ‘C:\Apache2\Apache2\conf\httpd.conf’)

ServerRoot, ServerName, DocumentRoot etc will all have been pre-set according to what information you provided in the intial installation phase. Check these and it is ok to change them manually if your setup needs or locations change.

Locate this code near the bottom of the file :-

<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Satisfy all
</Directory>

and just below it add a new directory container for your base websites files locations.

<Directory "d:/accounts/*/">
AllowOverride None
AddType text/html .shtml
AddHandler server-parsed .shtml
Options FollowSymLinks +Includes
Order allow,deny
Allow from all
AddOutputFilter INCLUDES;DEFLATE shtml
</Directory>

In the above example, this is needed to configure the directory structure for where our virtual hosts will be placed on the server - and this for security reasons is outside of the directory structure for the web server apache files themselves. Here I have created a directory called ‘accounts’ where all websites will be based beneath.

Find the code section:-

<IfModule dir_module>
DirectoryIndex index.html
</IfModule>

and make it look like this :-


<IfModule dir_module>
DirectoryIndex index.html index.shtml index.php
</IfModule>

Find the section :-

# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>

and uncomment out those last two lines to read :-

# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
</IfModule>

————–

There is now a supplementary section near the bottom of httpd.conf which gives you the option to include extra configuration files into your setup. In our case, the virtualHosts that we want to configure, instead of doing so at the bottom of this httpd.conf file, we instead enable the ‘httpd-vhosts.conf’ file and do our configurations in there.

Still in httpd.conf file , find the section which is headed by :-

# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.

and then find these two lines of code :-

# Virtual hosts
# Include conf/extra/httpd-vhosts.conf

Uncomment out the second line to enable the external vhosts file :-

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Ok, we are done with httpd.conf file but we are not done configuring. We now need to edit /extra/httpd-vhosts.conf and configure our virtual host containers. Save and Close ‘httpd.conf’ file.

Locate and edit ‘httpd-vhosts.conf’ file (should be in ‘..\conf\extra\httpd-vhosts.conf’)
NameVirtualHost *:80 should already be enabled - that is uncommented, if not enable it.

then create a new VirtualHost container for your first site (yoursite.com).

<VirtualHost *>
ServerName yoursite.com
ServerAdmin webmaster@yoursite.com
DocumentRoot "D:/accounts/yoursite"
ServerAlias www.yoursite.com yoursite.dnsalias.com
ErrorLog logs/yoursite.com-error_log
CustomLog logs/yoursite.com-access)log combined
AddHandler server-parsed .shtml
Options FollowSymLinks +Includes
AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
</VirtualHost>

The first VirtualHost container block - or the only container block - is also the fallback default virtualhost should any other requests not be found. More information on configuring VirtualHost containers is at http://httpd.apache.org/docs/2.2/vhosts/

Ok so that about it, Save the file, then ‘Stop’ and ‘Start’ the Server again.

Check that the default site is now our new VirtualHost by going to http://localhost in your browser. Of course you will already have some files including an index page in d:/accounts/yoursite/ or you’ll get a 404 error.

Step 4 - Extra Configurations.
With the new configuration of version 2.2.x of Apache, you may find that some things have changed, some things disabled etc. This extra config section hopefully will show you the way. This page will be updated as I find things.

Enable the local Manual again!
So Apache have decided to disable the local copy of the manual - it is still there, but using up 9MB of disk space and not being utilised. I have been asked - and I asked myself to begin with - why is it that typing in http://localhost/manual gives me an error page instead of the manual I love to refer to ?

Edit your httpd.conf file and locate :-

# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf

Lets enable the manual by removing the comment from the second line.

# Local access to the Apache HTTP Server Manual
Include conf/extra/httpd-manual.conf

Ok, good thats it, restart the Apache Server service and go to http://localhost/manual and you should have your manual showing again!

If you get an Access Denied message, have a look in ../conf/extra/httpd-manual.conf and check that the location specified in the Alias Match and Manual lines points to the location of the manual directory.

Disable external access to the Manual
Ok, so above we have enabled access to the manual again, and even though Apache have commented it as being ‘Local access …’ , it will also be able to be accessed if you have enabled your website to be accessed externally across the internet. So accessing http://localhost/manual is possible, but so is http://yoursite.com/manual .

You may not care about this, but if you do here is how to disable external access to your manual.

Edit your ../conf/extra/httpd-manual.conf file and locate in the Directory configuration :-

Allow from all

Change this to read :-

Allow from localhost

Restart your Server. Now http://locahost/manual will still work, but http://yoursite.com/manual will not. You can enhance this to allow the whole of your local network access, certain external IP addresses etc etc.



Filed Under (Javascript Code Samples) by Anoop on May-11-2007

//Function to Change the action of a form in Javascript

Code (javascript)


<script type="text/javascript">
function changeAction()
{
        document.getElementById("myForm").action = 'http://techjunk.websewak.com';
}
</script>
Example usage:
<form id="myForm" action="http://www.yah.in">
<input type="button" onclick="changeAction()" value="Change value of action attribute">
<input type='submit' value='Submit'>
</form>