User Tools

Site Tools


PHP example codes

Basic Examples for reading and understanding code(testing)


function myfunction() {
	list($string) = func_get_args();
	print $string;
myfunction("Hello, World!");


Hello, World!

reference variable

  • Simple reference:
    $a = 10;
    $b = &$a;
    print $a


  • Custom reference
    function &find_variable(&$one, &$two, &$three) {
    	if($one > 10 && $one < 20) return $one;
    	if($two > 10 && $two < 20) return $two;
    	if($three > 10 && $three < 20) return $three;
    $one = 2;
    $two = 20;
    $three = 15;
    $var = &find_variable($one, $two, $three);
    print "1: $one, 2: $two, 3: $three";


    1: 2, 2: 20, 3: 16

compare 2 values in the same type and value

$a = 2;
$b = '2';
if ($a == $b)
	print "$a == '$b'";
	print "not $a == '$b'";
if ($a === $b)
	print "\n$a === '$b'";
	print "\nnot $a === '$b'";

global variable

$a = 20;
function myfunction($b) {
	$a = 30;
	global $a, $c;
	return $c = ($b + $a);
print myfunction(40) + $c;



Class and Object

class ClassOne {
  protected $a = 10;
  public function changeValue($b) {
    $this->a = $b;
class ClassTwo extends ClassOne {
  protected $b = 10;
  public function changeValue($b) {
    $this->b = 10;
    parent::changeValue($this->a + $this->b);
  public function displayValues() {
    print "a: {$this->a}, b: {$this->b}\n";
$obj = new ClassTwo();


a: 30, b: 10

Send mail with PHP

php code

$subject = 'We Have Received Your Article';
$fromEmail = '[email protected]';
$fromName = 'shop';
$toEmail = '[email protected]';
$toName = 'Anh Vo';
$message= <<<EMAIL
Hi $toName!
I just wanted to notify you and let you know that I received your article and it will be reviewed shortly.
Douglas Brown
mail($toEmail,$subject,$message,"From: $fromEmail\n");

understand php email

email log: /var/log/maillog


May 23 09:03:59 mail postfix/pickup[3000]: 12F4E40A83: uid=48 from=<apache>
May 23 09:03:59 mail postfix/cleanup[3188]: 12F4E40A83: message-id=<[email protected]>
May 23 09:03:59 mail postfix/qmgr[1174]: 12F4E40A83: from=<[email protected]>, size=569, nrcpt=1 (queue active)
May 23 09:03:59 mail postfix/smtp[3190]: connect to[2607:f8b0:400e:c03::1a]:25: Network is unreachable
May 23 09:04:01 mail postfix/smtp[3190]: 12F4E40A83: to=<[email protected]>,[]:25, delay=2.2, delays=0.07/0/0.67/1.5, dsn=2.0.0, status=sent (250 2.0.0 OK 1400810645 xp1si1843220pab.44 - gsmtp)
May 23 09:04:01 mail postfix/qmgr[1174]: 12F4E40A83: removed

⇒ webserver apache use local account apache to send email

May 23 09:03:59 mail postfix/qmgr[1174]: 12F4E40A83: from=<[email protected]>, size=569, nrcpt=1 (queue active)

Solve problem: error log in sendmail

Sometime occur error below:

[Fri May 23 09:44:40 2014] [error] [client] PHP Warning:  mail(): Could not execute mail delivery program '/usr/sbin/sendmail -t -i' in testemail.php on line 17

⇒ Not enough memory for sending email

connect database with php_mysql

check connect database with pdo_mysql

$hostname = "localhost";
$username = "root";
$dbname = "tendatabase";
$password = "opLHghz9CkQ8FM";
try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
    echo "Connected to database"; // check for connection
catch(PDOException $e)
    echo $e->getMessage();
function vietnamese_permalink ($title, $replacement = '-')
		/* 	Replace with "-"
		//$replacement = '-';
		$map = array ();
		$quotedReplacement = preg_quote( $replacement, '/' );
		$default = array (
						'/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ|å/' => 'a',
						'/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ|ë/' => 'e',
						'/ì|í|ị|ỉ|ĩ|Ì|Í|Ị|Ỉ|Ĩ|î/' => 'i',						'/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ|ø/' => 'o',
						'/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ|ů|û/' => 'u',
						'/ỳ|ý|ỵ|ỷ|ỹ|Ỳ|Ý|Ỵ|Ỷ|Ỹ/' => 'y',
						'/đ|Đ/' => 'd',
						'/ç/' => 'c',
						'/ñ/' => 'n',
						'/ä|æ/' => 'ae',
						'/ö/' => 'oe',
						'/ü/' => 'ue',
						'/Ä/' => 'Ae',
						'/Ü/' => 'Ue',
						'/Ö/' => 'Oe',
						'/ß/' => 'ss',
						'/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
						'/\\s+/' => $replacement,
						sprintf( '/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement ) => ''
		//Some URL was encode, decode first
		$title = urldecode( $title );
		$map = array_merge( $map, $default );
		return strtolower( preg_replace( array_keys( $map ), array_values( $map ), $title ) );
$str = 'Rượu bàu đá';
$seolink = vietnamese_permalink($str);
echo $seolink;

⇒ output:


Read XML with PHP


Read xml file to object SimpleXMLElement


// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.
if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');
} else {
    exit('Failed to open test.xml.');

Read xml string to SimpleXMLElement

SimpleXMLElement is JSON Object

  • First We create example.php file with the xml content:
    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
      <title>PHP: Behind the Parser</title>
        <name>Ms. Coder</name>
        <actor>Onlivia Actora</actor>
        <name>Mr. Coder</name>
        <actor>El Act&#211;r</actor>
       So, this language. It's like, a programming language. Or is it a
       scripting language? All is revealed in this thrilling horror spoof
       of a documentary.
       <line>PHP solves all my web problems</line>
      <rating type="thumbs">7</rating>
      <rating type="stars">5</rating>
  • Next we convert the xml content to SimpleXMLElement and access content of it:
    include 'example.php';
    $movies = new SimpleXMLElement($xmlstr);
    echo $movies->movie[0]->plot;

Modify SimpleXMLElement Object and save xml content to file

include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie[0]->plot;


Create Google Analytics Code for website

Add an account to your Analytics Account

You need to have edit permission to add accounts to an existing Google Analytics Account.

To create a new account level in an existing Google Analytics Account:

  1. Click Admin in the menu bar at the top of any page.
  2. From the dropdown in Account column, click Create new account.

Add a property

Properties are where you send data and set up reporting views Only users with edit permission can add a property to a Google Analytics account.

To set up a property:

  1. Click Admin in the menu bar at the top of any page.
  2. In the Account column, select the account from the dropdown that you want to add the property to.If you have a lot of accounts, use the search box to help you find the right one.
  3. In the dropdown in the Property column, click Create new property.

Facebook Integration

Basic Steps To Integrate Facebook


Steps to integrate with facebook:

  1. Step1: Before Integrate with facebook, we need to signin facebook, then go to link and create the Your Application. Facebook will create AppID and AppSecret to identify the your application. We will use these informations to integrate login, like, share, comments…and manage theme
  2. Step2: Go to link to get code for each features integrated. Below are basic template code for integrate like, share and comment:
    • Load Facebook javascript base on AppID
        window.fbAsyncInit = function() {
            appId      : '1471852209797861',
            xfbml      : true,
            version    : 'v2.4'
        (function(d, s, id){
           var js, fjs = d.getElementsByTagName(s)[0];
           if (d.getElementById(id)) {return;}
           js = d.createElement(s); = id;
           js.src = "//";
           fjs.parentNode.insertBefore(js, fjs);
         }(document, 'script', 'facebook-jssdk'));
    • Update template to display button like
    • update template to display button share simple:
      <div class="fb-share-button" data-href="<?php echo $_product->getProductUrl(); ?>" data-layout="button_count"></div>
    • update template to display comment box:
      <div class="fb-comments" data-href="<?php echo $_product->getProductUrl(); ?>" data-numposts="5"></div>
  3. Step3: Update layout display of buttons follow link

Facebook Fanpage Box

Go to link to config and create HTML code:

<div class="fb-page" data-href="" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="" class="fb-xfbml-parse-ignore"><a href="">Shop Babies VN</a></blockquote></div>

⇒ In case you have created other facebook integration, you don't need to add javascript code which generated by generate tool above

Facebook share Custom


  1. Step1: Create Open Graph TagFacebook Crawler will use internal heuristics to make a best guess about the title, description, and preview image for your content. So we need to check the share on real website for facebook crawl the data exactly
  2. Step2: Go to link and enter the link of your website to check Open Graph Tag → we need fix all errors when debug with this tool. With old pages,facebook has cached informations on this page, so the facebook will not recognize the Open Graph Tag update with new image. Therefore, we must use debug tools to refresh these caches → Fix error can't comment and share missing the image(Click Fetch New Scrape Information 3 times to get new information). Or wait patiently for every 30 days to ensure the properties are up to date as it says in documentation

Manage Facebook Comments(moderation tool)

php/examplecodes.txt · Last modified: 2022/10/29 16:15 by