PHP is holiday class

Test out is it a holiday for any given date.

This class currently support United States and Canada’s holidays.

Here is
United States holidays information.
Canadian Holidays information.

This PHP class supports different provinces have its own provincial holidays. For example, December 26th is statutory holiday for Ontario and New Brunswick in Canada.

Usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
include_once("IsHoliday.php");
 
$h = new Holiday('US');
if($h->is_holiday('2010-07-04')) 
        echo "yes, 2010-07-04 is holiday in US <br>";
else	
        echo "no <br>";
 
 
//Using Canadian province code for specific province
$h = new Holiday('Canada','ON');
if($h->is_holiday('2010-12-26')) 
        echo "yes, 2010-12-26 is holiday in Canada <br>";
else	
        echo "no <br>";
?>

Download source code here

  • Share/Save/Bookmark

cp file always getting overwrite prompt?

wondering why always getting overwrite prompt when use “cp” command with “-f” option

try this,

1. login as root

1
vi /root/.bashrc

2. comment out this line

1
#alias cp='cp -i'

3. logout and login again

  • Share/Save/Bookmark

Mysql fix crashed tables

Sometimes, system halt or power off will make your MySQL database crashed and you without knowing it unless you try to access those bad tables.

Run this Linux command to automatically find crashed tables and fix them.

1
mysqlcheck --auto-repair -A -u <username> -p<password>
  • Share/Save/Bookmark

Make a copy of mysql table

One SQL to make a copy of existing MySQL table ( table structure and records )

1
CREATE TABLE clone_table SELECT * FROM original_table WHERE 1
  • Share/Save/Bookmark

Change Firefox user agent to mobile devices’

Often you need view your mobile web development on mobile devices. Wouldn’t it be better to have Firefox, web developer, firebug and etc to help you?
You can change your desktop Firefox user agent string to make a mobile web site thinks you are view it from a mobile device.
Here’s how to do it.

  • Type about:config in Firefox address bar. And read the scary warning and proceed
  • Right click on the settings and select New -> String.
  • Enter the preference name: general.useragent.override, enter string value: BlackBerry9000/4.6.0.266 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/120

Then you’ve done.

In above example, “BlackBerry9000/4.6.0.266 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/120″ is Blackberry Bold user agent.

Common user agents
iPhone user agent:
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3
Windows mobile 6 user agent:
Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile M.N)

In case you want to get full desktop power back, just select the settings you just added, and select “Reset”

  • Share/Save/Bookmark

Rsync server and client – backup your server files

rsync can synchronizes files and directories from one server to another. It’s perfectly for backup or create a mirror site purpose.

This tutorial shows you step by step to create a rsync server and client server.

First of all, you must have rsync installed. For fedora, rsync should be included by default. If you don’t have it, run

1
yum install rsync

Setup rsync server

Create rsync configuration file:

1
2
3
4
5
6
7
cd /etc
mkdir rsyncd
cd rsyncd
touch rsyncd.conf
touch rsyncd.motd
touch rsyncd.user
chmod 600 rsyncd.user

edit rsyncd.user file:
vi /etc/rsyncd.user

1
my_rsync_user_1:user_1_password

edit rsyncd.conf file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
pid file=/var/run/rsyncd.pid
port=873
uid=root
gid=root
use chroot=yes
read only=yes
 
# limit access to LANS
hosts allow=192.168.2.0/255.255.255.0   #default, listen to lan server
host deny=*
 
max connections=5
motd file=/etc/rsyncd/rsyncd.motd
 
log format=%t%a%m%f%b
syslog facility=local3
timeout=300
 
[profile_1]          #profile name
path = /path/to/backup/directory
ignore errors
read only = false
list = false
hosts allow = 66.66.66.66   #listen to client server which use public ip
hosts deny = 0.0.0.0/32
auth users = my_rsync_user_1
secrets file = /etc/rsyncd/rsyncd.user
 
