NURUL FERDOUS

Archive for the ‘PHP’ Category

Recently I made a news bot named news@bot.im AKA newsbot24@yahoo.com with the help of a wrapper class wrote by Hasin Hayder. This cool API has been provided by imified recently to make your application IM enable easily . You may test my bot by sending any instant message to newsbot24@yahoo.com or sending a message from your GTalk. It will grab one of the latest 25 top news from http://www.news.google.com or http://www.bdnews24.com RSS feed. I have set caching time as 1200 so that it can be easily work with very less bandwidth. I used lastRSS class to grab the RSS feed as I am having some freight to use Google feed parser with JSON 😦

You can make one just for FREE from http://www.bot.im All you need is to DOWNLOAD the wrapper class to do it quick. Alternatively you may read the quick and dirty documentation from HERE.

Now lemme reveal the source code I used for my news bot :p

<?php
// include lastRSS
include "lastRSS.php";
include "class.imified.php";
// Set cache dir and cache time limit (1200 seconds)
// (don't forget to chmod cahce dir to 777 to allow writing)
$rss->cache_dir = './temp';
$rss->cache_time = 1200;
$rss->cp = 'UTF-8';
$rss->date_format = 'l';
//initiating bot...
//@param pass your imified user credentials
$im = new ImifiedHelper("YOUR-API-KEY-GIVEN-FROM-IMIFIED","DEVELOPERS-NAME","PASSWORD");
if(!isset($_REQUEST['msg']))
{
    echo "This is a newsbot. You may add it as news@bot.im or newsbot24@yahoo.com";
    die();
}

