crossz

Archive for the ‘php’ Category

HOWTO: php.ini for both xdebug and zenddebugger in both Eclipse and M(L)AMP

In php on May 12, 2009 at 1:19 am

Note: Either zenddebugger or xdebug is not included by default, (all-in-one PDT saying zenddebugger is included), You’d better check and install from software update in Eclipse.

The content in the end of php.ini
;========================================
[Zend]
zend_optimizer.optimization_level=15
zend_extension_manager.optimizer=/Applications/MAMP/bin/php5/zend/lib/Optimizer-3.3.3
zend_optimizer.version=3.3.3

;+++++++++++++++++++++++
;zend_extension=/Applications/MAMP/bin/php5/zend/lib/ZendExtensionManager.so
;+++++++++++++++++++++++

zend_extension=/Applications/MAMP/bin/php5/zend/lib/ZendOptimizer.so
zend_extension=/Applications/MAMP/bin/php5/zend/lib/ZendDebugger.so

;+++++++++++++++++++++++
;zend_extension=/Applications/MAMP/bin/php5/lib/php/extensions/no-debug-non-zts-20050922/xdebug.so
;+++++++++++++++++++++++

xdebug.file_link_format=”txmt://open?url=file://%f&line=%1″

xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.idekey=

HOWTO[mac]: php.ini for both xdebug and zenddebugger in both Eclipse and M(L)AMP

In php on May 12, 2009 at 1:19 am

Note: Either zenddebugger or xdebug is not included by default, (all-in-one PDT saying zenddebugger is included), You’d better check and install from software update in Eclipse.

xdebug.so: can be extract from the dmg file of Komodo .
zenddebugger: from zend or pdt (issued from zend), or http://downloads.zend.com/pdt/server-debugger/

Note: Sometime, when the debugger is changed, the xdebug will not work any more on that project. Copy all the files into a new php project, it will work fine. This seems that the some of the project properties are changed during debuger is changed. (so far, don’t know which modified property cause this issue). Refactor, such as rename, the project name will fix it.

The content in the end of php.ini

;========================================
[Zend]
zend_optimizer.optimization_level=15
zend_extension_manager.optimizer=/Applications/MAMP/bin/php5/zend/lib/Optimizer-3.3.3
zend_optimizer.version=3.3.3

;———————– to be removed; it never runs well with this line
;zend_extension=/Applications/MAMP/bin/php5/zend/lib/ZendExtensionManager.so
;———————–

[ZendDebugger]
zend_extension=/Applications/MAMP/bin/php5/zend/lib/ZendDebugger.so

; Sometime, to enable Zend Debugger, Xdebug need to be disabled in php.ini; vice versa.

[xdebug]
zend_extension=/Applications/MAMP/bin/php5/lib/php/extensions/no-debug-non-zts-20050922/xdebug.so
;xdebug.file_link_format=”txmt://open?url=file://%f&line=%1″
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.idekey=

Php, Joomla: alphacontent(joomla component) show youtube thumbnail

In joomla, php on March 13, 2009 at 1:56 am

A very good frontpage component for joomla, AlphaContent, can pick up photos from article as thumbnail on the article list. However, it just pick up thumbnail for articles, which have photos inside, not for those only embed video object.

Modify the ‘function findIMG( $contenttext, $showfirstimg)’, in /components/com_alphacontent/assets/includes/alphacontent.functions.php, will solve this problem.

Solution:
=====================

<?php

$contenttext = <<<youtube
<div><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="425" height="350"><param name="width" value="425" /><param name="height" value="350" /><param name="src" value="http://www.youtube.com/v/e_0oqGy0OyY" /><embed type="application/x-shockwave-flash" width="425" height="350"
src="http://www.youtube.com/v/e_0oqGy0OyY"></embed></object></div>

youtube
;
$showfirstimg = '1';

//<img width="20" src="http://cnfeed.co.uk/images/stories/screenshot.png"></img>