#[profile_1]          #another profile name
#path = /path/to/backup/directory/2
#ignore errors
#read only = false
#list = false
#hosts allow = 88.88.88.88   #listen to client server which use public ip
#hosts deny = 0.0.0.0/32
#auth users = my_rsync_user_2
#secrets file = /etc/rsyncd/rsyncd.user

Next, create init start up script
vi /etc/init.d/rsyncd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/bin/sh
#
# Startup script for rsyncd daemon
#
# chkconfig: 35 90 10
# description: Server data for sync to other server
# processname rsync
 
# Source function library
. /etc/rc.d/init.d/functions
 
prog=rsync
conf=/etc/rsyncd/rsyncd.conf
 
case "$1" in
    start)
        echo -n "Starting rsync daemon: "
        daemon /usr/bin/$prog --daemon --config=$conf
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && touch /var/lock/subsys/$prog
        ;;
    stop)
        echo -n "Shutting down $prog: "
        killproc -d 60 $prog
        RETVAL=$?
        echo
        [ $RETVAL = 0 ] && rm -f /var/lock/subsys/$prog
        ;;
    status)
        status $prog
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
esac
 
exit 0

make /etc/init.d/rsyncd executable, and register this service

3
4
5
chmod +x /etc/init.d/rsyncd 
/sbin/chkconfig --add rsyncd
/sbin/service rsyncd start

Setup rsync client

first, of course you must have rsync installed on client server

make rsync password file

1
2
3
4
5
cd /etc
mkdir rsync
cd rsync
touch rsync.pwd
chmod 600 rsync.pwd

vi /etc/rsync/rsync.pwd

1
user_1_password

execute this command to start synchronize file to server

1
rsync -vrtLogp --progress /path/to/directory/to/be/backup/* my_rsync_user_1@[SERVER_IP]::profile_1 --password-file=/etc/rsync/rsync.pwd

where [SERVER_IP] is rsync server IP

  • Share/Save/Bookmark

Ajax form upload local image file without refresh

The code example below performs following tasks:

  • Upload multiple image files without refresh page.
  • Control maximum number of image files to be uploaded.
  • Instantly review uploaded images.

See it in action here

Download source code

Basic idea:

You have a Form #1 with input element with type “file” to let user to select what images to be uploaded. Also, you need a hidden Form #2 and hidden iframe to do the upload action implicitly. When user select a file, the value of input element needed in Form #2. However, for security reason, browsers are not allow us to manipulate the value of input element, therefore directly copy value of input element to another is not the way to achieve our goal. But, how about copy the whole input element to Form #2? Here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
 
<script  type="text/javascript">
var frameId = 'frame_ID';         //hidden frame id
var jFrame = null;                //hidden frame object
var formId = 'form_ID';           //hidden form id
var jForm = null;                 //hidden form object
var fileMax = 3;                  //maximum number of file to be uploaded
var fileCount = 0;                //file counter
var uploadUrl = "save.php";       //where to handle uploaded image
 
 
$(document).ready(function(){                     
 
jForm = createForm(formId);            //create hidden form
jFrame = createUploadIframe(frameId);  //create hidden iframe
 
//append hidden form to hidden iframe
jForm.appendTo('body');         
jForm.attr('target',frameId);          //make form target to iframe
 
//bind onchange function to input element
$("#inp").bind('change',startUpload); 
 
function startUpload(){
   if(jForm!=null){               
      jForm.remove();                        //re-create hidden form
      jForm = createForm(formId);
      jForm.appendTo('body');
      jForm.attr('target',frameId);
   }
 
   var newElement = $(this).clone(true);   //clone input element object
   newElement.bind('change',startUpload);  //bind onchange function. detect iframe changes
   newElement.insertAfter($(this));        //insert clone object to current input element object
   $(this).appendTo(jForm);                   
 
   jForm.submit();                         //let's upload the file
 
   jFrame.unbind('load');                  
   jFrame.load(function(){        //bind onload function to hidden iframe
 
      //get response message from hidden iframe
      var myFrame = document.getElementById($(this).attr('name'));   
      var response = $(myFrame.contentWindow.document.body).text();
 
      /*
      * you may handle upload status from reponse message.
      * in this example, upload succeeded if message contains ".gif" , otherwise, alert reponse message
      */
 
      if(response.indexOf('.gif')!=-1){ //upload successfully
 
         //show thumbnails, add text box with file name
         addUpload(Math.floor(Math.random()*100),response);   
         fileCount++;
         if(fileCount >= fileMax){   //reach maximum upload file, disable input element
            $("#inp").attr('disabled','disable');
         }
      }else{  //error
         alert(response);
      }
   });
}
 
 
});
 
