Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Tuesday, November 20, 2012

Zend file upload and addfilter rename isnt working

Ive had spent many days repeatly on different project, stumbling on one same issue.
AddFilter rename isnt working on my file upload.

It was one simple solution,
first, never ever getValue from the field before addfilter rename is in place.

Its very easy that we miss out lines of code where by it tries to populate data model from form.
Also its also easy to accidentally getting value from model to replace upload form field.

Make sure addfilter rename is called before isvalid is checked.

Hope this will solve your hair pulling days figuring why it isnt working.
The worst part is, Zend Framework isnt complaining about it!

Monday, August 13, 2012

get date from Zend_Date

$zendate->toString(Zend_Date::DATE_MEDIUM);

Wednesday, August 1, 2012

jQuery form and Zend_Form File

It appears that Zend Form will validate fail if we are using ajax or jquery form to submit the form.
To fix the issue, just ensure the form is submitted with the parameter: iframe: true

Also note that IE 8 or below will behave strangely when submitting via jQuery Form with file input.
So avoid using it on IE8 or below...

Tuesday, May 15, 2012

Zend DB Select join

Example of joining table using dbtable (EntStudio_Db_Table_Abstract)

$maintable = "x";

$query = $dbtable->select();
$query->setIntegrityCheck(false);
$query->from($dbtable, array("*")); //only specify column for main table

   
$query->join(array("u" => "table2"),  $maintable . ".userid=u.id", array("username")); //only specify column for table2

to output to test:
echo $query;

to get results:

$resultSet = $dbtable->fetchAll($query);
$entries   = array();
foreach ($resultSet as $row) {
//... codes here
}


to get a single row:
$row = $dbtable->fetchRow($query);

Zend Notification

Zend built in notification are divided into session saved message, and current message.
$flashmsg = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');

To get last added message in previous request (which is saved in the session):
$flashmsg->hasMessages();
$aMsg = $flashmsg->getMessages();

To clear the messages storage:
$flashmsg->clearMessages();
--------------------
To get current added message (same request):

$flashmsg->hasCurrentMessages();
$aMsg = $flashmsg->getCurrentMessages();

To clear the current messages storage:
$flashmsg->clearCurrentMessages();


Please note that the current and the session message are separated, and need to be called respectively to retrieve all messages in the notification

zend view render vs layout render

To render another view file within the same controller,
$view / $this->render("filename.phtml");

to render a view file within layout:
$view / $this->layout()->render("filename"); //without .phtml


Friday, March 30, 2012

installing apc on kloxo

For Yum based OS:
sudo yum install pcre-devel
sudo pecl install apc

Then create /etc/php.d/apc.ini
insert content as follows:
extension=apc.so

then restart httpd

If you are still having some problem installing this, try refer here:

http://www.agileapproach.com/blog-entry/howto-install-pecl-apc-cache-centos-without-xampp

Thursday, December 1, 2011

htmlentities and utf8

Ever wonder why your utf8 charactors doesn't work with htmlentities?
try htmlspecialchars
Example:
$sResult = htmlspecialchars($sText, ENT_COMPAT, "UTF-8");

Wednesday, September 28, 2011

MySQL data contains chinese charactor become äöüßæåéé

It took me hours figuring this.
All my mysql data became symbols.
Then finally, i found the culprit.
1st, i converted my field and default charset of my table to unicode.
But i did not update the existing data to unicode. So it was my mistake.

2nd, in php, i changed my mysql_set_charset("UTF-8");
So now all the data from the table which contains original latin will be forced to utf-8.
So the symbol appear in my html output, so does phpmyadmin.

To fix this, i wrote a program to retrieve the data from latin charset, and
then output it as a code in array to replace the data later back to the database as utf-8.

Example:
mysql_set_charset("latin1", $conndb);
mysql_query("select ...");
$aData = mysql_fetch_assoc($query);

mysql_set_charset("utf-8", $conndb);
$aData["fieldname"] = utf8_encode($aData["fieldname"]);
//then update those record with newly encoded utf8
mysql_query("update table ... ");

so, the next time we query the database, ensure to use
mysql_set_charset("utf-8", $conndb);


Wednesday, September 21, 2011

utf encoding and json

If someone tell you that json doesnt work with utf8, they are wrong.
It does support utf8.
The main problem is the database side.
Ensure to set encoding of mysql connection charset to utf8 to have it working properly.

mysql_set_charset("utf8", $conn);//support for unicode

Saturday, July 30, 2011

php possible datetime gotcha

Initially, i thought it was a bug in php...
but i think thats how its suppose to work.

If any month with 31days, and the last month has less days than current date,
the strtotime("-1 month", mktime())
will return this month date, instead of last month.

Example: strtotime("-1 month", strtotime("2011-07-01"))
results: time of 2011-06-01.
But,
Example: strtotime("-1 month", strtotime("2011-07-31"))
results: time of 2011-07-01.

This is because minus 1 month of 2011-07-31 in math => 2011-06-31,
which results to 2011-07-01 due to no 31 days in june.