function findIMG( $contenttext, $showfirstimg ) {
$image = "";

// check is there any img tag/images
if (preg_match_all('#<img(.*)>#', $contenttext, $match0) ) {
//print_r($match0);
if ( count($match0) ) {
$n = sizeof($match0[1]);
if ( $showfirstimg=='2' ) {
$contenttext = $match0[1][$n-1];
} else $contenttext = $match0[1][0];
}
// else $contenttext may just host video 'src'

// for image search
if ( preg_match_all('#src="(.*)"#Uis', $contenttext, $match ) ) {
//print_r($match);
if ( count($match) ) {
$n = sizeof($match[1]);
if ( $showfirstimg=='2' ) {
$image = $match[1][$n-1];
} else $image = $match[1][0];
}
return $image;
}
}

// for youtube video search, just the first video thumbnail
if ( preg_match('#src="(.*)"#Uis', $contenttext, $match_video ) ) {
//print_r($match_video);
if ( count($match_video) ) {
if (preg_match('#youtube#i', $match_video[0], $match_temp) ) {
$youtube_src = $match_video[1];
//print_r($youtube_src);
if (preg_match('/v[\=\/][a-zA-Z0-9_]{1,}&/',$youtube_src, $image_0)) {
preg_match('/v[\=\/](.*)&/',$image_0[0], $image_1);
} else {
preg_match('/v[\=\/](.*)/',$youtube_src, $image_1);
}

//print_r($image_1);
$vid = ( $image_0 === null ) ? Vj9ChXA9y8I : $image_1[1];
$image = "http://img.youtube.com/vi/".$vid."/0.jpg";
}

// for other video search, static image to inform others: othervideo.png
else {
$image = "http://cnfeed.co.uk/images/othervideo.png";
}
}
}

if ($image == ''){
$image = "http://cnfeed.co.uk/images/noimage.png";
}

return $image;
}

echo findIMG( $contenttext, $showfirstimg );
?>

Regular expression and Possible modifiers in regex patterns in Php

In php on March 12, 2009 at 8:13 pm

Regular expression tool – regex.larsolavtorvik.com: “Help PHP PCRE

.
Any character
^
Start of subject (or line in multiline mode)
$
End of subject (or line in multiline mode)
[
Start character class definition
]
End character class definition
|
Alternates (OR)
(
Start subpattern
)
End subpattern
\
Escape character
\n
Newline (hex 0A)
\r
Carriage return (hex 0D)
\t
Tab (hex 09)
\d
Decimal digit
\D
Charchater that is not a decimal digit
\h
Horizontal whitespace character
\H
Character that is not a horizontal whitespace character
\s
Whitespace character
\S
Character that is not a whitespace character
\v
Vertical whitespace character
\V
Character that is not a vertical whitespace character
\w
‘Word’ character
\W
‘Non-word’ character
\b
Word boundary
\B
Not a word boundary
\A
Start of subject (independent of multiline mode)
\Z
End of subject or newline at end (independent of multiline mode)
\z
End of subject (independent of multiline mode)
\G
First matching position in subject
n*
Zero or more of n
n+
One or more of n
n?
Zero or one occurrences of n
{n}
n occurrences
{n,}
At least n occurrences
{,m}
At the most m occurrences
{n,m}
Between n and m occurrences”

Possible modifiers in regex patterns
============================
i (PCRE_CASELESS)
If this modifier is set, letters in the pattern match both upper and lower case letters.
s (PCRE_DOTALL)
If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl’s /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
U (PCRE_UNGREEDY)
This modifier inverts the “greediness” of the quantifiers so that they are not greedy by default, but become greedy if followed by “?”. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

#, in php regular expression

In php, symbol on March 12, 2009 at 7:42 pm
In PHP’s patterns, you always start with a delimiter (the first character in the pattern) and end with the same. Then follow it with any modifiers. These all work the same:

/[a-z]/i
#[a-z]#i
%[a-z]%i

#, in php regular expression

In php, symbol on March 12, 2009 at 7:42 pm
In PHP’s patterns, you always start with a delimiter (the first character in the pattern) and end with the same. Then follow it with any modifiers. These all work the same:

/[a-z]/i
#[a-z]#i
%[a-z]%i

php long string assign

In php on March 12, 2009 at 12:41 pm


$contenttext = <<<youtube

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="480" height="295"><param name="width" value="480" /><param name="height" value="295" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/KcAnhjr2R5w&hl=en&fs=1" /><embed type="application/x-shockwave-flash" width="480" height="295" allowfullscreen="true" allowscriptaccess="always" src="http://www.youtube.com/v/KcAnhjr2R5w&hl=en&fs=1"></embed></object>

youtube

;

Php Stream

In php on February 12, 2009 at 2:10 pm
The first thing you learn about in PHP is probably how to print something. This is usually done with a call to the echo or print, but there is another way to print things by writing content directly to the output buffer. The following code looks like you are writing to a file, but the text will appear in the browser window because we are writing to the php://output output stream.