//callback
$im->setCallback("callback");
function callback($message, $step, $network, $userKey)
{
    global $im;
    $message = strtolower($message);
    if("inews" == $message){
        // Create lastRSS object
        $rss = new lastRSS;
        // Try to load and parse RSS file of Slashdot.org
        $rssurl = 'http://news.google.com/?output=rss';
        $rs = $rss->get($rssurl);
        if ($rs) {
            $i = rand(0,25);
            echo $title = strip_tags(htmlspecialchars_decode($rs['items'][$i]['title']."

"))."
";
            echo $description = strip_tags(htmlspecialchars_decode($rs['items'][$i]['description']))."
";
        }
        else {
            echo "Error: It's not possible to get $rssurl...";
        }
        $im->resetStep();
    }
    elseif("bdnews" == $message){
        // Create lastRSS object
        $rss = new lastRSS;
        $rssurl = 'http://rss.bdnews24.com/rss/english/home/rss.xml';
        $rs = $rss->get($rssurl);
        if ($rs) {
            $i = rand(0,25);
            echo $title = strip_tags(htmlspecialchars_decode($rs['items'][$i]['title']))."
";
            echo $description = strip_tags(htmlspecialchars_decode($rs['items'][$i]['description']))."
";
        }
        else {
            echo "Oops! Looks like Server is Busy! to get ".$rssurl." Give it a try with inews";
        }
    }
    else{
        echo "Please type help to see available commands";
        $im->resetStep();
    }
}
?>

Thanks to hasin bro for your cool wrapper class 🙂

Advertisements
Tags: , ,

At first I would like to thank http://www.docs.php.net for their clear and cool documentation. Recently I’ve gone through the differences in between php4 and php5. I’ve found some interesting things by studying this topic. I think you all should have a look if you want to be a good developer. If you want a better performance and more features in your application easily then this post is appropriate for you. Happy Christmas!!

Type Hinting
PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

New Object Model
In PHP 5 there is a new Object Model. PHP’s handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object’s identifier).

Many PHP programmers aren’t even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications.

List of new Keywords
These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on–but they’re not, really: they are language constructs. You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.You will find detailed documentation on these new keywords by clicking on it.

abstract catch clone final implements interface instanceof namespace private protected public throw try

__NAMESPACE__ __DIR__

Backward Incompatible Changes
Although most existing PHP 4 code should work without changes, you should pay attention to the following backward incompatible changes:

  • There are some new reserved keywords.
  • strrpos() and strripos() now use the entire string as a needle.
  • Illegal use of string offsets causes E_ERROR instead of E_WARNING. An example illegal use is: $str = ‘abc’; unset($str[0]);.
  • array_merge() was changed to accept only arrays. If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. Be careful because your code may start emitting E_WARNING out of the blue.
  • PATH_TRANSLATED server variable is no longer set implicitly under Apache2 SAPI in contrast to the situation in PHP 4, where it is set to the same value as the SCRIPT_FILENAME server variable when it is not populated by Apache. This change was made to comply with the » CGI specification. Please refer to » bug #23610 for further information, and see also the $_SERVER[‘PATH_TRANSLATED’] description in the manual. This issue also affects PHP versions >= 4.3.2.
  • The T_ML_COMMENT constant is no longer defined by the Tokenizer extension. If error_reporting is set to E_ALL, PHP will generate a notice. Although the T_ML_COMMENT was never used at all, it was defined in PHP 4. In both PHP 4 and PHP 5 // and /* */ are resolved as the T_COMMENT constant. However the PHPDoc style comments /** */, which starting PHP 5 are parsed by PHP, are recognized as T_DOC_COMMENT.
  • $_SERVER should be populated with argc and argv if variables_order includes “S”. If you have specifically configured your system to not create $_SERVER, then of course it shouldn’t be there. The change was to always make argc and argv available in the CLI version regardless of the variables_order setting. As in, the CLI version will now always populate the global $argc and $argv variables.
  • An object with no properties is no longer considered “empty”.
  • In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used. Otherwise the behaviour is the old.
  • get_class(), get_parent_class() and get_class_methods() now return the name of the classes/methods as they were declared (case-sensitive) which may lead to problems in older scripts that rely on the previous behaviour (the class/method name was always returned lowercased). A possible solution is to search for those functions in all your scripts and use strtolower(). This case sensitivity change also applies to the magical predefined constants __CLASS__, __METHOD__, and __FUNCTION__. The values are returned exactly as they’re declared (case-sensitive).
  • ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.
  • If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn’t complain about it. It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.
  • include_once() and require_once() first normalize the path of included file on Windows so that including A.php and a.php include the file just once. Read the rest of this entry »

This wrapper class is a gift for my blog readers. I think the class is self descriptive. This is why I ain’t write how to use it bla bla bla…You can make pcl and ps files from html with this class. I have submitted this class at phpclasses too. You may have a look by clicking HERE. It runs both on Windows and *Nix envioronment.

html2pcl class starts here:

<?php
/* Description of wrapper class Html2pcl
* This class is used to produce .PCL and .PS file from HTML file
* @Author      : Nurul Ferdous
* Version      : 1.0.0
* Date         : 16 Dec 2008
* License      : Freeware
* Dependancy-1: html2ps package, you may get it from here: http://user.it.uu.se/~jan/html2ps.html
* you may install it from terminal by typing "sudo apt-get install html2ps" withpcl quote in kubuntu (in my case)
* html2ps uses perl
* Dependancy-2: Ghostscript, you may get it from here: http://pages.cs.wisc.edu/~ghost/
* Download it and run "make" command from terminal. you have to download and run exe installer if you use Windows
* The ps_output directory is used to store .ps files which are used to generate smaller sized pcl file
* keep in your mind that you should have write permission in "pcl_output" directory
*/

class Html2pcl {

    public $device = 'laserjet'; //alternatively you may use 'epson' etc as printers
    public $paperSize = 'a4'; //alternative you may use 'letter' etc as papersize

    function __construct(){
        //checking whether the directory named "out" already exists or not
        if(!file_exists("pcl_output")){
            mkdir("./pcl_output", 0755);
        }

        //checking whether the directory named "ps_output" already exists or not
        if(!file_exists("ps_output")){
            mkdir("./ps_output", 0755);
        }
    }

    function __destruct(){
        //Clearing file status cache
        clearstatcache();
    }

    function isWinServer()
    {
        return !(strpos(strtoupper($_SERVER&#91;'SERVER_SOFTWARE'&#93;), 'WIN32') === false);
    }

    //please don't use $htmlFileName without "http://" rather use like this "http://www.google.com"
    //please use $pclFileName without the extension like "google"
    function makePCL($htmlFileName, $pclFileName){
        $file = './pcl_output/'.$pclFileName.'.pcl';
        if($this-&gt;isWinServer()){
            //checking whether the file name given as parameter is already exists or not
            if(!file_exists($file)){
                exec("perl html2ps $htmlFileName &gt; ./ps_output/".$pclFileName.".ps");
                exec("gs -sDEVICE={$this-&gt;device} -sPAPERSIZE={$this-&gt;paperSize} -sOutputFile=./pcl_output/$pclFileName.pcl -dNOPAUSE -q ./ps_output/$pclFileName.ps -c quit");
            }
        }
        else{
            if(!file_exists($file)){
                exec("html2ps $htmlFileName &gt; ./ps_output/".$pclFileName.".ps");
                exec("gs -sDEVICE={$this-&gt;device} -sPAPERSIZE={$this-&gt;paperSize} -sOutputFile=./pcl_output/$pclFileName.pcl -dNOPAUSE -q ./ps_output/$pclFileName.ps -c quit");
            }
        }
    }
}
?>

Example usage starts here:

<?php
/*
* Usage of html2pcl class
*/
require_once('class.html2pcl.php');
$obj = new Html2pcl;
//please don't use $htmlFileName without "http://www." rather use like this "http://www.google.com"
//please use $pclFileName without the extension like "google"
$obj-&gt;makePCL("http://www.google.com", "google");
?>
Tags: ,

Are you working wih PHP MySQL? If your answer is yes, then you may have a look this free online test. This is an evaluation test for ZCE certification. You will find 8 questions there. Let me discuss on those questions a bit. Zillions of thanks to http://www.zend.com to organize this test:)

FYI I would like to suggest you not to read the rest of this post before completion of your test at : http://www.zend.com/store/education/certification/self-test.php?begin=1

Be back and read the rest of this post to check the correct answers. Good Luck!! Okay, Let’s start the test now!! Read the rest of this entry »

What is crontab? crontab  is  a  program which is used to install, deinstall or list the tables used to drive the cron(8) daemon in Vixie Cron. You can easily  have your    own    crontab,    and    though    these    are    files   in /var/spool/cron/crontabs, they are not intended to be edited  directly.
If  the /etc/cron.allow file exists, then you must be listed therein in order to be allowed to use this command.  If the  /etc/cron.allow  file does  not  exist  but the /etc/cron.deny file does exist, then you must not be listed in the /etc/cron.deny file in order to use this  command. If neither of these files exists, then depending on site-dependent configuration parameters, only the super user will be allowed to use  this command,  or  all  users will be able to use this command. For standard Ubuntu or Debian systems, all users may use this command.
The options of crontab command are given below:
If the -u option is given, it specifies the  name  of  the  user  whose crontab  is  to be tweaked.  If this option is not given, crontab examines “your” crontab, i.e., the crontab of the person executing the command.
crontab -l will show you your currently set up cron jobs on the server.
crontab -r will delete your current cron jobs.
crontab -e will allow you to add or edit your current cron jobs by using your default text editor to edit your “crontab file”. In my case Nano
Note that, vi has a bug in it and won’t work to edit your crontab! We recommend nano (which is just like pico), which is the default editor anyway! Read the rest of this entry »

Tags: , ,

1. Which of the following is not valid PHP code?
A. $_10
B. ${“MyVar”}
C. &$something
D. $10_somethings
E. $aVaR

Answer: PHP variables always start with a dollar sign and are a sequence of characters and numbers within the Latin alphabet, plus the underscore character. ${“MyVar”} is a valid variable name that simply uses a slightly less common naming convention, while &$something is a reference to the $something variable. Variables, however cannot start with numbers, making $10_somethings invalid and Answer D correct.

2. Which language construct can best represent the following series of if conditionals?
<?php
if($a == ‘a’) {
somefunction();
} else if ($a == ‘b’) {
anotherfunction();
} else if ($a == ‘c’) {
dosomething();
} else {
donothing();
}
?>
A. A switch statement without a default case
B. A recursive function call
C. A while statement
D. It is the only representation of this logic
E. A switch statement using a default case

Answer: A series of if…else if code blocks checking for a single condition as above is a perfect place
to use a switch statement:
<?php
switch($a) {
case ‘a’:
somefunction();
break;
case ‘b’:
anotherfunction();
break;
case ‘c’:
dosomething();
break;
default:
donothing();
}
?>
Because there is a catch-all else condition, a default case must also be provided for that
situation. Answer E is correct. Read the rest of this entry »

Tags: ,

I am Nurul Ferdous a Zend Certified Engineer (ZCE), serving at Bangladesh Internet Press Limited (BIPL) as programmer. I am a FOSS advocate and love RnD.

Categories

Me @ LinkedIn

View Nurul Ferdous's profile on LinkedIn

My Photos @ Flickr

Blog Stats

  • 42,620 [ Vistors ]

My Twitter Updates