Wednesday, July 27, 2011

Concurrency / Que with clustering

I realize a lot of people depends on existing framework or infrastructure to achieve concurrency or Que system to achieve what they need.
Basically if one need to get multiple server to be synced for write, and read, its possible to do it manually by coding it with combination of python or php scripts to connect between nodes...

But faster way to achieve so is by using open source combination such as zookerper with cassandra and cage.

But Case have issue when you are using more than 3 nodes.
This issue with zookeeper having to sync all the nodes together to have the transaction to run.
But after reading an article, its nice to have 2 or 3 nodes for transaction of 1 group of zookeeper process and separated zookeeper for read process. But do we need zookeeper for all nodes?
I think its better to have cassandra to sync those data to those server passively instead...
Only maintain between 2-3 nodes for transaction update to ensure uptime.

Thursday, June 30, 2011

PHP regex to match any link on text

//1st match subdomain: xyz. OR
// next, match domain
// then match .
// then match dual extension: .com or .org or ...and .sg OR
// then match single extension: TLD: .com or .org or .net or .... OR
// then match single country name .us
// then match uri, example: /xxx
// also try to match ending /
// and also try to match with ending name /xxx/lastnamehere
$sSubDomainSet = "[^.,\:\+\s]*\."; // xyz.
$sPatSubDomain = "(" . $sSubDomainSet . ")*";
$sPatCountryDomain = "((com|org|net|name|mil|gov|co|info)\.[a-z]{2})";
$sPatTLD = "(com|org|net|name|mil|gov|info)"; //top level domain tld
$sPatCountryTLD = "([a-z]{2})";
$sURIChar = "[a-z0-9\.\?\=\&\(\&amp\;)\-\_\+\%]";
$sPatURI = "([\/]*" . $sURIChar . "*)?";
$sPatURISlash = "([\/])?";
$sPatLastName = "(" . $sURIChar . "*)";
//match last uri name, example domain.com/email/xxx (match xxx)
$sPattern = "/(" . "((http:\/\/)|(https:\/\/))?" . $sPatSubDomain . $sSubDomainSet .
"(" . $sPatCountryDomain . "|" . $sPatTLD . "|" . $sPatCountryTLD . ")" .
$sPatURI . $sPatURISlash . $sPatLastName .
")/is";
preg_match_all($sPattern, $sContent, $matches, PREG_PATTERN_ORDER);
if (count($matches[1]) > 0) {
$sResult = $matches[1][0];//match first title tag
}

Example Results:
Original: this is a link https://www.yahoo.com/, result: https://www.yahoo.com/
Original: this is a link https://yahoo.com, result: https://yahoo.com
Original: this is a link http://yahoo.com, result: http://yahoo.com
Original: this is a link www.yahoo.com, result: www.yahoo.com
Original: this is a link yahoo.com, result: yahoo.com
Original: this is a link www.yahoo.org, result: www.yahoo.org
Original: this is a link www.whitehouse.gov, result: www.whitehouse.gov
Original: this is a link www.whitehouse.mil, result: www.whitehouse.mil
Original: this is a link www.yahoo.net, result: www.yahoo.net
Original: this is a link yahoo.com.my, result: yahoo.com.my
Original: this is a link yahoo.org.my, result: yahoo.org.my
Original: this is a link yahoo.co.sg, result: yahoo.co.sg
Original: this is a link yahoo.co, result: yahoo.co
Original: this is a link yahoo.my, result: yahoo.my
Original: this is a link yahoo.us, result: yahoo.us
Original: this is a link xyz.123.www.yahoo.com, result: xyz.123.www.yahoo.com
Original: this is a link yahoo.com/news is this right?, result: yahoo.com/news
Original: this is a link yahoo.com/ i think so, result: yahoo.com/
Original: this is a link yahoo.com/aboutus.php, result: yahoo.com/aboutus.php
Original: this is a link yahoo.com/email/ maybe its right, result: yahoo.com/email/
Original: this is a link yahoo.com/email/compose,gotta love it, result: yahoo.com/email/compose
Original: this is a link yahoo.COM/email/compose.html?search=233 haha, result: yahoo.COM/email/compose.html?search=233
Original: this is a link yahoo.com/email/compose.html?search=233&xx=22 haha, result: yahoo.com/email/compose.html?search=233&xx=22
Original: this is a link yahoo.com/email/compose.html?search=233&uu=232 hehe, result: yahoo.com/email/compose.html?search=233&uu=232
Original: this is a link yahoo.com/email/compose.html?search=233&xx=2?ehh, result: yahoo.com/email/compose.html?search=233&xx=2?ehh
Original: this is a link yahoo.com/email/com-pose.html, result: yahoo.com/email/com-pose.html
Original: this is a link yahoo.com/email/com-pose_.html?a=1, result: yahoo.com/email/com-pose_.html?a=1
Original: this is a link yahoo.com/email/com+20%pose.html?a=1, result: yahoo.com/email/com+20%pose.html?a=1


