User Tools

Site Tools


php:php

PHP code

Create PHP simple code and run

Create helloworld.php

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

Create phpinfo.php

<?php
  phpinfo();
?>

Run PHP code

  • linux:
    php helloworld.php
  • windows:
    c:\Program Files (x86)\PHP\php.exe helloworld.php

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:

  • default production [/etc/php.ini]:
    error_reporting = E_ALL & ~E_DEPRECATED
    display_errors = Off
    display_startup_errors = Off
    track_errors = Off
  • debug: [/etc/php.ini]
    error_reporting = E_ALL
    display_errors = On
    display_startup_errors = On
    track_errors = On
  • Explain config:display_errors = On ⇒ Allow display debug information in front end

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

  • in php-fpm.conf
    [global]
    error_log = /var/log/php-fpm.log
    ;log_level = notice
    [www]
    catch_workers_output = yes
  • in php.ini:
    display_errors = On ⇒ Allow display debug information in front end

Config turn on/off log in httpd:

  • [/etc/httpd/conf.d/php.conf]
    php_flag  display_errors        on
    php_value error_reporting       2039
  • Turn on in PHP code for debugging:
    error_reporting(E_ALL & ~E_NOTICE);
    if (!ini_get('display_errors')) {
        ini_set('display_errors', '1');
    }
  • Turn error log in httpd.conf
    ErrorLog "logs/error_log"
    LogLevel error

Config in web server to display error log

  • in nginx
    ###demo.vn
    server {
        listen       80;
        server_name  demo.vn www.demo.vn;
        root   /data/www/gamebai/demo;
    
        index index.html index.htm index.php;
        fastcgi_index  index.php;
    
        access_log /gb/nginx/logs/demo.access_log;
        error_log /gb/nginx/logs/demo.error_log;
    
        error_page  404              /404.html;
        error_page 500 502 503 504  /50x.html;
    
        location ~* "^.+\.(js|ico|gif|jpg|png|css|swf|htc|xml|bmp)$" {
            access_log  off;
            expires     30d;
        }
        location ~ \.php$ {
          fastcgi_pass   127.0.0.1:9000;
          fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
          include        fastcgi_params;
        }
    }

    ⇒ error log: error_log /gb/nginx/logs/demo.error_log;

  • in apache
    <VirtualHost *:80>
      DocumentRoot "D:/web/gamebai/demo"
      ServerName demo.vn
      DirectoryIndex index.php index.html index.htm
      <Directory D:/web/gamebai/demo>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order Deny,Allow
        Allow from all
      </Directory>  
      ErrorLog "logs/demo-error.log"
      CustomLog "logs/demo-access.log" common
    </VirtualHost>

    ⇒ error log: ErrorLog “logs/demo-error.log”

Debug with php code

  • Debug with print
    print(variable_name)
  • Debug with firebug
    • Config addon firebug in firefox: enable console pannel and net pannel
  • var_dump
    echo "<pre>";var_dump(debug_backtrace());echo "</pre>";

    ⇒ Print name of class for checking their functions

  • using try catch to get error and write to log:
        try{
     
        }
        catch(Exception $e){
            echo $e->getMessage();
        }
    ?>

Debug with xdebug

Debug with Javascript

  • Debug with Internet Explorer: Turn on Debug Mode in Internet Options for debugging code javascript error
  • Debug in Chrome: Using Developer Tools for debugging Javascript with break points

PHPUnit

Install PHPUnit

  • Install as binary
    wget -O phpunit https://phar.phpunit.de/phpunit-5.phar
    chmod +x phpunit
    ./phpunit --version
  • Install with composer:
    composer require --dev phpunit/phpunit ^5
    ./vendor/bin/phpunit --version

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

  • standard tags:
     <?php ?>
  • short tags:
    <? ?>
  • ASP tags:
    <% %>
  • script tags:
    <SCRIPT LANGUAGE="php"> </SCRIPT>

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

  • Bring the global variable into local scope with the global keyword:
    function eat_fruit($fruit) {
       global $chew_count;
     
       for ($i = $chew_count; $i > 0; $i--) {
         ...
       }
    }
  • Or reference it directly in $GLOBALS:
    function eat_fruit($fruit) {
       for ($i = $GLOBALS['chew_count']; $i > 0; $i--) {
         ...
       }
    }

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

  • Default value
    function wrap_html_tag($string, $tag = 'b') {
      $string = "<$tag>$string</$tag>";
      return $string;
    }
    $string = 'I am some HTML';
    wrap_html_tag($string);
    print "$string\n";
    $string = wrap_html_tag($string);
    print "$string\n";

    Out put:

    I am some HTML
    <b>I am some HTML</b>
  • reference value
    function wrap_html_tag(&$string, $tag = 'b') {
      $string = "<$tag>$string</$tag>";
      return $string;
    }
    $string = 'I am some HTML';
    wrap_html_tag($string);
    echo $string;

    Out put:

    <b>I am some HTML</b>

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

  • Cookies are small amounts of data stored by the user's browser after a request from a server or script
    • the maximum number of cookies from a host that can be stored by a browser is 20
    • and the maximum cookie size is 4KB
    • Cookies consist of a name, value, expiry date, host and path information, and they end up to the user because they are send from the server thru an HTTP header
  • There are 3 ways a PHP script can access the cookie:
    • Using the environmental variable “$HTTP-COOKIE” which holds all cookie names and values
    • In a global variable “$cookie_name” (replace with the name, of course)
    • Or in the global array variable “HTTP_COOKIE_VARS[“cookie_name”]”:Example:
      print $HTTP_COOKIE; //outputs "visits=23"
      print getenv("HTTP_COOKIER"); //outputs "visits=23"
      print $visits; //outputs "23"
      print $HTTP_COOKIE_VARS[visits]; //outputs "23"
  • To set a cookie with PHP, you can use the “header()” function, or the “setcookie()” function:
    //don't output anything before this
    header("visits=23; expires=Friday, 20-Aug-04 03:27:21 GMT; path=/; domain=softwareprojects.org");
    setcookie("hits", 23, time() + 3600, "/","softwareprojects.org", 0); //notice this last extra argument
  • Deleting cookies is also very easy, you should set the cookie you want to delete a date that has already expired.
    setcookie("visits", 23, time(), 60, "/", "softwareprojects.org", 0)

PHP Session

Understand about PHP Session

  • The difference between sessions and cookies is that a session can hold multiple variables, and you don't have to set cookies for every variable.
  • By default, the session data is stored in a cookie with an expiry date of zero, which means that the session only remains active as long as the browser. When you close the browser, all the stored information is lost. You can modify this behavior by changing the “session.cookie_lifetime” setting in “php.ini” from zero to whatever you want the cookie lifetime to be.
  • PHP uses several functions to deal with sessions. Before you start the actual work with sessions, you must explicitly start a session with “session_start()”

get, set and remove session variable

  • Set value session variable
    session_start();
    if(isset($stored_var))//if(session_is_registered("stored_var"))
    {
      print $stored_var; //this will not be displayed the first time you load the page, because you haven't registered the variable yet!
    }
    else
    {
      $stored_var = "Hello from a stored variable!";
      session_register("stored_var"); //don't do this: session_register($session_var)
    }
  • Remove the registered variable
    session_start();
    session_register("test");
    $test = 12;
    session_unset(); //$test is destroyed
    session_destroy();
    print $test; //outputs nothing

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;
}
php/php.txt · Last modified: 2022/10/29 16:15 by 127.0.0.1