Php for beginners — Part2

LORY
4 min readAug 29, 2020

--

datetime

To string format

$dt_str=”2021–08–21 10:30:20";

echo (date(“Y-m-d H:i:s”, strtotime($dt_str)).”<br/>”);

echo (date(“Y-m-d h:i:sa”, strtotime($dt_str)).”<br/>”);

echo (date(“l”, strtotime($dt_str)).”<br/>”); // day of week

Add days/months/hours

echo (date(‘Y-m-d H:i:s’, strtotime($dt_str. ‘ + 2 days’)).”<br>”);

echo (date(‘Y-m-d H:i:s’, strtotime($dt_str. ‘ + 3 hours’)).”<br>”);

echo (date(‘Y-m-d H:i:s’, strtotime($dt_str. ‘ — 40 minutes’)).”<br>”);

echo (date(‘Y-m-d H:i:s’, strtotime($dt_str. ‘ — 2 months’)).”<br>”);

Get Now datetime

$now = date(“Y-m-d H:i:s”);

get date or time

$dt = strtotime(“2020–01–29 16:30:11”);

//date time

echo (date(“Y-m-d”,$dt).’<br>’);

//time part

echo(date(“H:i:s”,$dt));

compare date

$d1 = new DateTime(‘2020–08–03 14:52:10’);

$d2 = new DateTime(‘2020–01–03 11:11:10’);

var_dump($d1 == $d2);

var_dump($d1 > $d2);

var_dump($d1 < $d2);

Unix timestamp

$datetime = new DateTime(“2020–08–01 14:20:32”);

echo $datetime->getTimestamp();

//or

echo(time())

Timezone

Get all timezones

$timezone_identifiers = DateTimeZone::listIdentifiers();

foreach($timezone_identifiers as $key => $list){

echo $list . “<br/>”;

}

Set timezone

date_default_timezone_set(‘Europe/London’);

$now = date(“Y-m-d H:i:s”);

echo($now.’<br>’);

date_default_timezone_set(‘Indian/Kerguelen’);

$now = date(“Y-m-d H:i:s”);

echo($now.’<br>’);

Php map/filter/reduce

$users = [

[ ‘id’ => 1, ‘name’ => ‘a’ ],

[ ‘id’ => 2, ‘name’ => ‘b’ ],

[ ‘id’ => 3, ‘name’ => ‘c’ ]

];

function getNames(array $users, $id_after)

{

$filtered = array_filter($users, function ($x) use ($id_after) {

return $x[‘id’] > $id_after;

});

return array_map(function ($x) { return $x[‘name’]; }, $filtered);

}

$res = getNames($users ,1);

echo (json_encode($res).’<br>’);

function sum_id($users){

$id_arr = array_map(function($x){return $x[‘id’];} ,$users);

return array_reduce($id_arr, function ($sum, $cur) {

return $sum+$cur;

});

}

echo (sum_id($users).’<br>’);

Include and require

Require :if file does not exist throw error

include : continue execute even file does not exist

HTTP

get http GET parameter

$_GET[“name”]

get http POST parameter

$_POST[“name”]

get http POST json body

$json = file_get_contents(‘php://input’);

$data = json_decode($json);

upload file

if ($_FILES[‘uploadedfile’][‘error’] == UPLOAD_ERR_OK

&& is_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’])) {

echo file_get_contents($_FILES[‘uploadedfile’][‘tmp_name’]);

}

get client ip address

$ip = $_SERVER[‘HTTP_CLIENT_IP’] ? $_SERVER[‘HTTP_CLIENT_IP’] : ($_SERVER[‘HTTP_X_FORWARDED_FOR’] ? $_SERVER[‘HTTP_X_FORWARDED_FOR’] : $_SERVER[‘REMOTE_ADDR’]);

echo ($ip);

server variables

echo(json_encode($_SERVER));.

‘SERVER_ADDR’:The IP address of the server

‘REQUEST_METHOD’:GET/POST/PUT/DELETE

‘REQUEST_TIME’:timestamp when request hit server

‘QUERY_STRING’

‘HTTP_ACCEPT’

‘HTTP_ACCEPT_ENCODING’

‘HTTP_HOST’:full content of the post

‘HTTP_USER_AGENT’

‘HTTPS’: if this request using https

‘REMOTE_ADDR’:ip address of request pc

‘REMOTE_HOST’:host name of request pc

‘REMOTE_PORT’:client pc port

‘SERVER_PORT’

Get cookie

$_COOKIE[$cookie_name]

File/Folder

Read

//read all content