function createUploadIframe(id){
   //set top and left to make form invisible
   return $('<iframe width="300" height="200" name="' + id + '" id="' + id + '"></iframe>')
         .css({position: 'absolute',top: '270px',left: '450px',border:'1px solid #f00'})
         .appendTo('body');
}
 
function createForm(formId) {
      return $('<form method="post" action="'+uploadUrl+'" name="' + formId + '" id="' + formId + 
            '" enctype="multipart/form-data" style="position:absolute;border:1px solid #f00;'+
            'width:300px;height:100px;left:450px;top:150px;padding:5px">' +
            '<strong>You should hide red blocks</strong><br><br></form>');
}
 
function addUpload(id,img){
   var div = $(document.createElement('div')).attr('id',id);
 
   //add uploaded image
   div.html("<img src='"+img+"'><br />");
 
   //add text box
   var fileName = img.substring(img.lastIndexOf("/")+1);
   var txtbx = $(document.createElement('input')).attr('name','img[]').attr('type','text').val(fileName);
   /* you may want to change textbox to a hidden field in production */
   //var txtbx = $(document.createElement('input')).attr('name','img[]').attr('type','hidden').val(fileName);
   txtbx.appendTo(div);
 
 
   //add remove thumbnail link
   var rem = $(document.createElement('a'))
                               .attr('alt',id)
                               .attr('href','javascript:;')
                               .text("Remove").click(removeUpload);      
   rem.appendTo(div);
 
   //add to the page
   div.appendTo("#uploaded_thumb");
}
 
function removeUpload(e){
   var removeId = $(e.target).attr('alt');
   $('#'+removeId).remove();
   if(fileCount>0) fileCount--;
   $("#inp").removeAttr('disabled');
}
</script>
 
</head>
<body>
  <form>   
   <div id='uploaded_thumb'></div>
 
   <div style='padding-top:20px'>
   upload a small GIF <input type='file' name='image' id='inp'>
   </div>
  </form>
</body>
</html>
  • Share/Save/Bookmark

Plesk common shell commands

Reload vhost.conf for single domain

1
/usr/local/psa/admin/sbin/websrvmng --reconfigure-vhost --vhost-name=

Update AWStats for only 1 domain in Plesk

1
/usr/local/psa/admin/sbin/statistics --calculate-one --domain-name=you-domain.com
  • Share/Save/Bookmark

Subversion client for Windows command line output unreadable characters

If you use subversion client windows command line

1
svn help

on a Windows system with current language for non-Unicode programs set to a different language such as Chinese Simplified.
You probably will see a screen with strange characters – garbage output in command prompt window.
It’s very easy to fix this by set an environment variable for your system

1
Set LANG=C
  • Share/Save/Bookmark

Backup newly modified files

My server backups over 20GB files everyday. It takes hours to tar those huge amount of files. I think this kind of stupid task is harmful to hard driver. One more stupid issue is that over 99% of files are not modified since last backup. So, here is the command to let me backup newly modified files only.

tar -zcvf /save/to/file.tar /filePath/* –newer-mtime ‘1 days ago’

You may want to change “1 days ago” to 2 days, or 5 days.

By the way, it’s better to do full backup monthly or bi-monthly. :)

  • Share/Save/Bookmark