User Tools

Site Tools


php:examplecodes

PHP example codes

Basic Examples for reading and understanding code(testing)

func_get_args

<?php
 
function myfunction() {
	list($string) = func_get_args();
	print $string;
}
 
myfunction("Hello, World!");
 
?>

output:

Hello, World!

reference variable

  • Simple reference:
    <?php
    $a = 10;
    $b = &$a;
    $b++;
    print $a
    ?>

    output:

    11
  • Custom reference
    <?php
     
    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);
     
    $var++;
     
    print "1: $one, 2: $two, 3: $three";
     
    ?>

    output:

    1: 2, 2: 20, 3: 16

compare 2 values in the same type and value

<?php
$a = 2;
$b = '2';
if ($a == $b)
	print "$a == '$b'";
else
	print "not $a == '$b'";
if ($a === $b)
	print "\n$a === '$b'";
else
	print "\nnot $a === '$b'";
?>

global variable

<?php
 
$a = 20;
 
function myfunction($b) {
	$a = 30;
 
	global $a, $c;
	return $c = ($b + $a);
}
 
print myfunction(40) + $c;
 
?>

output:

120

Class and Object

<?php
 
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();
 
$obj->changeValue(20);
$obj->changeValue(10);
 
$obj->displayValues();
 
?>

output:

a: 30, b: 10

Send mail with PHP

php code

<?php
$subject = 'We Have Received Your Article';
$fromEmail = '[email protected]';
$fromName = 'shop babies.vn';
$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.
 
 
 
Regards,
Douglas Brown
EMAIL;
mail($toEmail,$subject,$message,"From: $fromEmail\n");
?>

understand php email

email log: /var/log/maillog

[/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 gmail-smtp-in.l.google.com[2607:f8b0:400e:c03::1a]:25: Network is unreachable
May 23 09:04:01 mail postfix/smtp[3190]: 12F4E40A83: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[74.125.25.26]: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 115.73.56.43] 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

<?php
$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();
    }
?>
<?php
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:

ruou-bau-da

Read XML with PHP

SimpleXMLElement

Read xml file to object SimpleXMLElement

refer: http://php.net/manual/en/function.simplexml-load-file.php

<?php
// 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');
 
    print_r($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:
    <?php
    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
    <movies>
     <movie>
      <title>PHP: Behind the Parser</title>
      <characters>
       <character>
        <name>Ms. Coder</name>
        <actor>Onlivia Actora</actor>
       </character>
       <character>
        <name>Mr. Coder</name>
        <actor>El Act&#211;r</actor>
       </character>
      </characters>
      <plot>
       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.
      </plot>
      <great-lines>
       <line>PHP solves all my web problems</line>
      </great-lines>
      <rating type="thumbs">7</rating>
      <rating type="stars">5</rating>
     </movie>
    </movies>
    XML;
    ?>
  • Next we convert the xml content to SimpleXMLElement and access content of it:
    <?php
    include 'example.php';
     
    $movies = new SimpleXMLElement($xmlstr);
     
    echo $movies->movie[0]->plot;
    ?>

Modify SimpleXMLElement Object and save xml content to file

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

DOM

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

refer:

Steps to integrate with facebook:

  1. Step1: Before Integrate with facebook, we need to signin facebook, then go to link https://developers.facebook.com/ 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 https://developers.facebook.com/docs/plugins?locale=vi_VN to get code for each features integrated. Below are basic template code for integrate like, share and comment:
    • Load Facebook javascript base on AppID
      <script>
        window.fbAsyncInit = function() {
          FB.init({
            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); js.id = id;
           js.src = "//connect.facebook.net/vi_VN/sdk.js";
           fjs.parentNode.insertBefore(js, fjs);
         }(document, 'script', 'facebook-jssdk'));
      </script>
    • Update template to display button like
      <div
        class="fb-like"
        data-share="false"
        data-width="450"
        data-show-faces="true">
      </div>
    • 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 https://developers.facebook.com/docs/plugins/like-button?locale=vi_VN#faqlayout

Facebook Fanpage Box

Go to link https://developers.facebook.com/docs/plugins/page-plugin to config and create HTML code:

<div class="fb-page" data-href="https://www.facebook.com/ShopBabiesVn/" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/ShopBabiesVn/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/ShopBabiesVn/">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

refer: https://developers.facebook.com/docs/sharing/web

  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 https://developers.facebook.com/tools/debug/ 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 https://developers.facebook.com/docs/plugins/like-button

Manage Facebook Comments(moderation tool)

php/examplecodes.txt · Last modified: 2018/08/31 23:44 by admin