Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, August 26, 2009

PHP Multithreading for beginner

This entry is inspired by Iman "Sapi". Thank you sapi.

PHP has become not just web scripting language. Now PHP also widely use for simple server side shell scripting. PHP is proven a strong platform do perform database and www operation, such as querying, CURL-ing, http tunnelling and API's function.


The differences is at output and how long the script allowed to runs. Output of web-based PHP mostly markup languages bounded with fancy images and media files. But shell scripting only output only-God-knows log messages, and has no time limit.


Supported by enormous of active developer, PHP server scripting are very easy to those actively build applications under web. PHP also powerful to build heavy-duty task, such as file backup, backend server-to-server processes. Like Java, PHP5 now has the capability for multithreading, to increase processing speed. The only limit is memory and processor. But I found for doing certain task (my case) it's much lighter than using Java.

To enable, first make sure you've installed pcntl extension. On Ubuntu machine, install the extension files :
$ sudo apt-get install php5-dev
$ cd ~
$ mkdir php-temp
$ cd php-temp
$ sudo apt-get source php5
$ cd php5-xx.xx/ext/pcntl (xx.xx is your PHP5 subversion, pressing tab would reveal it)
$ sudo phpize
$ sudo ./configure
$ sudo make

Copy the compiled extension into modules library.
$ cp modules/* /usr/lib/php5/xxxxxx/ (xxxxx is php library date)

Restart apache
$ sudo /etc/init.d/apache2 restart


Next is, try copy and paste this simple script simulate the multithreading.
Further reading, please visit PHP official manual page. Happy multi-threading.



$children = 5;

for ($i=1; $i<=$children; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
SaveLog("THREADING","could not fork thread $i");
die("could not fork\n");
}
else if ($pid) {
# If we are the parent, we did our job of giving birth,
# now lets finish our job and die!
SaveLog("THREADING","Parent thread exiting..");
exit(0);
}
else {
# Since we are the child, fork so that init will become our parent. Init
# is good at wait()ing on children - ie: reaping.
$cpid = pcntl_fork();
if ($cpid == -1) {
SaveLog("THREADING","could not fork in child process $i");
die("could not fork in child process\n");
}
if (!$cpid) {
# Put your real task here, dont forget they're run as separate process, make sure no dependency each thread
SaveLog("THREADING","Thread $i started");
$result = StupidTask(10000000);
SaveLog("TASK","Result on thread $i : $result");
SaveLog("THREADING","Thread $i finished");
# Don't forget to exit after the child processing is done. Certainly
# change this exit code if you need to however.
exit(0);
}
}
}

function StupidTask($count) {
for ($i=1;$i<$count;$i++) {
}
return "I'm done doing stupid thing for $count times";
}

function SaveLog($type,$msg) {
global $logfile;
file_put_contents($logfile,date('Y-m-d H:i:s') . ' ' . $type . ' ' . $msg . "\n",FILE_APPEND);
return true;
}

Friday, January 9, 2009

Download KOMPAS Daily to your own server

Kompas starts today 2 July 2009, implements Microsoft's Silver Light framework, this download script temporary unable to fetch any edition




As most popular daily newspaper in indonesia, KOMPAS's content always been a compass most people to look to, from marketing to adv publisher, formal and informmal worker. As the biggest newspaper in country, everything in it counts, the news and advertorial. Some people may need it to be archived at their own for future reference.

As now, KOMPAS has their edition published online, you read it via internet browser. It uses djvu format, small image as thumbnail, combination of png (for text layer) and jpeg (for color photos layer). To download it, kind of hassle, because you might need to combine these two layers to get complete paper layout. Also, they just implement a sign up system to gather user information. Though it's free for now, but sure will consider a paid-scheme in the future.

If you want to keep ones as your archive, you install this script to your server, or you can try the working demo version. The interface isn't beautiful tough, but it's functional. Enjoy.

Demo version
Facebook version of KOMPAS
KOMPAS Script

Tuesday, October 28, 2008

Create Profesional Chart using PHP

As it function spread, PHP also can be develop into reporting agent. But creating chart graphic report using php never been this easy before i found ChartDirector. ChartDirector is a programming module that enable creation of chart based on given numeric data.

To install ChartDirector, simply go to its download section. Choose your platform, then extract into web-browsable folder. For Windows installation supposed no issue to highlight here. On Ubuntu, after several attempt, finally I got the installation works.

For Linux (Ubuntu) version, extract the package tar.gz into a web browseable folder. Then copy all co
ntent of lib into PHP shared object (so) folder, including all dll and font files. Remember to copy not move as the original file is needed for web browsable folder as well. To find out correct folder where the so lies, create a phpinfo() script.


Next is create an include entry in INI file. For Ubuntu, you may create a new file name it : chartdir.ini, put in /etc/php5/apache2/conf.d/ along with existing modules. For other system, put in php.ini :

#configuration for php chart director module
extension=phpchartdir520.dll

Remember, eventhough the loaded extention is dll, but it is a Linux extention. Do not load the so file as it will reported non-valid PHP module error. Restart your apache server. To make sure your installation is runs well, rerun the phpinfo, you should get this of your info page

This software is shareware, and lots of platform and programming language are available not just PHP. Even its cracks are easily to find on the net, please support by purchasing full version licences.

Tuesday, September 2, 2008

Enable Google Analytics without javascript


Site counter tracker has been a very important component for us to trace popularity of a web portal. Luckily, a lot of web site counter we can use freely. All these time I count on two site counter to track my pages. StatCounter.com offer a easy to manage and weekly reporting statistic tracker. Simply sign up and add new project to the account, and paste snippet to your HTML template. StatCounter free edition has limitation of storing last 500 records only for analysis.

Google analytics (GA) offer a more complete service, and advanced reporting tools. But so far I searched across the net, found nothing we can do to implement GA in pages (rss or widget) that not support JavaScript. With such limitation, we can't track images loadings, email reads, pdf files, and the most important to me : WML pages.

Got inspired from LinkLove, which is run smoothly on my server but lack of User Agent info, I try to alter some point. Instead of using fopen remote file, I use CUrl function. With CUrl function, we can send set HTTP header to GA to simulate the actual hit by handset to the GA Server. To know more, simply download and try it on your web server. This script is totally standalone, no external 3rd function needed.

On WML/RSS pages, instead of copying GA Urchin JS snippet, simply add a
<img src="http://yourserver.com/ga.php" alt="" /> tag like this :

<img src="http://yourserver.com/ga.php?t=UrchinCode&amp;d=your-original-domain" alt="GA" />

Wednesday, May 28, 2008

Integrate PHPBB login to your website

PHPBB is one of most widely used forum board system. Build on strength platform of PHP, PHPBB free yet stable and easy to configure. We can aware if a system using PHPBB as its forum board system, by its unique layout and themes.

For some website that doesn't have own member management system can use PHPBB for their user / login based system. PHPBB provide a solid member management system, sign up interface, also nice member profile interface.

For sign up, easiest way is using existing PHPBB signup form. More customization is required to match your website theme. Simply edit profile_add_body.tpl template under your phpbb/template/templatename/ folder. It's all in html + smarty code.

Next is to link a login form (on your main website) to phpbb login verification system. You need to create a form contain 3 main object : user name, password, and Login button


<form name="frmPhpBBLogin" action="your_phpbb_login.php" method="post">

User name : <input name="username" type="text">

Password : <input name="'password'" type="password">

<input value="'Login'" type="'submit'">

</form>




To get login info which stored in PHPBB session, simply get it from COOKIE data by
PHP Code snippet
-----------
$session_data = isset($_COOKIE['phpbb2_data'])?unserialize(stripslashes($_COOKIE['phpbb2_data'])) : array();
if (isset($session_data['userid'])) GetPHPBBMemberDetail($session_data['userid'])
function GetPHPBBMemberDetail($id) {
$myQR = "SELECT * FROM `phpbbdb`.`phpbbprefix_users` WHERE `user_id`='$id'";
$myRE = mysql_query($myQR);
return mysql_fetch_assoc($myRE);
}

------------
Note :
- Actual cookie variable name may vary, you can do a var_dump($_COOKIE) to find out.
- Change `phpbbdb` to your actual PHPBB database name
- Chnage `phpbbprefix_` to actual PHPBB table naming prefix
You must have mysql access to get all the data.

To log out simply hit PHPBB's logout url, normally at login.php?logout=true

Monday, April 28, 2008

Download Liputan6 video


Liputan6 is one of most popular news programme in Indonesia owned by SCTV (www.sctv.co.id) and has certains fanatic viewer, since Liputan6 gives a different point of view to a news. As it's slogan, Aktual, Tajam & Terpercaya, make it stand apart from other news programme.

Luckily, liputan6 has online version so even we're abroad and unable to watch this aired SCTV news programme, we can log on to its portal at www.liputan6.com. But to watch directly from the portal need at least 256kbps of steady connection. Even you has better connection, sometime it's not really enough due to the country's internet infrastructure is not sufficient for steady 256kbps streaming. When this happen, you need to download the video file and play locally.

Thanks to youtube, FLV is now the most popular video format on the net. Liputan6 uses VP6F codec FLV. At the resolution 320x240, each minute of video may sized up to 1MB.

At liputan6, each aired part will be create in one file. Each programme instance will contain 3 or 4 files. All files wrapped in a XML file. To download simply navigate your browser to http://www.liputan6.com/mediaplayer/playlist.php?program=prgramme_name. There are several valid programme name :
- l6pagi, for liputan 6 pagi, aired 5.00 am - 6.30 am daily.
- l6siang, for liputan 6 siang, aired daily at noon.
- l6petang, for liputan 6 petang, aired 17.30pm daily.
- l6malam, for liputan 6 malam, aired 00.00 am daily.
Some other non-daily news programme also available, like weekly's SIGI (id : sigi) and Topik Minggu ini (id : topik).

You may either visit addresses above daily and copy-paste FLV location to your download manager, or there's smarter way. If you have a always-connected internet and php installed, you can setup a scheduled download. Download this php script, change some configuration. Then add to crontab (if you use linux) or scheduled task (for windows user). php-cli must installed to be able run php script from linux shell.

Please notice each programme will publish to internet 30 minutes after aired.
Localtime is GMT +07.00.

Wednesday, December 19, 2007

Installing and Using WURFL with PHP

To build a download site that compatible for most mobile device is a very challenging task where we need to gather all these device capabilities and match it to our available services. But every device manufacturer might have a different format for describing its device capabilities.

WURFL is a very original idea to combine all device into a standard format that can be contribute by anyone. Using single XML file as it database core, most wireless handset capabilities can be query to it. By the time I post this, there's new version, WURFLDB that using real database. But I still prefer WURFL. WURFL with PHP is one of the great combination, where PHP is the most popluar language for developing a web/wap site, WURFL can deliver a query just in a blink of eye.

To download WURFL for PHP simply go to http://wurfl.sourceforge.net/php/index.php . Select the latest stable version. Once downloaded, simply unpack it into a web accessible folder (if you plan to make this detection available for public) or just put it into a internal folder and using command line PHP to access it.

Edit the wurfl_config.php file if necessary. In my installation, I edit the DATADIR directive to "/opt/www/html/wurfl/data/" instead of relative path "../data/". Make sure set permission on the folder to public writeable. For linux user, I recommend "chmod
/opt/www/html/wurfl/data/ 666". For Windows user (with folder security and permission set on, right click -> Properties -> Security). For initial folder content, download the WURFL database file wurfl.xml and save into the data dir.

Once saved, you can test the installation by accessing check_wurfl.php with full URL. There's text box for you to input the user agent manually. But on the real working environment, you maybe need to pass user's UA string from http header value $_SERVER['HTTP_USER_AGENT'] to the application. In my case, you can use PHP CURL function on wap site side and return the user agent using var_export($wurflObj->capabilities). You can also convert the result using any array to xml converter to switch the result's format. My sample installation is available here.

Once you get the data, it's now all up to you how to provide the appropriate service based on these data. Happy wurfl-ing !!

Tuesday, December 11, 2007

Building a wap site

Nowadays, everything has go mobile. If you have any service, make it available on mobile phone version, you'll have your service access more than if you just make it available on web only. This all because, almost at least 80% of world population have access to mobile phone network. And mobile phone is the one we carry wherever we go.

To build a mobile phone enabled site, your have few options. There's rich HTML version (HTML v.4.0) that supported by latest device such as Nokia Internet Table, Apple Iphone and Smart phone (PDA-phone). The middle version is xHTML which is supported by newer mobile phone (with colour screen). If you going to make it available on most phone models, use WML (wireless markup language). Latest version of WML is 1.3. A basic WML page would be looks like :


<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd">
<wml>
<head>
<meta http-equiv="Cache-Control" content="max-age=0" forua="true"/>

</head>
<card title="{$page_title|htmlspecialchars}">
<p align="center"><img src="your-logo-here" alt=""/></p>
<p>
{$main_content}


</p>

</card>
</wml>



Since WML only support basic font display, it only support bold, italic and underline, but no fancy fonts selection. This is the model that I most recommend, especially on developing country like Indonesia where new technology adoption is slow. More reading and discussion about WML can be found at WML programming mailing list. And the easiest way to test out your page is using openwave phone simulator.

If you're going to build a transactional wap site, make sure your server is supported and registered by wireless service provider (telco) so any access to the site can be detected its msisdn (mobile subscriber isdn a.k.a phone number). This information and other useful header can be found on HTTP HEADER variable HTTP_X_FH_MSISDN values. If you're using PHP, you can read that as $_SERVER[HTTP_X_FH_MSISDN] vars. Variables the supplied from telco may vary. Please read the documentation.

To provide content that match to certain phone models, you can use User Agent Profile (UAProf) to identify certain specification of the phone. But due to every device manufactures has different standard, you can use WURFL to determine most phone capabilities and specification. Now you have all the information needed to build a wap site, wap charging and provide content as the device supported.