$fp = fopen(“php://output”, ‘r+’);
fputs($fp, “Hello World”);

Or another way…

file_put_contents(“php://output”, “Hello World”);

The php://output stream is an encapsulation between PHP and the browser. The stream doesn’t really exist, but PHP knows what to do with it.

More about Php stream:
http://uk3.php.net/manual/en/function.stream-get-contents.php

Php Stream

In php on February 12, 2009 at 2:10 pm
The first thing you learn about in PHP is probably how to print something. This is usually done with a call to the echo or print, but there is another way to print things by writing content directly to the output buffer. The following code looks like you are writing to a file, but the text will appear in the browser window because we are writing to the php://output output stream.

$fp = fopen(“php://output”, ‘r+’);
fputs($fp, “Hello World”);

Or another way…

file_put_contents(“php://output”, “Hello World”);

The php://output stream is an encapsulation between PHP and the browser. The stream doesn’t really exist, but PHP knows what to do with it.

More about Php stream:
http://uk3.php.net/manual/en/function.stream-get-contents.php

Mysql usages comparison in php, joomla and drupal

In joomla, mysql, php on February 1, 2009 at 12:48 pm



## php_mysql: ####

<?
$username="username";
$password="password";
$database="your_database";

$link = mysql_connect(localhost,$username,$password);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';

@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

echo "<b><center>Database Output</center></b><br><br>";

$i=0;
while ($i < $num) {

$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");

echo "<b>$first $last</b><br>Phone: $phone<br>Mobile: $mobile<br>Fax: $fax<br>E-mail: $email<br>Web: $web<br><hr><br>";

$i++;
}

?>

## Joomla_mysql: ####
## Normally in a helper class ####
<?php
/**
* Helper class for Hello World! module
*
* @package    Joomla.Tutorials
* @subpackage Modules
*/
class modHelloWorldHelper
{
function getHello( $userCount ){
        
        //$db = &JFactory::getDBO();
        $username="gigibri1_cross";
$password="zhengxin";
$database="gigibri1_dev";
        
        mysql_connect(localhost,$username,$password);
        @mysql_select_db($database) or die( "Unable to select database");

// get a list of all users
$query = 'SELECT * FROM jos_users';
//$db->setQuery($query);
$result = mysql_query($query);

$items = ($items = $db->loadObjectList())?$items:array();
// create a new array and fill it up with random users
$actualCount = count($items);
if ($actualCount < $userCount) {
    $userCount = $actualCount;
}
$items2 = array();
$rands = array_rand($items, $userCount);
foreach ($rands as $rand) {
     $items2[] = $items[$rand];
}
return $items2;

mysql_close();
return $result;
    }    
}

## Drupal_mysql: ####
## Normally in a module file ####
  $result_sell_price = db_fetch_object(db_query('SELECT i.sell_price FROM {image} i WHERE i.vid = %d', $node->vid));
  $node->sell_price=$result_sell_price->sell_price;
  
  
  
$result = db_query("SELECT i.image_size, f.filepath FROM {image} i INNER JOIN {files} f ON i.fid = f.fid WHERE i.nid = %d", $node->nid);
$node->images = array();
while ($file = db_fetch_object($result)) {
    $node->images[$file->image_size] = file_create_path($file->filepath);
}

Mysql usages comparison in php, joomla and drupal

In joomla, mysql, php on February 1, 2009 at 12:48 pm



## php_mysql: ####

<?
$username="username";
$password="password";
$database="your_database";

$link = mysql_connect(localhost,$username,$password);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';

@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM contacts";
$result=mysql_query($query);

$num=mysql_numrows($result);

mysql_close();

echo "<b><center>Database Output</center></b><br><br>";

$i=0;
while ($i < $num) {

$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
$mobile=mysql_result($result,$i,"mobile");
$fax=mysql_result($result,$i,"fax");
$email=mysql_result($result,$i,"email");
$web=mysql_result($result,$i,"web");

echo "<b>$first $last</b><br>Phone: $phone<br>Mobile: $mobile<br>Fax: $fax<br>E-mail: $email<br>Web: $web<br><hr><br>";

$i++;
}

?>

## Joomla_mysql: ####
## Normally in a helper class ####
<?php
/**
* Helper class for Hello World! module
*
* @package    Joomla.Tutorials
* @subpackage Modules
*/
class modHelloWorldHelper
{
function getHello( $userCount ){
        
        //$db = &JFactory::getDBO();
        $username="gigibri1_cross";
$password="zhengxin";
$database="gigibri1_dev";
        
        mysql_connect(localhost,$username,$password);
        @mysql_select_db($database) or die( "Unable to select database");

// get a list of all users
$query = 'SELECT * FROM jos_users';
//$db->setQuery($query);
$result = mysql_query($query);

$items = ($items = $db->loadObjectList())?$items:array();
// create a new array and fill it up with random users
$actualCount = count($items);
if ($actualCount < $userCount) {
    $userCount = $actualCount;
}
$items2 = array();
$rands = array_rand($items, $userCount);
foreach ($rands as $rand) {
     $items2[] = $items[$rand];
}
return $items2;

mysql_close();
return $result;
    }    
}

## Drupal_mysql: ####
## Normally in a module file ####
  $result_sell_price = db_fetch_object(db_query('SELECT i.sell_price FROM {image} i WHERE i.vid = %d', $node->vid));
  $node->sell_price=$result_sell_price->sell_price;
  
  
  
$result = db_query("SELECT i.image_size, f.filepath FROM {image} i INNER JOIN {files} f ON i.fid = f.fid WHERE i.nid = %d", $node->nid);
$node->images = array();
while ($file = db_fetch_object($result)) {
    $node->images[$file->image_size] = file_create_path($file->filepath);
}

Php script to resize and add watermark

In php on December 22, 2008 at 7:43 pm
$xoffset=0;
$yoffset=0;
$opacitypercent = 80;
$scaling = 480;
$Photos=GetFileList();
foreach ($Photos as $original){
$watermark=’logo.png’;
AddWM($original,$watermark);
echo ‘*’;
}
function AddWM($photo,$watermark){
//xoffset of the watermark
global $xoffset;
//yoffset of the watermark
global $yoffset;
//the original image to be watermarked
$originalimage=$photo;
//the watermark to apply
$watermarkimage = $watermark;
//top end opacity number (totally transparent)
$opacity0 = @MagickGetQuantumRange();
//bootom opacity (totally visible)
$opacity100 = 0;
//desired opacity percentage
// THIS IS THE ONE TO SET
global $opacitypercent;
//gather the actual opacity number
$opacity = $opacity0 * ( 1 – $opacitypercent/100 ) ;
//initialize the wands
$sourceWand = NewMagickWand();
$compositeWand = NewMagickWand();
//read in the images
@MagickReadImage($sourceWand, $originalimage);
@MagickReadImage($compositeWand, $watermarkimage);
//resize the original photo
global $scaling;
$PhotoWidth = MagickGetImageWidth($sourceWand);
$PhotoHeight = MagickGetImageHeight($sourceWand);
$WvsH = $PhotoWidth/$PhotoHeight;
if($WvsH>=1){
$resizeresult = MagickScaleImage( $sourceWand, $scaling, $scaling/$WvsH);
}else{
$resizeresult = MagickScaleImage( $sourceWand, $scaling*$WvsH, $scaling);
}
//setting the image index
MagickSetImageIndex($compositeWand, 0);
MagickSetImageType($compositeWand, MW_TrueColorMatteType);
//seting the opacity level
MagickEvaluateImage($compositeWand, MW_SubtractEvaluateOperator, $opacity, MW_OpacityChannel) ;
//combining the images
@MagickCompositeImage($sourceWand, $compositeWand, MW_OverCompositeOp, $xoffset, $yoffset);
//create a subdirectory to store photos with watermark
if(!is_dir(“PhotosWithWaterMark”)){
mkdir(“PhotosWithWaterMark”, 0755);
}
//generate the image
MagickWriteImage( $sourceWand, “PhotosWithWaterMark/”.”WM_”.$photo);
}
function GetFileList(){
$dir = “./”;
$PhotoFormats = array(‘jpg’,'jpeg’);
// Open a known directory, and proceed to read its contents
if ($dh = opendir($dir)) {
$PhotosList = ”;
while (($file = readdir($dh)) !== false) {
$NameExt = explode(“.”,$file);
if (in_array(strtolower($NameExt[count($NameExt)-1]),$PhotoFormats)){
echo “filename: $file” . “\n”;
$PhotosList[] = $file;
}
}
closedir($dh);
}
return $PhotosList;
}
?>

HOWTO: using Php to add watermark

In php on December 21, 2008 at 3:14 am

<?php

makewatermark();

function makewatermark()
{
///////////////
// php imagemagick test harness
//
// create a watermarked image
///////////////

//xoffset of the watermark
//yoffset of the watermark

//the original image to be watermarked
$rawimage = NewMagickWand();
MagickReadImage( $rawimage, ‘cyclops.gif’ );
MagickWriteImage($rawimage, ‘new_image.jpg’ );
$originalimage=’new_image.jpg’;
//the watermark to apply
$watermarkimage = “sphinx.gif”;

//top end opacity number (totally transparent)
$opacity0 = @MagickGetQuantumRange();

//bootom opacity (totally visible)
$opacity100 = 0;

//desired opacity percentage
// THIS IS THE ONE TO SET
$opacitypercent = 50;

//gather the actual opacity number
$opacity = $opacity0 – ($opacity0 * $opacitypercent/100 ) ;

//validate the opacity number
if ($opacity > $opacity0){
$opacity = $opacity0;
}elseif ($opacity <0){
$opacity = 0;
}

//initialize the wands
$sourceWand = NewMagickWand();
$compositeWand = NewMagickWand();

//read in the images
@MagickReadImage($compositeWand, $watermarkimage);
@MagickReadImage($sourceWand, $originalimage);

//setting the image index
MagickSetImageIndex($compositeWand, 0);
MagickSetImageType($compositeWand, MW_TrueColorMatteType);

//seting the opacity level
MagickEvaluateImage($compositeWand, MW_SubtractEvaluateOperator, $opacity, MW_OpacityChannel) ;

//combining the images
@MagickCompositeImage($sourceWand, $compositeWand, MW_ScreenCompositeOp, 0, 0);

//print out the image
MagickWriteImage( $sourceWand, ‘new_image.jpg’ );
//header(“Content-Type: image/jpeg”);
//MagickEchoImageBlob($sourceWand);
}
?>

a PHP script to transfer files between iphone and linux/mac computer

In howto, php on August 3, 2008 at 8:23 pm
#!/usr/bin/php

<?php
# requirement:
# a)the work directory on PC/laptop is /home/cross/iphone, which you should modify to suit your situation.
# b)install php on iphone.

# To transfer file from PC to iphone:
# php trans.php FILETOTRANSFER
# To transfer file from iphone to pc:
# php trans.php -[anything] FILETOTRANSFER

$port_lsbu = 150;
$port_home = 75;

$athome = shell_exec(“ifconfig”); // check where are you now.

if (substr($argv[1],0,1)==’-') { // get the first argument, if it starts with ‘-’, then transfer from iphone
if(stristr($athome, ‘192.168.1.57′) == FALSE) { // ip address of iphone at home is this, this command can find out where i am.
echo ‘from iphone to lsbu pc’;
$output = shell_exec(“scp ./{$argv[2]} cross@136.148.98.{$port_lsbu}://home/cross/iphone/”); //using scp to transfer.
}else{
echo ‘from iphone to home laptop’;
$output = shell_exec(“scp ./{$argv[2]} cross@192.168.1.{$port_home}://home/cross/iphone/”);
}
}else{ // no option, which start with ‘-’. only what file to transfer.
if(stristr($athome, ‘192.168.1.57′) == FALSE) {
echo ‘from lsbu pc to iphone’;
$output = shell_exec(“scp cross@136.148.98.{$port_lsbu}://home/cross/iphone/{$argv[1]} .”);
}else{
echo ‘from home laptop to iphone’;
$output = shell_exec(“scp cross@192.168.1.{$port_home}://home/cross/iphone/{$argv[1]} .”);
}
}

echo $output;
echo “done!”;
?>

a PHP script to transfer files between iphone and linux/mac computer

In howto, php on August 3, 2008 at 8:23 pm
#!/usr/bin/php

<?php
# requirement:
# a)the work directory on PC/laptop is /home/cross/iphone, which you should modify to suit your situation.
# b)install php on iphone.

# To transfer file from PC to iphone:
# php trans.php FILETOTRANSFER
# To transfer file from iphone to pc:
# php trans.php -[anything] FILETOTRANSFER

$port_lsbu = 150;
$port_home = 75;

$athome = shell_exec(“ifconfig”); // check where are you now.

if (substr($argv[1],0,1)==’-') { // get the first argument, if it starts with ‘-’, then transfer from iphone
if(stristr($athome, ‘192.168.1.57′) == FALSE) { // ip address of iphone at home is this, this command can find out where i am.
echo ‘from iphone to lsbu pc’;
$output = shell_exec(“scp ./{$argv[2]} cross@136.148.98.{$port_lsbu}://home/cross/iphone/”); //using scp to transfer.
}else{
echo ‘from iphone to home laptop’;
$output = shell_exec(“scp ./{$argv[2]} cross@192.168.1.{$port_home}://home/cross/iphone/”);
}
}else{ // no option, which start with ‘-’. only what file to transfer.
if(stristr($athome, ‘192.168.1.57′) == FALSE) {
echo ‘from lsbu pc to iphone’;
$output = shell_exec(“scp cross@136.148.98.{$port_lsbu}://home/cross/iphone/{$argv[1]} .”);
}else{
echo ‘from home laptop to iphone’;
$output = shell_exec(“scp cross@192.168.1.{$port_home}://home/cross/iphone/{$argv[1]} .”);
}
}

echo $output;
echo “done!”;
?>

howto: php: quote usage

In Blogged, howto, php on August 1, 2008 at 4:12 pm

Step 1 – PHP string basic

You can set a string in three different ways. It’s up to you what method do you use, all have pros.

  1. The
    first and most known way is to specify a string in single quotes.
    Similar to other programing languages you need to use backslash ‘\’ if
    you want to display a single quote in your text.
    Code:
    1. <?php
    2. $str_1 = 'Demo text';
    3. $str_2 = 'Demo text with single quote(\')';
    4. echo $str_1;
    5. echo $str_2;
    6. ?>
  2. The
    second option to use double quotes. Between double quotes you can use
    more escape character in your string. Besides this if you put a
    variable in the string then PHP will interpret it and display the
    content of the variable.
    Code:
    1. <?php
    2. $str_1 = "Demo text";
    3. $str_2 = "Demo text with double quote(\")\r\n";
    4. $demo = "Internal";
    5. $str_3 = "This is a $demo string";
    6. echo $str_1;
    7. echo $str_2;
    8. echo $str_3;
    9. ?>

    Here the most important part is the string defined as $str_3 and its output in line 8 will result this:

    Output:
    This is a Internal string
  3. And
    last you can use heredoc as well. In this case you define your text
    between heredoc identifiers. In this case it is DEMO. You need to start
    it with the operator <<< and then the identifier. If you are
    ready you need to close the heredoc part by adding the identifier again
    at the beginning of a new line like this:
    Code:
    1. <?php
    2. $str_1 = <<<DEMO
    3. This is a heredoc message
    4. Text.
    5. DEMO;
    6. echo $str_1;
    7. ?>

    As
    you can see the output is in the same formatting – text indent, new
    lines – as it was defined. You can use variables in case of heredoc as
    well as in case of double quoted strings.

The 2.
case is the most interesting string definition version so let’s see a
bit more how to insert a variable inside a string. (You can use
variables in case 3. as well but heredoc is not so common.)

Step 2 – Variable parsing in string

Time to time you need to compose a complete text from sub strings
and variables. For example if you want to greet your visitor you want
to display a text like:

“Hello Peter, nice to see you again!”

Of
course you can not hard code the user name but you want to use a
variable like $userName. If you use single quoted strings then you can
display your text like this:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo 'Hello '.$userName.', nice to see you again!';
  4. ?>

Using double quotes you can make it more simple:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "Hello $userName, nice to see you again!";
  4. ?>

The more variable you need to use the bigger is the difference.

After the basic case let’s see some more complex variable parsing. What if you want to display the text:

“Peters website”

Using the above examples the $userName variable contains only the string Peter and if you compose your string as before:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "$userNames website";
  4. ?>

You will get a warning and the result is not what you expected:

Output:
Notice: Undefined variable: userNames in Z:\wdocs\test.php on line 4 website

To solve this problem you need to enclose the variable in curly braces like in the following example:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "${userName}s website";
  4. echo "{$userName}s website";
  5. ?>

As you can see it is possible to enclose only the variable name without the $ sign or the complete variable.

You have to use this solution in case of arrays as well in the following way:

Code:
  1. <?php
  2. $users = array('U1' => "Peter");
  3. echo "Hello {$users['U1']}, nice to see you again!";
  4. ?>

howto: php: quote usage

In Blogged, howto, php on August 1, 2008 at 4:12 pm

Step 1 – PHP string basic

You can set a string in three different ways. It’s up to you what method do you use, all have pros.

  1. The
    first and most known way is to specify a string in single quotes.
    Similar to other programing languages you need to use backslash ‘\’ if
    you want to display a single quote in your text.
    Code:
    1. <?php
    2. $str_1 = 'Demo text';
    3. $str_2 = 'Demo text with single quote(\')';
    4. echo $str_1;
    5. echo $str_2;
    6. ?>
  2. The
    second option to use double quotes. Between double quotes you can use
    more escape character in your string. Besides this if you put a
    variable in the string then PHP will interpret it and display the
    content of the variable.
    Code:
    1. <?php
    2. $str_1 = "Demo text";
    3. $str_2 = "Demo text with double quote(\")\r\n";
    4. $demo = "Internal";
    5. $str_3 = "This is a $demo string";
    6. echo $str_1;
    7. echo $str_2;
    8. echo $str_3;
    9. ?>

    Here the most important part is the string defined as $str_3 and its output in line 8 will result this:

    Output:
    This is a Internal string
  3. And
    last you can use heredoc as well. In this case you define your text
    between heredoc identifiers. In this case it is DEMO. You need to start
    it with the operator <<< and then the identifier. If you are
    ready you need to close the heredoc part by adding the identifier again
    at the beginning of a new line like this:
    Code:
    1. <?php
    2. $str_1 = <<<DEMO
    3. This is a heredoc message
    4. Text.
    5. DEMO;
    6. echo $str_1;
    7. ?>

    As
    you can see the output is in the same formatting – text indent, new
    lines – as it was defined. You can use variables in case of heredoc as
    well as in case of double quoted strings.

The 2.
case is the most interesting string definition version so let’s see a
bit more how to insert a variable inside a string. (You can use
variables in case 3. as well but heredoc is not so common.)

Step 2 – Variable parsing in string

Time to time you need to compose a complete text from sub strings
and variables. For example if you want to greet your visitor you want
to display a text like:

“Hello Peter, nice to see you again!”

Of
course you can not hard code the user name but you want to use a
variable like $userName. If you use single quoted strings then you can
display your text like this:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo 'Hello '.$userName.', nice to see you again!';
  4. ?>

Using double quotes you can make it more simple:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "Hello $userName, nice to see you again!";
  4. ?>

The more variable you need to use the bigger is the difference.

After the basic case let’s see some more complex variable parsing. What if you want to display the text:

“Peters website”

Using the above examples the $userName variable contains only the string Peter and if you compose your string as before:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "$userNames website";
  4. ?>

You will get a warning and the result is not what you expected:

Output:
Notice: Undefined variable: userNames in Z:\wdocs\test.php on line 4 website

To solve this problem you need to enclose the variable in curly braces like in the following example:

Code:
  1. <?php
  2. $userName = "Peter";
  3. echo "${userName}s website";
  4. echo "{$userName}s website";
  5. ?>

As you can see it is possible to enclose only the variable name without the $ sign or the complete variable.

You have to use this solution in case of arrays as well in the following way:

Code:
  1. <?php
  2. $users = array('U1' => "Peter");
  3. echo "Hello {$users['U1']}, nice to see you again!";
  4. ?>

Facebook application: Invitation page

In howto, php on March 17, 2008 at 2:43 pm


<?php

require_once 'facebook.php';

$appapikey = '1111111111111111111111111';

$appsecret = '111111111111111111111111111';

$facebook = new Facebook($appapikey, $appsecret);

$user = $facebook->require_login();

// Build your invite text

$invfbml = <<<FBML

You have been invited to join YQLM notifier.

<fb:name uid="$user" firstnameonly="true" shownetwork="false"/> wants you to add YQLM googlegroups Notifier. so that you can join

<fb:pronoun possessive="true" uid="$user"/>London YQLM GoogleGroups! <fb:req-choice url="http://www.facebook.com/add.php?api_key=$appapikey" label="Add this application" />

FBML;

?>

<fb:request-form type="YQLM Notifier" action="./index.php" content="<?=htmlentities($invfbml)?>" invite="true">

<fb:multi-friend-selector max="20" actiontext="Select your friends to add this application!" showborder="true" rows="3">

</fb:request-form>

Facebook application: Rss notifier

In howto, php on March 14, 2008 at 2:48 pm


<?php //create 1 hour life cookie to prevent duplicate news

feed story.

/*

session_start();

if(isset($_SESSION['views']))

  $_SESSION['views']=$_SESSION['views']+1;

else

  $_SESSION['views']=1;

echo "Total Visits: ". $_SESSION['views'];

//*/

////////// session or cookie /////////////////

if (isset($_COOKIE["updatetime"])){

}

else{

setcookie("updatetime", time(), time()+3600);

}

?>

<?php

require_once 'facebook.php';

$appapikey = '3d3fabe3276d1dd50ddf78353c719af4';

$appsecret = 'fe4754d97d24392ba9e40105f0ea0a08';

$facebook = new Facebook($appapikey, $appsecret);

$user_id = $facebook->require_login();

// Greet the currently logged-in user!

echo "<p>Hello, <fb:name uid=\"$user_id\" useyou=\"false\"

/>!<br/>"." There are new messages on the YQLM group.</p>";

?>

<?php

// Parse the Rss feed.

$doc = new DOMDocument();

$doc->load

('http://groups.google.co.uk/group/londonppl/feed/atom_v1_0_ms

gs.xml');

//$doc->load

('http://feeds.feedburner.com/YqlmLondonGoogleGroup');

$arr = array();

foreach ($doc->getElementsByTagName('entry') as $node) {

$itemRSS = array (

'author' => $node->getElementsByTagName

('name')->item(0)->nodeValue,

'email' => $node->getElementsByTagName

('email')->item(0)->nodeValue,

'date' => $node->getElementsByTagName

('updated')->item(0)->nodeValue,

'link' => $node->getElementsByTagName('link')

->item(0)->getAttribute("href"),

'title' => $node->getElementsByTagName

('title')->item(0)->nodeValue,

'desc' => $node->getElementsByTagName

('summary')->item(0)->nodeValue);

array_push($arr, $itemRSS);

}

?>

<?php

// Show Rss contents in facebook canvas.

$dashbutton = <<<EndHereDoc

<fb:dashboard> <fb:create-button

href="http://www.facebook.com/apps/application.php?

id=11393681690">Add/Remove this application</fb:create-button>

</fb:dashboard>

EndHereDoc;

echo $dashbutton;

for ($i=0;$i<10;$i++){

echo '<br/>'.'==================='.'<br/>';

$item = $arr[$i];

$author = ($item['author']=="")?$item['email']:$item

['author'];

$content = '<b>'.$author.'</b><i> said on </i>'.$item

['date'].'<br/>'.'<a href="'.$item['link'].'">'.$item

['title'].'</a><br/><li>'.$item['desc'].'</li>';

echo $content;

}

?>

<?php

// Generate short contents in users' profile file.

$profilecontent = '<a

href="http://apps.facebook.com/googlegroupsnotifier">YQLM

Group</a><br/>';

for ($i=0;$i<2;$i++){

$pitem = $arr[$i];

$author = ($pitem['author']=="")?$pitem

['email']:$pitem['author'];

$profilecontent =

$profilecontent.'==================='.'<br/><b>'.$author.'</b>

<i> said on </i>'.$pitem['date'].'<br/><i>'.$pitem

['title'].'</i><br/><li>'.$pitem['desc'].'</li><br/>';

}

?>

<?php

///*

// This is for fbml_setRefHandle

$fbml = <<<EndHereDoc

<fb:wide>

$profilecontent

<fb:editor

action="http://apps.facebook.com/googlegroupsnotifier">

<fb:editor-button value="More messages"/>

</fb:editor>

</fb:wide>

<fb:narrow>

$profilecontent

<fb:editor

action="http://apps.facebook.com/googlegroupsnotifier">

<fb:editor-button value="More messages"/>

</fb:editor>

</fb:narrow>

EndHereDoc;

$facebook->api_client->fbml_setRefHandle

("googlegroupsnotifier",$fbml);

// */

$refinprofile = '<fb:ref handle="googlegroupsnotifier" />';

$facebook->api_client->profile_setFBML

($refinprofile,$user_id);

?>

<?php

// This is for news feed/mini feed.

$title_template = "{actor} viewed the group";

$title_data = null;

$body_template = null;

$body_data = null;

$fitem = $arr[0];

$author = ($fitem['author']=="")?$fitem

['email']:$fitem['author'];

$feedcontent = '<br/>'.$author.' said

<br/><b>'.$fitem['desc'].'</b><br/> in the topic of

'.'<i>'.$fitem['title'].'</i>';

$body_general = 'The latest post : <br/>'.$feedcontent;

//print_r($_COOKIE);

//echo time()-$_COOKIE["updatetime"];

if (time()-$_COOKIE["updatetime"]>3600){

echo "<br/><i>A new news feed will be published in the

next 1 hour.</i>";

try{

$facebook->api_client-

>feed_publishTemplatizedAction

($title_template,$title_data,$body_template,$body_data,$body_g

eneral);

}catch(Exception $e) {

//this will clear cookies for your app and

redirect them to a login prompt

echo "<br/><br/><i>"."Update the news feed too

many times, no news will appear today."."</i>";

$facebook->set_user(null, null);

}

}

else

echo "<br/><i>No news feed will be published in the

next 1 hour.</i>";

?>