Posts Tagged ‘php’

JSON_ERROR_SYNTAX while decoding huge json-encoded array

2014/02/21 3 comments

It took me a lot of time to eventually find out what was throwing the JSON error known as “JSON_ERROR_SYNTAX”. I was dealing with a huge array, more than 100,000 entries and 2MB in size. The PHP script processing the data always hangs when trying to decode the big array into a PHP variable. Using PHP function json_last_error() I could find out that JSON decoder was throwing the error code 4, meaning there was a syntax error in the json string.

Finally I found the array entry that makes JSON go crazy:


NULL. Yes. That’s the culprit. So, bottom line: avoid array null keys at all cost.

Here is the code I used to locate the error:

	function json_error() {
		switch(json_last_error()) {
				return '';
				return 'JSON_ERROR_DEPTH';
				return 'JSON_ERROR_CTRL_CHAR';
				return 'JSON_ERROR_SYNTAX';
			case JSON_ERROR_UTF8:
				return 'JSON_ERROR_UTF8';

		return 'Unknown Json error' . json_last_error();

echo "\nstrlen(json) = " . strlen($json);
$dummy = json_decode($json, 1);
if (json_error()) die('Json Error: ' . json_error() . "\n");

Hope this helps …

PHP time function, ISO 8601

2012/10/09 1 comment

This is a PHP time function according to the output format specified by ISO 8601 (yyyy-mm-dd hh:mm:ss):

function time_iso8601() {
$timearray = getdate(time());
return sprintf("%04d-%02d-%02d %02d:%02d:%02d", $timearray['year'], $timearray['mon'], $timearray['mday'], $timearray['hours'], $timearray['minutes'], $timearray['seconds']);

Categories: PHP, Snippets of Code Tags: , , ,

NOW() function in SQLite

2012/08/14 1 comment

NOW() function does not exist in SQLite. Instead use datetime(‘NOW’,’localtime’) as in the example:

<?prepare("SELECT datetime('NOW','localtime') AS now");
if (!$result) { echo "\nError SQLite::errorInfo(): "; print_r($dbsqlite->errorInfo()); }
$data = $result->fetchAll();
$now_SQLite = $data[0][0];
$dbsqlite = NULL;
echo "\nSQLite Time: " . $now_SQLite;

Categories: PHP, Snippets of Code Tags: , , , ,

How to install PHP 6 on CentOS 6

2011/11/08 Leave a comment

How to install PHP6 on CentOS6: These are the Linux commands required to install latest PHP source code into a CentOS 6 LAMP server, and several useful libraries as: GD, Curl, Tidy, JSON, SQLite, PSpell, …

yum install wget
wget ""
tar -jxvf php-trunk-201111071530.tar.bz2
cd php-trunk-201111071530
yum groupinstall "Development Tools"
yum install libxml2 libxml2-devel
yum install httpd-devel
yum install pcre pcre-devel
yum install bzip2 bzip2-devel
yum install gmp gmp-devel
yum install tidy libtidy libtidy-devel
yum install curl libcurl libcurl-devel
yum install libjpeg libjpeg-devel
yum install libpng libpng-devel
yum install libXpm libXpm-devel
yum install freetype freetype-devel
yum install aspell aspell-devel

./configure –build=x86_64-unknown-linux-gnu –host=x86_64-unknown-linux-gnu –target=x86_64-redhat-linux-gnu –program-prefix= –prefix=/usr –exec-prefix=/usr –bindir=/usr/bin –sbindir=/usr/sbin –sysconfdir=/etc –datadir=/usr/share –includedir=/usr/include –libdir=/usr/lib64 –libexecdir=/usr/libexec –localstatedir=/var –sharedstatedir=/var/lib –mandir=/usr/share/man –infodir=/usr/share/info –cache-file=../config.cache –with-libdir=lib64 –with-config-file-path=/etc –with-config-file-scan-dir=/etc/php.d –disable-debug –with-pic –disable-rpath –without-pear –with-bz2 –with-exec-dir=/usr/bin –with-freetype-dir=/usr –with-png-dir=/usr –with-xpm-dir=/usr –enable-gd-native-ttf –without-gdbm –with-gettext –with-gmp –with-iconv –with-jpeg-dir=/usr –with-openssl –with-pcre-regex=/usr –with-zlib –with-layout=GNU –enable-exif –enable-ftp –enable-magic-quotes –enable-sockets –enable-sysvsem –enable-sysvshm –enable-sysvmsg –with-kerberos –enable-ucd-snmp-hack –enable-shmop –enable-calendar –with-sqlite3 –with-libxml-dir=/usr –enable-xml –with-system-tzdata –with-apxs2=/usr/sbin/apxs –with-mysql –with-gd –disable-dom –disable-dba –without-unixODBC –disable-pdo –disable-xmlreader –disable-xmlwriter –disable-phar –disable-fileinfo –enable-json –with-pspell –disable-wddx –with-curl –disable-posix –disable-sysvmsg –disable-sysvshm –disable-sysvsem –enable-mbstring –with-mysqli –with-tidy

make install
sed -i ‘/^LoadModule php5_module/ s/^/#/’ /etc/httpd/conf/httpd.conf
service httpd restart

Getting snippets as search results in PHP

2011/08/15 Leave a comment

The following PHP code is a function that extracts snippets of text from a corpus, matching a given keyword and highlighting it with an HTML bold tag:

function get_snippet($keyword, $txt) {
  $span = 15;
  preg_match_all("#(\W.{0,$span}\W)($keyword)(\W.{0,$span}\W)#i", "  $txt  ", $matches);
  foreach($matches[0] as $match) {
    if (!$match = trim($match)) continue;
    if (isset($snippet)) $snippet .= "$match..."; else $snippet = "...$match...";
  $snippet = preg_replace("#($keyword)#i", '<b>$1</b>', $snippet);
  return $snippet;

Applying to a text like this:

Since its launch in November 2007, Android has not only dramatically increased consumer choice but also
improved the entire mobile experience for users. Today, more than 150 million Android devices have been
activated worldwide with over 550,000 devices now lit up every day through a network of about 39 manufacturers
and 231 carriers in 123 countries. Given Android’s phenomenal success, we are always looking for new ways to
supercharge the Android ecosystem. That is why I am so excited today to announce that we have agreed to acquire

Would throw an output like this, when searching for “Android” keyword:

...November 2007, Android has not only...150 million Android devices have....
Given Android’s phenomenal...supercharge the Android ecosystem. That...

Log rotation with file locking support

2011/08/09 Leave a comment

PHP programmingSame code from previous entry but adding file locking support and making it simple by using file_put_contents PHP function. Writing function is called using two flags FILE_APPEND, LOCK_EX. Bitwise OR operator (inclusive or) expressed by “|” symbol is used to attach several flags into 1 byte field. LOCK_EX is supposed to guarantee transaction safety. Nevertheless there are claims against that, here. I have added the PHP function
clearstatcache() before measuring the size of current log file, in order to get instant proper measures. Otherwise rotation wouldn’t occur unless the PHP script would end and restart again.


// Appends lines to file locked and makes sure the file doesn't grow too much
function append_line_to_limited_text_file($text, $filename) {
	if (!file_exists($filename)) { touch($filename); chmod($filename, 0666); }
	if (filesize($filename) > 2*1024*1024) {
		$filename2 = "$filename.old";
		if (file_exists($filename2)) unlink($filename2);
		rename($filename, $filename2);
		touch($filename); chmod($filename, 0666);
	file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);

Append text into a rotating log with PHP

2011/08/09 Leave a comment

If you ever needed a log rotate function in PHP check out this small snippet of code. It is meant to append lines of text into a log file, but avoiding it to grow limitless. When it reaches 2 Mb in size, automatically the log file is renamed adding .old extension to its file name. This is very useful for fast growing debugging log files. You may customize it defining another threshold for rotation triggering, just changing the value 2*1024*1024 ( 2 Mbytes). This code does not use external system calls, but just filesystem php native functions, so it should work properly under Linux and/or Windows servers. I am developing on a WAMP server over Windows 7 OS and this code seems to work as expected:

// Appends lines to file and makes sure the file doesn't grow too much
function append_line_to_limited_text_file($text, $filename) {
	if (!file_exists($filename)) { touch($filename); chmod($filename, 0666); }
	if (filesize($filename) > 2*1024*1024) {
		$filename2 = "$filename.old";
		if (file_exists($filename2)) unlink($filename2);
		rename($filename, $filename2);
		touch($filename); chmod($filename,0666);
	if (!is_writable($filename)) die("<p>\nCannot open log file ($filename)");
	if (!$handle = fopen($filename, 'a')) die("<p>\nCannot open file ($filename)");
	if (fwrite($handle, $text) === FALSE) die("<p>\nCannot write to file ($filename)");