2009/12/01

php soap wget curl

php.ini has the following pertinent settings:

default_socket_timeout = 120
max_execution_time = 60
memory_limit = 20M

In soap client, connection_timeout is equivalent to default_socket_timeout.

<?php

$soapClient = new SoapClient('http://www.example.com/path/to.wsdl',
array('connection_timeout' => 120));

?>

Looks like soapclient use similar technique as file_get_contents() does
to get wsdl file. But unlike wget, file_get_contents generates distinct
packet for each line of HTTP request. Server doesn't reply on these
small chunks.

To let PHP behave like wget:

Define the following function:

function curl_file_get_contents($URL)
{
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
curl_close($c);

if ($contents) return $contents;
else return FALSE;
}

And replace all file_get_contents entries with curl_file_get_contents.

2009/11/05

two select

Two selects:

SELECT cart_name as tag, count(cart_name) as frequency
From
  (SELECT distinct cart_name , account_id
   FROM `account_cart`
   where cart_name REGEXP '^[a-z]+'
) as tb1
Group by cart_name



2009/11/03

empty matches 0 in sql????

page_id = '', the following sql still work.

SELECT SQL_CACHE a.unique_id, b.banner_id, a.page_id, a.grp, a.page_pos,
a.order_seq, b.banner_type, b.image_name, b.link, b.target, b.params, ''
AS sku_list
FROM page_banners_link a, page_banners b
WHERE a.page_id = ''
AND site_id = '0'
AND a.banner_id = b.banner_id
ORDER BY a.page_pos, a.page_id, a.order_seq
LIMIT 0 , 30

2009/11/02

how to purge master logs

> on master:    mysql -p

> 

> mysql >  show master status;

> 

> 

> on slave:   mysql -p

> 

> mysql > show slave status;

> 

> 

> If both master and slave are processing the same replication log file

> (meaning that replication is running correctly),  then you can safely

> run the following commend on master:

> 

> 

> mysql > purge master logs to "current-replication-log-filename";

 

2009/10/26

window.location

function onSelectChangeSite(){
   var dropdown = document.getElementById("snssite");
   var index = dropdown.selectedIndex;
   var ddVal = dropdown.options[index].value;

   var current = window.location;
   var re1 = /\?custm/;
   var re2 = /\?/;

   if (re1.test(current))
      window.location = "?custm=" + ddVal;
   else if (re2.test(current))
      window.location = current + "&custm=" + ddVal;
   else
      window.location = "?custm=" + ddVal;

}

2009/10/25

perl note part2

1.      @line= <STDIN>

Chomp(@line)

print @line;

CTR+D in linux CTR+Z in window to end of standard input

2.      A lot of default

Sub list_from_a_to_b{

            If ($a>$b){

            $a;

            }

            Else{

            $b;

            }

}

$a, $b are global variables. No return needed

Or use

