<<TableOfContents(2)>>

= PHP =
PHP is a popular general-purpose scripting language that is especially suited to web development.
 * http://www.php.net/

== Console hello world ==
{{{#!highlight sh
php php_echo.php
chmod 755 php_echo.php 
./php_echo.php
}}}

{{{#!highlight php
#!/usr/bin/php
<?php
echo "Hello world";
?>
}}}

== syslog ==
Generate a system log message
{{{#!highlight php
<?php
// levels LOG_EMERG LOG_ALERT LOG_CRIT LOG_ERR	LOG_WARNING LOG_NOTICE	LOG_INFO LOG_DEBUG 
syslog(LOG_INFO,'Hello here'); // In Slackware by default logs the message to /var/log/messages
?>
}}}

== 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 (
    "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("first", 5 => "second", "third")
);

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

== array_push ==
Push one or more elements onto the end of array
{{{#!highlight php
<?php
$array[] = $var; // push $var into $array
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
?>
}}}

== count ==
Count all elements in an array, or something in an object
{{{#!highlight php
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a); // $result == 3
}}}

== intval ==
Get the integer value of a variable
{{{#!highlight php
<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
?>
}}}

== sprintf ==
Return a formatted string
{{{#!highlight php
<?php
echo sprintf('There are %d monkeys in the %s', 5, 'tree');
?>
}}}

== str_replace ==
Replace all occurrences of the search string with the replacement string
{{{#!highlight php
<?php
// Returns <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
?>
}}}

== Class ==
{{{#!highlight php
<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}
class Bar extends Foo
{
    public function fooStatic() {
        return parent::$my_static;
    }
}

class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

class MyClass
{
    const CONSTANT = 'constant value';

    function showConstant() {
        echo  self::CONSTANT . "\n";
    }
}

class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

?>
}}}

== Predefined variables ==
 * $GLOBALS
 * $_SERVER
 * $_GET
 * $_POST
 * $_COOKIE
 * $_FILES
 * $_ENV
 * $_REQUEST
 * $_SESSION

== foreach ==
{{{#!highlight php
<?php
$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
{{{#!highlight php
<?php
$p="p1 p2 p3 p4 p5 p6";
$ps = explode(" ", $p);
echo $pieces[0]; // p1
echo $pieces[1]; // p2
echo $pieces[3]; // p4
?>
}}}

== preg_split ==
Split the given string by a regular expression
{{{#!highlight php
<?php
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords); // will output the three word
?>
}}}

== file_get_contents ==
Reads entire file into a string
{{{#!highlight php
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
$file = file_get_contents('./people.txt', true);
?>
}}}

== DOMDocumentDOMDocument::loadXML ==
Load XML from a string
{{{#!highlight php
<?php
$doc = DOMDOcument::loadXML( file_get_contents( $base . '/sitemap.xml' ) );
$elements = $doc->getElementsByTagName('loc');
?>
}}}

== CORS (cross origin resource sharing) ==
=== read.example.org/index.php ===
{{{#!highlight php
<?php
header("Content-type:application/json");
header("Cache-Control: no-cache");
header("Pragma: no-cache"); 
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']  ); 
header("Access-Control-Allow-Credentials: true");
session_start();
$user = $_SESSION["user"];

echo("{\"key\":\"readData\" , \"user\": \"" . $user . "\" }");
?>
}}}

=== auth.example.org/index.php ===
{{{#!highlight php
<?php
header("Content-type:application/json");
header("Cache-Control: no-cache");
header("Pragma: no-cache"); 
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");

session_set_cookie_params(0, '/', '.example.org');
session_start(); 

$_SESSION["user"] = "userx " .  time();

echo("{\"key\":\"authData\"}");
?>

}}}

===  app.example.org/index.html ===
{{{#!highlight html
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<script>
$(document).ready(function(){
  console.log('Iooo');

  $.ajax({
  url: "http://auth.example.org/",
  xhrFields: { withCredentials: true  },
  success:  function(data, textStatus,jqXHR ){ $("#auth").text(data.key); },
  error: function( jqXHR, textStatus, errorThrown ){console.log(textStatus);}
  });

  $.ajax({
  url: "http://read.example.org/",
  xhrFields: {withCredentials: true},
  success: function(data,textStatus,jqXHR){ $("#read").text(data.key + ' ' + data.user  ); },
  error: function( jqXHR, textStatus, errorThrown ){console.log(textStatus);}
  });

});

</script>
</head>
<body>
<p id="auth"></p>
<p id="read"></p>
</body>
</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 ==
{{{#!highlight sh
# enable line /etc/httpd/httpd.conf 
sed -i 's/#Include \/etc\/httpd\/mod_php.conf/Include \/etc\/httpd\/mod_php.conf/g' httpd.conf

#update mod_php.conf to point to the right path of libphp5.so
LoadModule php5_module /usr/lib64/httpd/modules/libphp5.so
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>
#restart httpd/apache
sh /etc/rc.d/rc.httpd restart
}}}

=== /var/www/htdocs/teste.php ===
{{{#!highlight php
<?php 
phpinfo();  
echo "aaa"; 
?>
}}}
 * http://localhost/teste.php

=== /var/www/htdocs/log.php ===
{{{#!highlight php
<?php
// In Slackware by default logs the message to /var/log/messages
syslog(LOG_INFO,$_GET['msg']); 
?>
}}}
 * http://localhost/log.php?msg=Test%20message%20!!!

== Current date ==
{{{#!highlight php
<?php
//$today = date("Y-m-d H:i:s");
$today = gmdate("Y-m-d H:i:s");
echo php_uname() . " " . $today;
?>
}}}