PHP - atabegruslan/Notes GitHub Wiki

PHP Knowhows

Class

Composer

Setup

https://github.com/atabegruslan/Notes/wiki/Setup-developers-Ubuntu-computer#composer

Usage

Autoload

  1. https://viblo.asia/p/php-autoloading-psr4-and-composer-V3m5Wy0QZO7
  2. https://github.com/atabegruslan/Notes/blob/main/notes/php/composer/autoload.pdf

Debug

Live debug.

Limit by IP Address

Use: https://www.ip2location.com/

if ('14.161.26.170' == $_SERVER['REMOTE_ADDR'])
{
     // Debug code
}

Dump out debug messages

ob_flush();
ob_start();
var_dump($session->get('auto_extended', 'default'));
file_put_contents("/home/genbrugsauktion/public_html/filename" . date("YFd_H-i-s") . ".txt", ob_get_flush());
$myfile = fopen("C:/Users/Victor/Desktop/filename" . date("YFd_H-i-s") . rand(1, 99999) . ".txt", "w");
fwrite($myfile, debug_backtrace()[0]['file'] . ' | ' . debug_backtrace()[0]['line']);
fclose($myfile);
echo '<pre>';
print_r($results);
echo '</pre>';
die();
file_put_contents("/home/ruslan/Desktop/filename" . date("YFd_H-i-s") . ".txt", serialize($validData));
$output = "|   |   |   |   |\n|---|---|---|---|\n";
foreach (debug_backtrace() as $stack)
{
  $output .= ' | ' . $stack['file'] . ' | ' . $stack['class'] . ' | ' . $stack['function'] . ' | ' . $stack['line'] . ' | ' . "\n";
}
var_dump($output);
file_put_contents("C:/Users/Victor/Desktop/stacktrace" . date("YFd_H-i-s") . rand(1, 99999) . ".md", $output);

https://github.com/atabegruslan/Notes/tree/main/notes/php/print

Force out a Guzzle Request Exception

throw new \GuzzleHttp\Exception\RequestException('test', new \GuzzleHttp\Psr7\Request('dummy', '', [], null, []));

https://www.howtobuildsoftware.com/index.php/how-do/zlV/guzzle-how-to-create-own-requestexception-in-guzzle

Get various info

Get base URL:

<?php
echo '<pre>';
print_r($_SERVER);
echo '</pre>';

echo '<pre>';
$baseUrl = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$urlParts = explode('/', $baseUrl);
array_pop($urlParts);
$baseUrl = implode('/', $urlParts);
$baseUrl .= '/';
echo $baseUrl;
echo '</pre>';

Get PHP's info: phpinfo();

A file, folder or link's info: print_r(lstat('C:\Users\somefile.txt'));

Reading HTTP request body from a JSON POST in PHP

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

Make file from binary

$pdf_base64 = "binary_string_inside.txt";
//Get File content from txt file
$pdf_base64_handler = fopen($pdf_base64,'r');
$pdf_content = fread($pdf_base64_handler, filesize($pdf_base64));
fclose ($pdf_base64_handler);
//Decode pdf content
$pdf_decoded = base64_decode($pdf_content);
//Write data back to pdf file
$pdf = fopen('document.pdf','w');
fwrite ($pdf, $pdf_decoded);

Dates and Times

Timezone standards

Functions

Example of DateTime usage:

misc others

Sessions, Tokens, Auth

Concurrency

array_filter

Make CSV and download directly

Rounding numbers

Encrypting passwords

function encrypt($password, $encryptionKey)
{
    $iv    = openssl_random_pseudo_bytes(openssl_cipher_iv_length("AES-256-CBC"));
    $crypt = openssl_encrypt($password, "AES-256-CBC", $encryptionKey, OPENSSL_RAW_DATA, $iv);

    return base64_encode($iv . $crypt);
}

function decrypt($password, $encryptionKey)
{
    $decodedPassword = base64_decode($password);

    $ivlen = openssl_cipher_iv_length("AES-256-CBC");
    $iv    = substr($decodedPassword, 0, $ivlen);
    $crypt = substr($decodedPassword, $ivlen);

    return openssl_decrypt($crypt, "AES-256-CBC", $encryptionKey, OPENSSL_RAW_DATA, $iv);
}

$encryptionKey is the secret in the config file

Progress bar

Versions

Errors

Throwable interface (PHP 7.2.0)

    Error class
      ArithmeticError
        DivisionByZeroError
      AssertionError
      ParseError
      TypeError
        ArgumentCountError
		
    Exception class
      ClosedGeneratorException
      DOMException
      ErrorException
      IntlException
      LogicException
        BadFunctionCallException
          BadMethodCallException
        DomainException
        InvalidArgumentException
        LengthException
        OutOfRangeException
      PharException
      ReflectionException
      RuntimeException
        OutOfBoundsException
        OverflowException
        PDOException
        RangeException
        UnderflowException
        UnexpectedValueException
      SodiumException

PHP 5 Error Levels

https://www.tutorialrepublic.com/php-reference/php-error-levels.php

There are various types of errors in PHP but it contains basically four main type of errors.

Parse error or Syntax Error: It is the type of error done by the programmer in the source code of the program. The syntax error is caught by the compiler. After fixing the syntax error the compiler compile the code and execute it. Parse errors can be caused dues to unclosed quotes, missing or Extra parentheses, Unclosed braces, Missing semicolon etc Fatal Error: It is the type of error where PHP compiler understand the PHP code but it recognizes an undeclared function. This means that function is called without the definition of function. Warning Errors : The main reason of warning errors are including a missing file. This means that the PHP function call the missing file. Notice Error: It is similar to warning error. It means that the program contains something wrong but it allows the execution of script.

PHP error constants and their description :

E_ERROR : A fatal error that causes script termination
E_WARNING : Run-time warning that does not cause script termination
E_PARSE : Compile time parse error.
E_NOTICE : Run time notice caused due to error in code
E_CORE_ERROR : Fatal errors that occur during PHP’s initial startup (installation)
E_CORE_WARNING : Warnings that occur during PHP’s initial startup
E_COMPILE_ERROR : Fatal compile-time errors indication problem with script.
E_USER_ERROR : User-generated error message.
E_USER_WARNING : User-generated warning message.
E_USER_NOTICE : User-generated notice message.
E_STRICT : Run-time notices.
E_RECOVERABLE_ERROR : Catchable fatal error indicating a dangerous error
E_DEPRECATED : Run-time notices.

https://www.quora.com/What-are-the-different-types-of-errors-in-PHP

PHP Global Variables - Superglobals

$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION

Magic Methods

__construct()
__destruct()
__call()
__callStatic()
__get()
__set()
__isset()
__unset()
__sleep()
__wakeup()
__toString()
__invoke()
__set_state()
__clone()
__debugInfo()

Magic constants

__LINE__	The current line number of the file.
__FILE__	The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__	The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__	The function name.
__CLASS__	The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__	The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__	The class method name.
__NAMESPACE__	The name of the current namespace.
ClassName::class	The fully qualified class name. See also ::class.
⚠️ **GitHub.com Fallback** ⚠️