Table of Contents

PHP code

PHP Editor:

Create PHP simple code and run

Create helloworld.php

<?php
  print "Hello Web!";
?>

Create phpinfo.php

<?php
  phpinfo();
?>

Run PHP code

How to debug in PHP and Javascript

Config debug mode in PHP

check http://192.168.2.11/info.php(To run with debug mode, remove option –disable-debug when build PHP from source). In php.ini, we need turn on log_errors = On for production and development and where to save log file

error_log = /var/log/php_errors.log

To be can save log to php_errors.log, you must change own to allow http write log:

chown www.www /var/log/php_errors.log

Config turn on/off debug log in php:

Config turn on debug log in ngix with php-fpm backend:

Config turn on/off log in httpd:

Config in web server to display error log

Debug with php code

Debug with xdebug

Refer: Debug PHP with xdebug

Debug with Javascript

PHPUnit

refer: https://phpunit.de/getting-started/phpunit-5.html

Install PHPUnit

Run PHPUnit

PHP Slow Log Config

Config Slow Log in php-fpm

request_slowlog_timeout = 5s
slowlog = /var/log/php-fpm/slowlog-site.log

Config Slow Log for php

Basic Syntaxs

PHP tags

The standard and the script tags are guaranteed to work under any configuration, the other tags be enabled in your “php.ini”

Comment in PHP code

//your commment
#your commment
/*your commment
*/

php with html

write code php with <?php -and- ?> tags

<html>
 <title>HTML with PHP</title>
 <body>
 <h1>My Example</h1>
 
<?php
 //your php code here
?>
<b>Here is some more HTML</b>
 
<?php
 //more php code
?>
</body>
</html>

output HTML with PHP by using PRINT or ECHO

<?php 
  Echo "<html>";
  Echo "<title>HTML with PHP</title>";
  Echo "<b>My Example</b>";
  //your php code here
  Print "<i>Print works too!</i>"; 
?>

variable and constant in PHP

set value for variable

if (! isset($cars)) { $cars = $default_cars; }
$defaults = array('emperors'  => array('Rudolf II','Caligula'),
                  'vegetable' => 'celery',
                  'acres'     => 15);

static variable

If you want a local variable to retain its value between invocations of a function, Declare the variable as static:

function track_times_called( ) {
    static $i = 0;
    $i++;
    return $i;
}

global variable

Magic constants

__LINE__ 	The current line number of the file.
__FILE__ 	The full path and filename of the file.
__DIR__ 	The directory of the file.
__FUNCTION__ 	The function name.
__CLASS__ 	The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__METHOD__ 	The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ 	The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0). 
DIRECTORY_SEPARATOR
	"..".DIRECTORY_SEPARATOR."foo" => windows: "..\foo" and linux: "../foo"

Function in PHP

simple function

function add($a, $b) {
  return $a + $b;
}
$total = add(2, 2);

Setting Default Value and Reference variable in function

include code with require and include

require and include. The main difference is that attempting to require a nonexistent file is a fatal error, while attempting to include such a file produces a warning but does not stop script execution.

<? include 'header.html'; ?>
content
<? include 'footer.html'; ?>
 
<? require 'codelib.inc'; ?>
mysub(  );// defined in codelib.inc

PHP Cookies and session

In order to store the contents of a shopping cart while the user is browsing your site, There are two easy ways: you either use cookies or sessions.

PHP cookies

Understand about cookies

PHP Session

Understand about PHP Session

get, set and remove session variable

PHP connect Database

if(!mysql_connect("localhost", "bob", "secret")) //tries to connect to the database server
die("Unable to connect to the database server!"); //terminates the script, and outputs the error

PHP mysql

'connect'            => 'mysql_connect',
'pconnect'           => 'mysql_pconnect',
'select_db'          => 'mysql_select_db',
'query'              => 'mysql_query',
'query_unbuffered'   => 'mysql_unbuffered_query',
'fetch_row'          => 'mysql_fetch_row',
'fetch_array'        => 'mysql_fetch_array',
'fetch_field'        => 'mysql_fetch_field',
'free_result'        => 'mysql_free_result',
'data_seek'          => 'mysql_data_seek',
'error'              => 'mysql_error',
'errno'              => 'mysql_errno',
'affected_rows'      => 'mysql_affected_rows',
'num_rows'           => 'mysql_num_rows',
'num_fields'         => 'mysql_num_fields',
'field_name'         => 'mysql_field_name',
'insert_id'          => 'mysql_insert_id',
'escape_string'      => 'mysql_escape_string',
'real_escape_string' => 'mysql_real_escape_string',
'close'              => 'mysql_close',
'client_encoding'    => 'mysql_client_encoding',
'ping'               => 'mysql_ping',

PHP mysqli

'connect'            => 'mysqli_real_connect',
'pconnect'           => 'mysqli_real_connect', // mysqli doesn't support persistent connections THANK YOU!
'select_db'          => 'mysqli_select_db',
'query'              => 'mysqli_query',
'query_unbuffered'   => 'mysqli_unbuffered_query',
'fetch_row'          => 'mysqli_fetch_row',
'fetch_array'        => 'mysqli_fetch_array',
'fetch_field'        => 'mysqli_fetch_field',
'free_result'        => 'mysqli_free_result',
'data_seek'          => 'mysqli_data_seek',
'error'              => 'mysqli_error',
'errno'              => 'mysqli_errno',
'affected_rows'      => 'mysqli_affected_rows',
'num_rows'           => 'mysqli_num_rows',
'num_fields'         => 'mysqli_num_fields',
'field_name'         => 'mysqli_field_tell',
'insert_id'          => 'mysqli_insert_id',
'escape_string'      => 'mysqli_real_escape_string',
'real_escape_string' => 'mysqli_real_escape_string',
'close'              => 'mysqli_close',
'client_encoding'    => 'mysqli_client_encoding',
'ping'               => 'mysqli_ping',

Convert from mysql to mysqli

Using tool: https://github.com/philip/MySQLConverterTool

php MySQLConverterTool-master/cli.php -f changeusername.php > changeusername_new.php

And Modify some missing in tool:

mysqli_connect("127.0.0.1", "forum_ttb", "xxxxxxxxxx"));

to

=> mysqli_connect("127.0.0.1", "forum_ttb", "xxxxxxxxxx","forum_ttb"));

PHP curl

<?php
function curl_post($url, $vars=array(), $second=10)
{
    try{
        $ch = curl_init();
        if ($ch === false) {
            throw new Exception('failed to initialize');
        }
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if ($data === false) {
            throw new Exception(curl_error($ch), curl_errno($ch));
        }
        curl_close($ch);
    }catch(Exception $e){
        echo "Curl Error: " . $e->getCode . $e->getMessage();
    }
    if($data)
        return $data;
    else
        return false;
}