Sub list_from_a_to_b{

            ($a,$b) = @_

Or use

$a = $_[0];

$b = $_[1];

 

2009/10/23

perl note part1

Perl does not have Boolean type true/false

Chomp chops new line, but chop chops the last char

Below does not work in php ($sum UNDEF), but works in perl (unless warning/strict turn on)

$n=1;

while($n<10){

$sum += $n++;

}

print $sum;

qw shortcut

qw /fred barney betty Wilma dino/ == (“fred”, “barney” …)

@array = 6..9

Push/pop operators do things to the end of an array, but shift/unshift do things to the begin of an array

for (1..9){ print;} == for (1..9) {print $_;}

sort/reverse functions does not change the array itself, but return a sorted/reversed array

2009/10/20

more xml encode

function xml_encode($str) {
   $str = preg_replace("/".chr(153)."/","(tm)",$str); // trademark
   $str = preg_replace("/".chr(174)."\s/","(r) ",$str); // registered tratemark
   $str = preg_replace("/".chr(174)."\W?/","(r)",$str); // registered tratemark
   $str = preg_replace("/".chr(169)."/","",$str); // copyright
   $str = preg_replace("/".chr(194)."/","",$str); // Capital A, circumflex accent

   $str = preg_replace("/&reg;/","(r)",$str);
   $str = preg_replace("/&quot;/","\"",$str);
   $str = preg_replace("/&#153;/","(tm)",$str);
   return $str;
}


How to use implode in IN sql

Here is a example,

$review_id = array();
$sql = "update pr_approved set emailed = 'Y' where merchant_review_id ('".implode("','",$review_id)."')";

2009/10/14

Different between Minfier and Packer

Found this article at
http://markmail.org/message/2v5mteddw3busgbp#query:packed%20vs.%20minified+page:1+mid:nfd2zt6ub3yltzgs+state:results


SWFObject uses YUI Compression (which is basically/similar-to minified, but with additional 'intelligence' to achieve smaller but still safe compression).

----------------------------------- Though it's a little off topic, for the benefit of the readership, here's a brief discussion of the differences:

YUI Compression (and minification) essentially strips out all whitespace/comments, shortens (safely) all internal variables, and removes unnecessary code syntactics.  The benefit is really good compression, but extremely quick "initialization" (in other words, having it ready on your page), because the code is directly executable in the page.

One other downside of YUI Compressor is that it strips out (or fails on, sometimes) IE-conditional-compilation comments, which SWFObject uses.  So, SWFObject's authors actually remove the IE-conditional-compilation block, YUI compress the code, then add the block back in, adjusting it to the right minified variable names, etc.  Kind of a pain, but this produces the best result (see below).

Packing (like Dean Edwards' Packer, among others) uses a slightly different concept -- it actually applies an advanced set of 'compression' packing algorithm to the code, rearranging code blocks/commands, using techniques to take advantage of looping, etc... and then it tacks onto the end a small runtime that 'unpacks' the payload and passes it through an eval() statement to evaluate it for execution on the page. Some 'packers' even actually use real compression, like zip or gzip, with javascript implementations of the decompressors.  The benefit is much higher compression, but the tradeoff is that the "decompression"/evaluation actually has some performance cost, sometimes a few seconds worth, for it to initialize and be ready for the page to use.

One additional factor is that a server can apply gzip/deflate compression on the stream of text being sent to the browser, so a 'minified' script can be 'compressed' with gzip (usually on the fly) for transfer over-the-line, and the browser takes care of natively uncompressing it.  This type of compression has much less performance cost.  The main downside is that the server (and browser, which most modern ones do) must support gzip compression.

Generally speaking, for most scripts, YUI compression (minification) combined with server/browser-gzip transfer turns out to be the best combination -- it generally gets the best, most efficient "compression", because it achieves close to (or better) compression to 'packers', but without most of the runtime performance cost.

In fact, this URL will take any script and run it through several of the most common minifiers/packers/compressors, and their various configuration tuning options, and return a list of all combinations with size and runtime speed costs. It sorts the list so you can see the best choice for your script.  http://compressorrater.thruhere.net/

Hope that helps.  :)

--Kyle

remove file named single quote

When I use VIM, sometimes I careless enter the wrong key and saved the file using single quote as file name.
[root@myserver page_render]# ls
'                    optin.php
You see the ' as  file name above. How to delete it?

I tried:
[root@myserver page_render]# rm '
>
It failed. I knew it can be deleted thru FTP client like WinSCP, etc. But just figure out how to delete it from command line. It is easy, but you have to escape it, like following,

[root@myserver page_render]# rm \'
rm: remove regular file `\''? y


2009/10/02

how to use smarty plugin with multiple parameters

For example, you have a plugin function like,

function smarty_modifier_trans_seo($string,$grp="",$sbgrp="",$ln="") {}

As you see, this plugin function accepts up to 4 parameters. By default the last 3 are empty.

Usage:

1. one parameter:
{$onefoo|trans_seo}

2. two parameters:
{$firstfoo|trans_seo:$secondfoo}

3. there parameters:
{$firstfoo|trans_seo:$secondfoo:$thirdfoo}

Four parameters, I bet you know how to do it.

2009/09/22

java NullPointerException Error

One of my cronjob running error last night, the error message is the following, java.lang.NullPointerException    at UpdtCreatePrdIndex.translateStr(UpdtCreatePrdIndex.java:648)  Trace into the code, the error is in,  private static String translateStr(String trans_str) {        trans_str = trans_str.replaceAll("&quot;","\"");        trans_str = trans_str.replaceAll("&reg;","");        trans_str = trans_str.replaceAll("&#153;","");        return trans_str }  Finally, find out the reason that we updated database table yesterday, and some field has value NULL. When those fields called this method, they failed.  NULL.replaceAll("a", "b") will cause  java.lang.NullPointerException 

2009/09/14

how to ignore dollar sign in the replacement

Found the solution @ http://theserverpages.com/php/manual/en/function.preg-replace.php

If you're setting your replacement values elsewhere and your replacement value can contain a dollar sign followed by an integer eg:

$replacement = 'Dad's $7 shoes'

You'll find that preg_replace() treats this (quite rightly) as callback syntax.

So, you might want to do this:

$replacement = preg_replace("!" . '\x24' . "!" , '\\\$' , $replacement);

To your replacement string first; Putting in an escaped backslash '\\' followed by an escaped dollar sign '\$' where every instance appears.

2009/09/10

install perl module in redhat

Just found it is so easy to install a perl module using cpan in redhat.

login as root, enter the following command:

cpan


This will open a cpan shell and display the following message:

cpan shell -- CPAN exploration and modules installation (v1.7602)
ReadLine support enabled


cpan>

The you can install a perl mdule if you know the name,

cpan> install WordPress::Post

The name of perl module is case sensitive, so if you are not sure the name, you can try

cpan> i /wordpress/

It would tell you any module whose name has 'wordpress' in there.

2009/09/08

MySQL Error: Lost connection to MySQL server at 'reading authorization packet', system error: 0

I receive this error today:
MySQL Error: Lost connection to MySQL server at 'reading authorization packet', system error: 0

I found this note below from mysql website: http://dev.mysql.com/doc/refman/5.0/en/error-lost-connection.html
So looks like myserver has the second issue.

There are three likely causes for this error message.

Usually it indicates network connectivity trouble and you should check the condition of your network if this error occurs frequently. If the error message includes “during query,” this is probably the case you are experiencing.

Sometimes the “during query” form happens when millions of rows are being sent as part of one or more queries. If you know that this is happening, you should try increasing net_read_timeout from its default of 30 seconds to 60 seconds or longer, sufficient for the data transfer to complete.

More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection. You can determine whether you are experiencing this more uncommon cause by using SHOW GLOBAL STATUS LIKE 'Aborted_connects'. It will increase by one for each initial connection attempt that the server aborts. You may see “reading authorization packet” as part of the error message; if so, that also suggests that this is the solution that you need.

If the cause is none of those just described, you may be experiencing a problem with BLOB values that are larger than max_allowed_packet, which can cause this error with some clients. Sometime you may see “packet too large” as part of the error message, and that confirms that you need to increase max_allowed_packet.

undefined index

$foo = array();

$foo[bar] = 'bad'; //this works but produce undefined index notice.

The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

-- by http://www.nusphere.com/kb/phpmanual/language.types.array.htm

//So always do:
$foo['bar'] = 'good';
//or
$bar = "bar";
$foo[$bar] = 'good';


There is another case may cause undefined index notice.

$bar = 'myindex';
if (!is_array($foo[$bar])){
   // do something;
}


Because $foo[$bar] is not defined yet, it could not be evaluated by in_array. The correct way is that

$bar = 'myindex';
if (isset($foo[$bar]) &&
!is_array($foo[$bar]) ){
   // do something;
}

2009/09/04

two errors when restart apache

I got two errors when trying to restart apache by command:

/etc/init.d/httpd graceful

1.       Cannot load /etc/httpd/modules/mod_proxy_connect.so into server: /etc/httpd/modules/mod_proxy_connect.so: undefined symbol: ap_proxyerror

Solution: LoadModule proxy_module modules/mod_proxy.so (which was turned off)

2.       Invalid command 'ExtendedStatus', perhaps misspelled or defined by a module not included in the server configuration

Solution: LoadModule status_module modules/mod_status.so (which was turned off)

gtalk windows application does not support non-gmail account

You can sign up Google service using your non-gmail email account, but you can only use gtalk widget if you are using non-gmail account.

 

I also found one interesting thing that if I mouse over my friend, who is logging thru widget with her non-gmail account, in my Google Talk window, I see she is actually using 3ux4794qhrxxx@id.talk.google.com

So looks like when you are using widget with non-gmail account, actually google assign you a special/temporary gtalk account.

 

2009/08/28

sort string field in mysql

A clever way to sort a string field.

Q:
It needs to be ORDER BY attribute. So then we get alphabetical order of non-numerical string (column named attribute) and numerical order for 'attribute' combined with numerical and non-numerical characters. For example,

apple
blueberry
orange

AND

1 foot
2 feet
3 feet

A:
ORDER BY CAST(attribute AS UNSIGNED)

2009/08/27

Remove a member from array and ArrayObject

For arrayobject, you can do
foreach ($arrobj as $obj){
do something ...
}
Like array does.

However you cannot use unset to remove a ArrayObject member, for example,
$hits is ArrayObject,

You could not do something like,
foreach ($hits as $hit) {
if(!preg_match("/.*abc$/", $hit->sku)){
unset($hits[$hit]);
}
}

You have to use ArrayObject's method called append to do it, like,

$new_hits = new ArrayObject();
foreach ($hits as $hit) {
if(!preg_match("/.*CR$/", $hit->sku)){
$new_hits->append($hit);
}
}
$hits = $new_hits;

Object to Array in PHP

If less than PHP5, then use this function,

function objectToArray($object)
{
$array=array();
foreach($object as $member=>$data)
{
$array[$member]=$data;
}
return $array;


If PHP5, then You can cast your object to an array by,

$array = (array) $this;

call native php function in smarty

I bet you know we can use php function in the smarty condition clause, like,
{if count($arr)} do something ... {/if}

But if we want to display array size, we cannot use {count($arr)}, but we can use,
{$arr|@count}

So to call native php function, we can use below format:
{$input_parameter|@native_phpfunction}
Note:
  1. $input_parameter is smarty variable
  2. native_php_function, like sizeof, count, round, etc..

2009/08/25

Trim in perl

Perl does not come with trim function, but you can crate one easily:

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($)
{
    my $string = shift;
    $string =~ s/\s+$//;
    return $string;
}

PHP4 CLASS VS PHP5

  1. PHP4 classes don't have scope operators such as private, public or
    protected.
  2. PHP4 constructional function should be the same name with that of the class. __construction won't work.
  3. Class variables in PHP4 classes are declared with the keyword 'var' rather
    than private or public.

REF: kavoir.com

2009/07/16

Amazon S3 upload issue

I got this error when I try to upload file to Amazon using S3.php library.

Amazon S3 Server.RequestTimeTooSkewed(403): The difference between the request time and the current time is too large.

The problem is that the developer box was down in the past few days. It is up now, but the date time is wrong.

Here is a solution:

ntpdate pool.ntp.org

2009/07/07

Call Member function

PHP5 is OO language. For a basic usage, we may not need to understand the concept of OO design in details, so sometimes we may forget how to call a member function defined in a Class. :-(

Got this error this morning:

PHP Fatal error:  Call to undefined function get_tokens()

Haha!

The solution:

$this->get_tokens();

Remember to you must have $this-> to call a member function defined in a Class.

2009/07/01

Permission denied to get property HTMLDivElement.parentNode

pForm is cool, and I just used it to build a form yesterday. But it worked fine yesterday, but this morning, when I when tried to select the date from Date field, I got this error message:

Permission denied to get property HTMLDivElement.parentNode

pForm integrated the calendar.js developed by Dynarch.com, seems this is a bug of firefox . Here is a quick fix. Open calendar.js at line 131 in the code. Add try and catch like below,

Calendar.isRelated = function (el, evt) {
   var related = evt.relatedTarget;try{
   if (!related) {
      var type = evt.type;
      if (type == "mouseover") {
         related = evt.fromElement;
      } else if (type == "mouseout") {
         related = evt.toElement;
      }
   }
   while (related) {
      if (related == el) {
         return true;
      }
      related = related.parentNode;
   }
   return false;
   }catch(e){
      return;
   }
};

2009/06/30

$_SERVER to get current URL

Checked PHP Manual,

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.

If you are using apache, check this page,

SCRIPT_NAME=/sw/lib/w3s/tree/global/u/rse/.www/index.html
SCRIPT_FILENAME=/u/rse/.www/index.html
SCRIPT_URL=/u/rse/
SCRIPT_URI=http://en1.engelschall.com/u/rse/

In my server, I can use below code to get URL without query string (or ‘?q=’).

$url = getenv("SCRIPT_URI");
//or
$url = $_SERVER['SCRIPT_URI'];

2009/06/25

include library files

If you hosted your site somewhere, your probably wanted to know where the root directory path is, in order to include (or require) some library files, which requires a whole path.

If you hosted on linux system, then it is easy to find it out, by

$docRoot = getenv("DOCUMENT_ROOT");
include ($docRoot . "path/to/yourfile");

However, if you hosted on IIS system, then getenv would not work. Here is a workaround:

require_once(dirname(__FILE__) . '/../includes/utils.php');
require_once(dirname(__FILE__) . '/includes/utils.php');
Note: direname(__FILE__)return the current dir name, so you need to tweak it a bit (for example, ‘..’ means jump up a level) to find out a correct library files.

2009/06/24

escape single quote in javascript

Problem:

alias_term = trim(alias_term);
var str = '<a href="javascript:updt_mapping(\'alias\',\''+alias_term+'\');">Update Alias</a>';
Using above code, when the alias_term is something like k’nex, which has single quote, it would broke the javascript, for the javascript statement become updt_mapping(‘alias’, ‘k’net’)

Solution:

escape single quote, but you could not using escape function, alias_term = escape(alias_term), but replace function, alias_term = alias_term.replace(/\'/,"\\'");

2009/06/23

Some notes about yslow

Company’s webstie is slow. The boss wanted to know why and I am trying to find out why.

I think form web developer viewpoint, what you can do is optimize the web component. If your site hosted on a bad server, then you effort on optimizing the web component is minor. Anyway Firefox fox yslow seems to be a great tool helping you do the website optimization.

1. make fewer HTTP requests.

I think most of current sites have a same problem that a page contain too many external javascript scripts. yslow suggests to try combining them into one, however, most of time this is not a solution at all because you just could not combine them.

2. yslow suggest move all javascript at bottom.

If you should every javascritp snippets, which are relied to those javascripts at header, is running after document ready, then you may do this. Otherwise, you may break some of them.

3. Minify javascript and css

I do some of them. Just too lazy to do all of this, because you are going to update those minified files, that is pain. You have to edit the unminified version, test it and then minfied it again (unless you have a good eye to modify on a minified file)

4. Add expires headers and compress components with gzip

This can be done by updating apache setting …

5. Use a content delivery network

I think this is a big reason the site is slow, if you site hosted on a fast and stable content  delivery network, then you site is most likely running faster.

Note: Just found that yslow does not recognized old style JavaScript tags, like

<script language="JavaScript" src="/js/ajax.js"></script>
//yslow uses type to determine it is javascript or not
<script type="text/javascript" src="/js/ajax.js"></script>

2009/06/18

Remove all posts

Sometimes you may want to remove all posts from your Wordpress. You can do this from Wordpress dashboard, but you have to do delete them page by page, and each page has only 20 posts.

If you really wanted to remove all post at a time, here is Perl script to do so.

use WordPress::XMLRPC;
my $o = WordPress::XMLRPC->new({
username => 'admin',
password => 'yourpass',
proxy => '/path/to/your/xmlrpc.php',
});
#print $o->getPost();
my $post = $o->getRecentPosts(500); #500 meant get 500 posts
for $p (@$post) {
 $id =  $p->{'postid'};
 #print "$id\t";
 $o->deletePost($id);
}
PERL WORDPRESS XMLRPC Module can be found at here

2009/05/27

initial array in java

1. static one:

int[] a;           // Declare a to be an array of ints
a = new int[100];  // Allocate an array of 100 ints
//or in a line
int [] a = new int[100];
//string type
String [] b = new String[100];

2. dynamic one:

Note: ‘Java does not offer arrays that can be extended at run time, for primitives or Objects, so it is common to use a Vector for a set of elements that needs to be able to grow.’ from javalobby

Vector v = new Vector();
int count = v.size();
String[] dynArray = new String[count];
v.copyInto(dynArray);

2009/05/08

How to embed youtbe video on the webpage

Here is code:
<object width="336" height="300">
<param name="movie" value="http://www.youtube-nocookie.com/v/VCtIS9vKdWg&hl=en&fs=1&color1=0x006699&color2=0x54abd6&border=1"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube-nocookie.com/v/VCtIS9vKdWg&hl=en&fs=1&color1=0x006699&color2=0x54abd6&border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="336" height="300">
</embed>
</object>
Here is what it looks like:

2009/04/27

How to auto post to Wordpress

  1. Turn on remove_posting at http://yourdomain/wp-admin/options-writing.php
  2. Using below PHP code:
function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$categories=array(1)){
   $categories = implode(",", $categories);
   $XML = "<title>$title</title>".
   "<category>$categories</category>".
   "<body>$body</body>";
   $params = array('','',$username,$password,$XML,1);
   $request = xmlrpc_encode_request('blogger.newPost',$params);
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
   curl_setopt($ch, CURLOPT_URL, $rpcurl);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, 1);
   curl_exec($ch);
   curl_close($ch);
}

2009/04/14

mySQL date function

The SQL to get total order number and total order amount from orders table:

SELECT count(*), sum(order_total) 
FROM orders 
WHERE DAYOFMONTH(last_accessed) = DAYOFMONTH(now()) 
      AND MONTH(last_accessed) = MONTH(now()) 
      AND YEAR(last_accessed) = YEAR(now()) 
      AND record_state = 1

Note:

  1. DAYOFMONTH is synonym of DAY used to get day (ex: 1-31) from a data and time string (ex: 2009-04-14 11:44:02)
  2. Complete mysql date function can be found at here

2009/03/30

Links is forced to open in a new window

All HTML links with target="_blank" usually means open in a new window. Some modern browser can open them in a new tab, which is one of enhancements that make Firefox famous.

But recently, the links of the page are forced to open in a new window other tan a new tab in my Firefox browser, although I have set it to open in a new tab in the Tools->option-tab.

I tried to Goolge an answer, but found nothing. Finally, I found the reason.

Try enter ‘about:config’ on your Firefox browser address bar, you will see a long list, type in ‘link’ in the Filter, you will see, below two parameters,

browser.link.open_newwindow and browser.link.open_newwindow.restriction

The default value of these two parameters are 3 and 2. But they were 1 and 1 on my browser.

browser.link.open.newwindow = 1 means open All HTML links with target="_blank" in a new tab, but it only work when browser.link.open_new.restriction = 2.

2009/03/24

iconv_substr() gives "Unknown error"

If Unknown error(0), then most likely it is this issue, iconv_substr() gives "Unknown error" when string length = 1" and it was fixed in PHP5.2, if you are still using PHP5.1, here is a workaround for this bug,

/*Reproduce code:
---------------*/
$s = 'x';
$s = iconv_substr($s, 0, 1, 'UTF-8');
var_dump($s);
/*Expected result:
----------------*/
string(1) "x"
/*Actual result:
--------------*/
bool(false)
//and Notice: iconv_substr() [function.iconv-substr.html]: Unknown error
//(0) in ...
/*A workaround:
-------------*/
$s = 'x';
$s .=" "; //add one more empty character
$s = iconv_substr($s, 0, 1, 'UTF-8');

But if you got Unknown error(12), which is what I got in lucene search engine. Then it is a issue in this thread, but don’t know the solution yet.

2009/03/20

Some https conf for sercurity

#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
#
ServerSignature Off
#Fri Mar 20 09:19:57 EDT 2009: per OReilly
ServerTokens ProductOnly

#
# Timeout: The number of seconds before receives and sends time out.
#
#Fri Mar 20 09:12:45 EDT 2009: Timeout 180  (reduced  per O'Reilly recommendation for DOS protection)
Timeout 60

Sessioin stuff

Session cookie lifetime in our server is 864000 sec, so it is 10days not 30minutes as we always assume.

When people logon online account,

  • 1. get billing/shipping info in account_billing/account_shipping table.
  • 2. then check if there is billing/shipping info in the billing/shipping table with the same session_id.
  • 3. if yes in step2, then update it with the one got from step1; if not, then insert with one got from step one if found in the step 1

2009/03/19

Trademark, Copyright, and Register symbols

Trademark, copyright, and register symbols in iso-8895-1 character set cannot be displayed correctly in other character set, for example, urf-8, or even iso-8895-15.

Try this function, which should fix this issue.

function tcr_encode($str) {
   $str = preg_replace("/".chr(153)."/",'&trade;',$str); // trademark
   $str = preg_replace("/".chr(174)."/",'&reg;',$str); // registered tratemark
   $str = preg_replace("/".chr(169)."/",'&copy;',$str); // copyright
   return $str;
}
//change trademark, copyright, and register symbols to html entity
$title = tcr_encode($title);

2009/03/17

How to have variable in jquery selector

Seems very simple, but sometimes I just forget it.

var myid = "result";

$("#" + myid).hide(); work

$('"#' + myid + '"').hide(); doesn't work

2009/03/16

Cleaning up/Formatting user input

We use below function to clean up a user input:

function x_site_safe($input,$do_quot=true,$remv_quot=false) {
   $input = preg_replace("/</","",$input);
   $input = preg_replace("/>/","",$input);
   $input = preg_replace("/\(/","",$input);
   $input = preg_replace("/\)/","",$input);
   if ($do_quot)   $input = preg_replace("/\"/","&quot;",$input);
   if ($remv_quot) $input = preg_replace("/\"/","",$input);
   return $input;
}

Usage:
x_site_safe($input) : remove >, <, ( , ), and change " to &quot
x_site_safe($input, false): remove >, <, ( , and )

For example: (combine with stripslashes and trim)

$str = (isset($_GET['v'])) ? stripslashes(trim(x_site_safe($_GET['v'],false))) : "";

A little better practice on web development

Every time working on a new project, I do it on the development box, after getting code done and tested, I load new code to the production. It sounds simple, isn’t it? But sometime it is not that simple, for the environment between production and development is different, so I cannot just simple overwrite the production one when load the new code in, also, sometime I directly changed the code on the production for a small change without updating the code on the development. (not a good practice though, but for the small company’s website, which may a quick way.)

So I think I need some good practices to follow when I start a new project. Here they are,

1. Before change any single file, compare it with the production one. If see any new in the production (usually a very small change), update it back to the development one. Make sure it works on development.

2. Make a copy of the file you are going to work with. Add it into the project’s file list.

3. Work on the files on the development box and test.

4. When code ready, compare each file on the project’s file list, and double check the different between new file and backup file, and make sure any additions also available on the production. 

5. Before loading the new code into production. Make a copy of the code on the production as filename.OLD. Make necessary change on the development code to meet the production’s environment and save as filename.NEW.

6. OK final step, check the order of files need to change, for a big project, the code updated may be done after 9:00pm. Basically it is copy filename.NEW to filename.

In any failures above, just copy the filename.OLD back to filename.

2009/03/15

Error: Permission denied to call method Location.toString

I got this error in both Firebug and Firefox add-on Web Developer . "Error: Permission denied to call method Location.toString", when visiting my own website.

I checked carefully of the webpage, but did not find any problem of my code. Finally, I found the problem was from a Flash Ad. from Google AdSense.

Anyway, I need to keep Ad.

2009/03/13

IE Security Warning

Most of time I am using Firefox, so I just found that the checkout page of my company's website has a problem in IE today. We bought the SSL certificate, so it is start with 'https.' However, when the page loaded in IE, it prompts,

This page contains both secure and nonsecure items. ...

secure

For user, the solution is that changing IE securtiy setting to display mixed content. Internet Options -> Security -> Custom level -> Enable Dispaly mixed content (in the middle of settings box, took me some time to find it :-))

By default, IE prompts when it see a mixed content page, so for developer, solution is to fix it other than telling user how to change the security settings. How? The reason of this warning is that in the page has both 'https" and "http" links, for example, some images links using 'http'. So changing those "http" links to "https" will fix it, at least in my case.

Updated: (3/16/09)

Actually it depends on how you registered the SSL domain, if it is www.yourdomain.com, then no matter you use http or https. if it is secure.yourdomain.com, then you should correct www.youdomain.com to secure.yourdomain.com.

2009/03/09

XML Parsing Error: Junk After Document Element

I got this error, XML Parsing Error: Junk After Document Element. My XMl was like this,

<?xml version="1.0" encoding="iso-8859-1" ?>
<billing_id>1234</billing_id>
<f_name>adam</f_name>

After some searching, I knew why,

A well-formed XML document must have one, and only one, top-level element. Anything after that element's end-tag will be ignored at best, and possibly reported as an error such as the one you're getting here.

So I fixed the problem by adding a top-level element <rsp>

<?xml version="1.0" encoding="iso-8859-1" ?>
<rsp>
  <billing_id>1234</billing_id>
  <f_name>adam</f_name>
</rsp>

2009/03/06

AdSense shows a blank space

I created an AdSense account a few days ago. But when I integrated it into my website, it only showed a blank space where I put the code without any contents. I googled the web and did not find a solution. Looks like not too many people have this problem, in case you get the same problem, here are some possible reason and solutions.

Reason 1: When you create an Ad unit, you choose to show a solid color when AdSense cannot find a match content on the page. And the solid color you picked is the same as the background color on the problem area.  
Solution 1: Most of time this is not a case. If it does, then try to used a different solid color.

Reason 2: You just created/updated an Ad unit, which usually take up to 10 minute to load
Solution 2: Wait 10 minutes to see it works or not

Reason 3: The AdSense code does not correctly paste. You cannot write the code in a single line.
Solution 3:

The is happen to me, see the code below,

//a sinlge line below causes a problem
<script type="text/javascript"><!-- google_ad_client = "pub-xxx"; /* 160x600, created 3/4/09 */ google_ad_slot = "9031182928"; google_ad_width = 160; google_ad_height = 600; //--> </script> 

After changed it like below, it fixed the problem.

<script type="text/javascript"><!-- 
google_ad_client = "pub-xxx";
 /* 160x600, created 3/4/09 */
 google_ad_slot = "9031182928";
 google_ad_width = 160; 
 google_ad_height = 600;
 //--> 
 </script>

2009/03/05

Mark all gmails as read

I use Outlook to revieve emails a lot. Sometimes, especially I'm at work, I also logon my Gmail thru Firefox. I installed the Google toolbar for firefox with Gmail notifier to let me know when a new email coming in.
Here is a problem, using Outlook to recieve emails, the received emails in you account are still shown as unread. So Gmail notifier keep on indicating there are new emails when I restart the firefox, but acutally, they are not really new. So I decided to mark those emails as read, however, it's painful if you have tons of emails unread. 
Google is always my best friend, I found a solution at http://www.woodwardweb.com/technology/marking_all_mai.html   
To mark all mail as read:-
   1. In the search box, type "is:unread"
   2. In the select area press "All"
   3. A link will appear that says "Select all conversations that match this search", press it
   4. From the drop down, select "Mark All as Read".

2009/03/03

Apache built-in funtion, server-status

There is mod_status built into Apache web server to get server status from web browser. With this module you can easily find out how well your server is performing.
You can turn in on in httpd.conf file, like below,
<Location /server-status>
    SetHandler server-status
    AuthType Basic
    AuthName "Admin Area"
    AuthUserFile /var/www/passwd/passwords
    Require user admin
    Order deny,allow
    Deny from all
    Allow from 172.16
    Satisfy any
</Location>
All reports are generated in a html format. You can easily find out following type of information:
   1. Total number of worker serving requests
   2. Total number of of idle worker
   3. Find the status of each worker, the number of requests that worker has performed and the total number of bytes served by the worker
   4. Total number byte count served
   5. Other information such as CPU usage, number of requests per second,current hosts and requests being processed etc.
For example, you may see 1&2 like below,
233 requests currently being processed, 13 idle workers
Here, 233 is simultaneously running requests, which cannot access the maximum number you set up. Depend on how busy your server is, you may make this number bigger. The default number is 256.
Usually, you can set this in your http.conf file, like below,
<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   20
ServerLimit      512
MaxClients       512
MaxRequestsPerChild  4000
</IfModule>

2009/02/26

Solutions of database replication failure

MySQL replication allows you to have an exact copy of a database from a master server on another server (slave), and all updates to the database on the master server are immediately replicated to the database on the slave server so that both databases are in sync. (instrested in how this being set up, check it out here, http://www.howtoforge.com/mysql_database_replication)
My compare have two web servers, and the replication is turning on. We use below php file to check the replication status.  
$link = mysql_connect('localhost', 'root', 'password')
   or die('Could not connect: ' . mysql_error());
mysql_select_db('production') or
    mail('example@email.com', 'www cannot connect', $message);
$query = 'SHOW SLAVE STATUS';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$line = mysql_fetch_array($result, MYSQL_ASSOC);
if ( $line["Slave_SQL_Running"]  != "Yes"  or
     $line["Slave_IO_Running"]  != "Yes" ) {
    $message = $line["Last_Error"];
    mail('example@email.com', 'www replication failure', $message);
}
?>
During the development, we created a database on slave DB, and today we were going to move the code to production, so we created a database on master DB. It used the samed name as the same one on slave DB, but having nothing in there. A few minutes later, we got email telling us the repliation failed.
Here is a solution:
On Slave:
1. In phpMyAdmin export the Database (For example, named A)
2. Drop the Database (A)
3. logon mysql, run command: START SLAVE (It would try to rerun the queries)
On Master:
1. Drop the Database (A);
2. Create a Database using different name (B)
On Slave:
Import the Database using the Export file.

2009/02/24

Fixed postion in IE6

To have something always shown on the same position on a page, we can use css position property and set it to "fixed", however it doesnot work in IE6. There might be some hack to make this happen in IE6, actually I searched along trying to find one, but have not find a good solution yet. Anyway I am not going to spend time on the IE hack, what I going to do is just hidded this funtion in IE6. Complaint? Who care! Why not just leave that old buggy stupid IE6, you have a lot of option, have not you?
So the html code is like this:
<div id="footerud">
<div id="up"></div>
<div id="down"></div>
</div>
The css is that:
#footerud{bottom:10px;display:block !important;position:fixed;left:15px;}
#up{
background:url(../images/arrowtop.png) no-repeat;
cursor:pointer;
height:14px;
margin-bottom:15px;
position:relative;
width:25px;
}
#down{
background:url(../images/arrowbottom.png) no-repeat;
cursor:pointer;
height:60px;
margin-top:15px;
position:relative;
width:25px;
}  
To hidded this on IE6, I added style into html code, like
<div id="footerud" style="display:none;">
 
Will that hidded it from Firefox or IE7? Don't worry, because we have this in the css file,
#footerud{bottom:10px;display:block !important;position:fixed;left:15px;}
The !important generally means the attribute cannot be overwrote, fortunately, IE6 does not recognized it, so it will be hid.
 

2009/02/23

'nodeName' is null or not an object error in IE

Says you have code like below
<div id="place1">ABC</div> ... <div id="place2">EFG</div> Then you try to update those div using jquery's html method, and the html result from ajax will be insert into this div, like
$('#change').html(data); //data is from ajax call Which works fine on Firefox, but fails on IE. The message you will get is that, 'nodeName' is null or not an object The fixes is that clearing the value in that div before assign anything into it, like,
$('#change').html(); //clear div $('#change').html(data); The version of the jQuery used to product this error is 1.2.6

jquery ajax with xml

1. How to generate XML output By default, echo in php sending the text to the browser. So it you try to generate xml output, you have to send the header before xml output to tell teh browser it is xml, like below: header("Content-Type: text/xml; charset=UTF-8"); $smarty->display('cart/popin.tpl'); 2. How to add html code in a xml node To have html in a xml node, you have to use CDATA:

A CDATA section starts with "<![CDATA[" and ends with "]]>":

3. how to use jquery to get XML respond $.ajax({ url: $(this).attr('href'), type: 'GET', dataType: 'xml', timeout: 1000, error: function(){ alert('Error loading XML document'); }, success: function(xml){ // do something with xml //alert('what\'s next'); $('#buynow-result').html($(xml).find('pop').text()); $('#buynow-inform').show('slow'); }