p/s: yes i know the line with double ? is incorrect, im lazy to write it :)

Full pattern string:
/(((http:\/\/)|(https:\/\/))?([^.,\:\+\s]*\.)*[^.,\:\+\s]*\.(((com|org|net|name|mil|gov|co|info)\.[a-z]{2})|(com|org|net|name|mil|gov|info)|([a-z]{2}))([\/]*[a-z0-9\.\?\=\&\(\&amp\;)\-\_\+\%]*)?([\/])?([a-z0-9\.\?\=\&\(\&amp\;)\-\_\+\%]*))/is

updated aug 28, avoid +,: in name, added http and https support

Friday, April 22, 2011

PHP Gotcha! Running 2 php process via same Session ID

If you came accross requirement to run 2 or more php execution via ajax or cron,
with same Session id, you will meet 1 fallback to the 2 process.

The 2nd php process cannot end until the first process end.
Therefore, if you have a big file uploading on 1 ajax call, and you may call another ajax later,
all your other ajax have to wait for the initial big file uploading to be done before this ajax can fully end.
The 2nd process will execute everything until all register_shutdown_function function is executed, but will not exit until 1st process is done.

This is logically acceptable as you may not want 1 session changes to mixed up with another session changes between 2 processes.
But hope this will save you some time on it...

Friday, April 15, 2011

MySQL query gotcha!

Example:
SELECT * FROM `modx_listvalues` WHERE listvalue like '%_'

like '%_' will result in having all records selected.
Instead, use this
like '%\_'


Thursday, April 14, 2011

Cron but not frequent enough?

If you ever need a on going php process, lets say every 5 or 2 seconds once, you may use python script to do this.
Here is an example of a script:
--------------------
#!/usr/bin/env python
import thread
import time
import os
import sys

sPHPPath = "/usr/bin/php"

def myphp1():
  while 1:
    os.system(sPHPPath + " " + sys.path[0] + "/myphp1.php")
    time.sleep(2)

def myphp2():
  while 1:
    os.system(sPHPPath + " " + sys.path[0] + "/myphp2.php")
    time.sleep(2)

if __name__=="__main__":
  thread.start_new_thread(myphp1, ())
  thread.start_new_thread(myphp2, ())
  while 1:
    time.sleep(60)


Monday, April 11, 2011

PHPUnit and global variable

"PDOException: You cannot serialize or unserialize PDO instances"

If you use phpunit and encounter this message above, you are hit by phpunit nature.
PHPUnit by default serialize all object in global.
So if you have a pdo connection as global variable, or as a variable / properties of a global variable, then you will doomed to face this problem.

Solution:
If you have a class with a property of type xpdo,
create a function __sleep()
and return variable names in array without the xpdo property:
Example:
public function __sleep() {
$aKey = array_keys(get_object_vars($this));

$aResult = array();
foreach($aKey as $sKey) {
if ($sKey != "xpdo") $aResult[] = $sKey;
}
return $aResult;
}

Tuesday, April 5, 2011

php float problem

Example:
326.3 * 100 => 32630 (in double, as displayed in echo)
But, when you floor(326.3*100) => resulted as 32629 (sigh*)

The issue is because after multiplying 326.3 by 100, the double is kept as 32629.9999999 instead of 32630.

But if you floor(32630), as raw integer, you will get 32630.

To fix this issue, convert the result in string, and floor it.
Example:
$iResult = floor((326.3*100)."");
//resulting: 32630.


Thursday, March 17, 2011

object to array of a class with protected variable

Interesting finding for PHP.
By default, if you plan to use get_object_vars to change a class into array, its known that protected and private variable will not be exported to array. Even if you have __sleep method and __get method set to retrieve those variable.

The solution is to put get_object_vars within a method to return get_object_vars($this);

----------------
class A {
public $id = 1;
protected $name = "";

public function __get($name) {
return $this->$name;
}

public function __sleep() {
return array("id", "name");
}

public function toArray() {
return get_object_vars($this);
}
}

$o = new A();
print_r(get_object_vars($o)); //only public variable exposed
print_r($o->toArray()); // all variable are exposed

Sunday, February 6, 2011

PHP gmtime?

I've seen some forum talking about, how nice to have gmtime() function.
But according to some post, it seems that time() is already in gmtime.

But how do we convert a unixtimestamp stored via gmdate("Y-m-d H:i:s") to a offset where its not the server locale timezone?

Its kind of confusing.
But the trick i used was to add the offset to the timestamp, and check if daylight is in effect.
Example of code:
$gmtime = $oRow["ftime"];
$daylight = date("I", $gmtime);
$iOffsetHour = _user_timezone_offset_here;
if ($daylight){
if ($iOffsetHour > 0){ $iOffsetHour-=1; }
else { $iOffsetHour+=1; }
}
$iLocalTime = $gmtime + (60*60*$iOffsetHour);

And to get a quick gmtime():
$gmtime = strtotime(gmdate("Y-m-d H:i:s"));

If anyone find this wrong, please correct me.
thank you :)