Readfile(‘sample.txt’)

//open then readall

$myfile = fopen(“test.txt”, “r”) or die(“Unable to open file!”);

echo fread($myfile,filesize(“test.txt”));

fclose($myfile);

//read by line

$myfile = fopen(“test.txt”, “r”) or die(“Unable to open file!”);

while(!feof($myfile)) {

echo fgets($myfile) . “<br>”;

}

fclose($myfile);

//read by char

$myfile = fopen(“test.txt”, “r”) or die(“Unable to open file!”);

while(!feof($myfile)) {

echo fgetc($myfile);

}

fclose($myfile);

Write

$myfile = fopen(“test1.txt”, “w”) or die(“Unable to open file!”);

$txt = “abc\n”;

fwrite($myfile, $txt);

$txt = “123\n”;

if (file_exists($myfile)) {

echo “Sorry, file already exists.”;

return;

}

fwrite($myfile, $txt);

fclose($myfile);

get current directory

echo (getcwd());

get directory file/folders

$res = scandir(‘/home’);

echo(json_encode($res));

Other useful methods

basename ($path) get filename

fseek() Seeks in an open file

fgetcsv() Returns a line from an open CSV file

file() Reads a file into an array

fileatime() Returns the last access time of a file

file_exists() Checks whether or not a file or directory exists

filectime() Returns the last change time of a file

filemtime() Returns the last modification time of a file

touch() Sets access and modification time of a file

unlink() Deletes a file

fileowner() Returns the user ID (owner) of a file

fileperms() Returns the file’s permissions

filesize() Returns the file size

filetype() Returns the file type

is_dir() Checks whether a file is a directory

is_file() Checks whether a file is a regular file

is_readable() Checks whether a file is readable

is_uploaded_file() Checks whether a file was uploaded via HTTP POST

is_writable() Checks whether a file is writable

stat() Returns information about a file

Object Oriented

Class

class Person {

//like most OO languages ,php support private,protected,public

// Properties

public $name;

public $id;

//constructor

function __construct($name) {

$this->name = $name;

}

// Methods

protected function set_name($name) {

$this->name = $name;

}

public function get_name() {

return $this->name;

}

function __destruct() {

echo “this method will be called when script is stopped or exited”;

}

}

Inheritance

class student extends person {

}

Abstract Class

abstract class parent {

abstract public function someMethod1();

abstract public function someMethod2($param1, $param2);

abstract public function someMethod3() : string;

}

class child: parent{

public function someMethod1(){…}

public function someMethod2($param1, $param2){…}

public function someMethod3() : string{…}

}

Interface

interface InterfaceName {

public function someMethod1();

public function someMethod2($param1, $param2);

public function someMethod3() : string;

}

class someClass: implements InterfaceName{

public function someMethod1(){…}

public function someMethod2($param1, $param2){…}

public function someMethod3() : string{…}

}

static

class sample{

public static function staticMethod(){

echo (“static method <br>”);

}

public static $staticProp = “abcd1234”;

}

sample::staticMethod();

echo(sample::$staticProp.”<br>”);

Trait

trait printMsg1 {

public function msg() {

echo “msg from trait1 “;

}

}

trait printMsg2 {

public function msg() {

echo “msg from trait2 “;

}

}

class Welcome {

use printMsg1;

//uncomment to raise error because trait method conflict

//use PrintMsg2;

// uncomment , class will override trait implementation

//public function msg(){

// echo (“msg from class”);

//}

}

$obj = new Welcome();

$obj->msg();

namespace

<?php

namespace namespace1;

class c1{

public static function print1(){

echo (“namespace1 function<br/>”);

}

}

?>

<?php

namespace namespace1\sub;

class c11{

public static function print1sub(){

echo (“namespace1 sub function<br/>”);

}

}

?>

<?php

namespace namespace2;

class c2{

public static function print2(){

echo (“namespace2 function<br/>”);

}

}

?>

<?php

use namespace1 as ns1;

ns1\c1::print1();

ns1\sub\c11::print1sub();

use namespace2 as ns2;

ns2\c2::print2();

?>

Error/Exception

log errors into error file

config : ‘error_log’ = some ‘path’ , log_errors=’1’

method : error_log(‘some error’);

Exception

getFile() : path of where exception thrown

getCode(): code that thrown exception

getLine(): line of code where exception thrown

getMessage(): exception description

getPrevious(): previous exception

getTraceAsString()/getTrace(): call stack

--

--

LORY
LORY

Written by LORY

A channel which focusing on developer growth and self improvement

No responses yet