PHP

PHP is a popular general-purpose scripting language that is especially suited to web development.

http://www.php.net/

Console hello world

   1 #!/usr/bin/php
   2 <?php
   3 echo "Hello world";
   4 ?>

syslog

Generate a system log message

   1 <?php
   2 // levels LOG_EMERG LOG_ALERT LOG_CRIT LOG_ERR  LOG_WARNING LOG_NOTICE  LOG_INFO LOG_DEBUG 
   3 syslog(LOG_INFO,'Hello here'); // In Slackware by default logs the message to /var/log/messages
   4 ?>

Log levels and files in operative systems

OS

File

Logged levels

Slack64 14

/var/log/messages

INFO

Slack64 14

/var/log/syslog

WARNING ERR CRIT

CentOS 6.4

/var/log/messages

INFO WARNING ERR CRIT

Ubuntu 12.04 Precise

/var/log/syslog

DEBUG INFO WARNING ERR CRIT

Debian 7.0 Wheezy

/var/log/syslog

DEBUG INFO WARNING ERR CRIT

array

Create an array {{{!highlight php <?php $fruits = array (

);

$foo = array('bar' => 'baz'); echo "Hello {$foo['bar']}!"; // Hello baz! ?> }}}

array_push

Push one or more elements onto the end of array

   1 <?php
   2 $array[] = $var; // push $var into $array
   3 $stack = array("orange", "banana");
   4 array_push($stack, "apple", "raspberry");
   5 ?>

count

Count all elements in an array, or something in an object

   1 <?php
   2 $a[0] = 1;
   3 $a[1] = 3;
   4 $a[2] = 5;
   5 $result = count($a); // $result == 3
   6 

intval

Get the integer value of a variable

   1 <?php
   2 echo intval(42);                      // 42
   3 echo intval(4.2);                     // 4
   4 echo intval('42');                    // 42
   5 ?>

sprintf

Return a formatted string

   1 <?php
   2 echo sprintf('There are %d monkeys in the %s', 5, 'tree');
   3 ?>

str_replace

Replace all occurrences of the search string with the replacement string

   1 <?php
   2 // Returns <body text='black'>
   3 $bodytag = str_replace("%body%", "black", "<body text='%body%'>");
   4 ?>

Class

   1 <?php
   2 class SimpleClass
   3 {
   4     // property declaration
   5     public $var = 'a default value';
   6 
   7     // method declaration
   8     public function displayVar() {
   9         echo $this->var;
  10     }
  11 }
  12 
  13 class Foo
  14 {
  15     public static $my_static = 'foo';
  16 
  17     public function staticValue() {
  18         return self::$my_static;
  19     }
  20 }
  21 class Bar extends Foo
  22 {
  23     public function fooStatic() {
  24         return parent::$my_static;
  25     }
  26 }
  27 
  28 class Foo {
  29     public static function aStaticMethod() {
  30         // ...
  31     }
  32 }
  33 
  34 class MyClass
  35 {
  36     const CONSTANT = 'constant value';
  37 
  38     function showConstant() {
  39         echo  self::CONSTANT . "\n";
  40     }
  41 }
  42 
  43 class MyClass
  44 {
  45     public $public = 'Public';
  46     protected $protected = 'Protected';
  47     private $private = 'Private';
  48 
  49     function printHello()
  50     {
  51         echo $this->public;
  52         echo $this->protected;
  53         echo $this->private;
  54     }
  55 }
  56 
  57 ?>

Predefined variables

foreach

$listx = array(10,11,12);
foreach($listx as $itemx){
    print("Itemx: $itemx  ");
}

$listassocx = array('ten'=>10,'eleven'=>11,'twelve'=>12);

foreach($listxassocx as $keyx=>$valx){
    print("Itemx: $keyx: $valx  ");
}

explode

Split a string by string

   1 <?php
   2 $p="p1 p2 p3 p4 p5 p6";
   3 $ps = explode(" ", $p);
   4 echo $pieces[0]; // p1
   5 echo $pieces[1]; // p2
   6 echo $pieces[3]; // p4
   7 ?>

preg_split

Split the given string by a regular expression

   1 <?php
   2 $keywords = preg_split("/[\s,]+/", "hypertext language, programming");
   3 print_r($keywords); // will output the three word
   4 ?>

file_get_contents

Reads entire file into a string

   1 <?php
   2 $homepage = file_get_contents('http://www.example.com/');
   3 echo $homepage;
   4 $file = file_get_contents('./people.txt', true);
   5 ?>

DOMDocumentDOMDocument::loadXML

Load XML from a string

   1 <?php
   2 $doc = DOMDOcument::loadXML( file_get_contents( $base . '/sitemap.xml' ) );
   3 $elements = $doc->getElementsByTagName('loc');
   4 ?>

CORS (cross origin resource sharing)

read.example.org/index.php

   1 <?php
   2 header("Content-type:application/json");
   3 header("Cache-Control: no-cache");
   4 header("Pragma: no-cache"); 
   5 header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']  ); 
   6 header("Access-Control-Allow-Credentials: true");
   7 session_start();
   8 $user = $_SESSION["user"];
   9 
  10 echo("{\"key\":\"readData\" , \"user\": \"" . $user . "\" }");
  11 ?>

auth.example.org/index.php

   1 <?php
   2 header("Content-type:application/json");
   3 header("Cache-Control: no-cache");
   4 header("Pragma: no-cache"); 
   5 header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
   6 header("Access-Control-Allow-Credentials: true");
   7 
   8 session_set_cookie_params(0, '/', '.example.org');
   9 session_start(); 
  10 
  11 $_SESSION["user"] = "userx " .  time();
  12 
  13 echo("{\"key\":\"authData\"}");
  14 ?>

app.example.org/index.html

   1 <html>
   2 <head>
   3 <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
   4 
   5 <script>
   6 $(document).ready(function(){
   7   console.log('Iooo');
   8 
   9   $.ajax({
  10   url: "http://auth.example.org/",
  11   xhrFields: { withCredentials: true  },
  12   success:  function(data, textStatus,jqXHR ){ $("#auth").text(data.key); },
  13   error: function( jqXHR, textStatus, errorThrown ){console.log(textStatus);}
  14   });
  15 
  16   $.ajax({
  17   url: "http://read.example.org/",
  18   xhrFields: {withCredentials: true},
  19   success: function(data,textStatus,jqXHR){ $("#read").text(data.key + ' ' + data.user  ); },
  20   error: function( jqXHR, textStatus, errorThrown ){console.log(textStatus);}
  21   });
  22 
  23 });
  24 
  25 </script>
  26 </head>
  27 <body>
  28 <p id="auth"></p>
  29 <p id="read"></p>
  30 </body>
  31 </html>

vhosts

<VirtualHost *:80>
    ServerName app.example.org
    DocumentRoot "/var/www/htdocs/app.example.org"
    <Directory "/var/www/htdocs/app.example.org">
      Require local
      AllowOverride All
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName auth.example.org       
    DocumentRoot "/var/www/htdocs/auth.example.org"
    <Directory "/var/www/htdocs/auth.example.org">
      Require local
      AllowOverride All
    </Directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName read.example.org       
    DocumentRoot "/var/www/htdocs/read.example.org"
    <Directory "/var/www/htdocs/read.example.org">
      Require local
      AllowOverride All
    </Directory>
</VirtualHost>

Enable PHP in Slackware64

   1 # enable line /etc/httpd/httpd.conf 
   2 sed -i 's/#Include \/etc\/httpd\/mod_php.conf/Include \/etc\/httpd\/mod_php.conf/g' httpd.conf
   3 
   4 #update mod_php.conf to point to the right path of libphp5.so
   5 LoadModule php5_module /usr/lib64/httpd/modules/libphp5.so
   6 <FilesMatch \.php$>
   7     SetHandler application/x-httpd-php
   8 </FilesMatch>
   9 #restart httpd/apache
  10 sh /etc/rc.d/rc.httpd restart

/var/www/htdocs/teste.php

   1 <?php 
   2 phpinfo();  
   3 echo "aaa"; 
   4 ?>

/var/www/htdocs/log.php

   1 <?php
   2 // In Slackware by default logs the message to /var/log/messages
   3 syslog(LOG_INFO,$_GET['msg']); 
   4 ?>

Current date

   1 <?php
   2 //$today = date("Y-m-d H:i:s");
   3 $today = gmdate("Y-m-d H:i:s");
   4 echo php_uname() . " " . $today;
   5 ?>

PHP (last edited 2021-03-31 11:12:55 by localhost)