Skip to content

Instantly share code, notes, and snippets.

@josanua
Last active December 13, 2024 07:53
Show Gist options
  • Select an option

  • Save josanua/b750c05bca2a3afcbb009442bb0ae15e to your computer and use it in GitHub Desktop.

Select an option

Save josanua/b750c05bca2a3afcbb009442bb0ae15e to your computer and use it in GitHub Desktop.
PHP Helper
<?php
PHP: Hypertext Preprocessor (PHP)
Server side programming language
// Code style
https://gist.github.com/jesseschalken/0f47a2b5a738ced9c845
// TODO: de citit
https://www.codementor.io/@veenitchauhan/basics-of-naming-conventions-for-php-developers-eliexmew6
// Here are some of the main differences between PHP 7 and PHP 8:
// 1 JIT (Just-In-Time) Compilation: PHP 8 introduces a new feature called JIT (Just-In-Time) compilation which can improve the performance of PHP code significantly. JIT compiles PHP code into machine code during runtime which can speed up the execution of PHP code.
// 2 Union Types: PHP 8 allows developers to specify more than one data type for function and method arguments, as well as return types. This feature is called union types and it helps to make code more expressive and easier to read.
// 3 Named Arguments: In PHP 8, developers can use named arguments to pass arguments to a function or method by name, instead of position. This makes it easier to understand the purpose of each argument and can reduce the risk of errors caused by passing arguments in the wrong order.
// 4 Attributes: Attributes (also known as annotations) were introduced in PHP 8 as a way to add metadata to classes, methods, properties, and function arguments. This can be used to document code or to provide additional information to IDEs and other development tools.
// 5 Nullsafe Operator: PHP 8 introduces the nullsafe operator ( ?->) which allows developers to safely access properties and methods of an object even if the object is null. This can help to reduce the amount of boilerplate code needed to handle null values.
// 6 Consistent Type Errors: In PHP 7, type errors were only thrown for scalar types (string, integer, float, boolean), but not for composite types (array, object, etc.). In PHP 8, type errors are consistently thrown for all types.
// 7 Match Expression: PHP 8 introduces the match expression (also known as a "switch without fallthrough") which is a more expressive and concise alternative to the traditional switch statement.
// ------------- work in CLI ------------- //
// Verify PHP Installation
php -v
// Execute the PHP Script
php hello.php
// Run the script with an argument
php hello.php CLI
// Execute a PHP Command Directly
php -r 'echo "Hello, CLI!\n";'
// Run a PHP Interactive Shell
php -a
// Display PHP Configuration
php -i
// Check PHP Syntax
php -l hello.php
// ------------- work data types ------------- //
/*
* https://www.w3schools.com/php/php_datatypes.asp
*/
//-> All data types
String
Integer
Float
Boolean
Array
Object // An object is a data type which stores data and information on how to process that data.
NULL // A variable of data type NULL is a variable that has no value assigned to it.
Resource
//-> Primitive data types
// In PHP, primitive data types (also known as scalar types) refer to the basic types of data that are built into the language.
// These data types represent the simplest forms of data and are not objects.
// PHP supports several primitive data types, each of which serves a specific purpose.
// Here's an overview of the primitive data types in PHP:
Integer
Float
String
Boolean
Null
Float example:
$x = 10.5;
$y = 2.4e3; // 2400
$z = 8E-5; // 0.00008
//-> Type Checking, check types
// PHP provides several functions to check the type of a variable:
is_int(); // Checks if a variable is an integer.
is_float(); // Checks if a variable is a float.
is_string(); // Checks if a variable is a string.
is_bool(); // Checks if a variable is a boolean.
is_null(); // Checks if a variable is null.
// Show types
// http://php.net/manual/en/ref.var.php
print_r( $type ); // Prints human-readable information about a variable
var_dump( $variable ); // Dumps information about a variable
var_dump( get_object_vars( objectName ) ); // Shows properties of object in detailing mode
var_dump( function name() ); // It's possible to check function return result
// To see if object exist in the indicated name class
var_dump( $objectName instanceof nameOfClass );
// Detect data vars
// How to solve the undefined variable/index/offset
// https://anto.online/code/how-to-solve-the-undefined-variable-index-offset-php-error/
!empty($arr['index_num']) // check if Index is empty
isset($arr['index_num']) // check if Index is not set
// Hide redundant or undesired error notices
// You can hide undefined variables, index, and offset notices by using the @ error control operator to hide them.
$var = @($_GET["optional_param"]);
// ------------- work Utils------------- //
echo phpinfo(); // info.php
echo phpversion();
echo getcwd(); // Gets the current working directory
// Find quick info
echo ($_SERVER['HTTP_HOST']) . "<br/>";
echo ($_SERVER['SCRIPT_FILENAME']) . "<br/>"; // Absolute path and filename
echo ($_SERVER['SERVER_ADDR']) . "<br/>";
echo $_SERVER['DOCUMENT_ROOT']; // Root to the file
echo $_SERVER['HTTP_REFERER']; // get find previous visited url
// superglobals, global variables
// https://www.php.net/manual/ro/language.variables.superglobals.php
$GLOBALS
$_SERVER // Server and execution environment information
$_GET
$_POST
$_FILES // HTTP File Upload variables, An associative array of items uploaded to the current script via the HTTP POST method.
$_COOKIE // HTTP Cookies, An associative array of variables passed to the current script via HTTP Cookies.
$_SESSION // Session variables
$_REQUEST // HTTP Request variables
$_ENV // Environment variables, An associative array of variables passed to the current script via the environment method.
// For find local path
echo ($_SERVER['SCRIPT_FILENAME']);
// include paths, include files
$_SERVER['SCRIPT_FILENAME'];
$_SERVER['DOCUMENT_ROOT']; // Document root $path = $_SERVER['DOCUMENT_ROOT'] . "/forum/index.php";
###### Coding Standards ######
https://www.php-fig.org/psr/
PSR - PHP Standard Recomendation
###### Debug, debuging ######
https://stackify.com/php-debugging-guide/
// info.php
<?php phpinfo(); ?>
// *** A combination of settings will get you the right levels of error logging.
// error_reporting sets the level of logging. E_NOTICE is useful during development since it will tell you about defects such as unassigned variables.
// display_errors tells PHP if and where to display error messages.
// display_startup_errors should only be used when debugging.
// log_errors and error_log work together to send errors to a log file. Do this in production rather than displaying them to end users.
// Write this code in .htaccess
# PHP error handling for development servers
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value docref_root 0
php_value docref_ext 0
php_value error_log /home/visitm/web/visitmoldova.travel/public_html/php-errors.log
php_value error_reporting -1
php_value log_errors_max_len 0
// write in source code directly
// config errors shows
https://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
https://www.php.net/manual/en/function.error-reporting.php
error_reporting( E_ALL ); // at the top
error_reporting( -1 ); // at the top of your script during dev to turn on all warnings, notices, etc in all versions of PHP
ini_set( 'display_errors', 1 );
ini_set( 'display_startup_errors', 1 );
set_error_handler( closeDay($merchantHandler) );
// For quick debug on server
error_reporting( E_ALL ); // at the top
ini_set( 'display_errors', 1 );
// get var info, data info
var_dump(); // Info about var
empty(); // Determine whether a variable is empty, Determină dacă o variabilă este vidă
print_r(); // View array, prints the variable value in human-readable form
gettype(); // Get type of var, var type
debug_print_backtrace(); // prints a backtrace that shows the current function call-chain.
// About error views
https://www.w3schools.com/php/php_error.asp
// Examples, need to test
// Report simple run errors error_reporting( E_ERROR | E_WARNING | E_PARSE );
// Report E_NOTICE in addition to simple run errors (to catch uninitialized variables or variable name misspellings)
// error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all PHP errors error_reporting(-1); //Report all PHP errors (see changelog) error_reporting(E_ALL); //Turn off all error reports error_reporting(0);
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
set_error_handler("customError");
// Debuging code functions
// debug custom function
function debug($arr){
echo '<pre>' . print_r( $arr, true ) . '</pre>';
}
debug();
// advanced debug func, convenient to use
function debug($value)
{
echo '<pre>';
if (is_array($value)) {
echo print_r($value) ;
} else {
var_dump($value, true) ;
}
echo '</pre>';
}
debug($value);
function enable_error_report(){
// Turn off error reporting
error_reporting(0);
// Turn on all errors reporting
error_reporting(E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
}
enable_error_report();
/** Generate view in Browser Console **/
function console_log( $data ){
if (!isset($value)) {
$value = "No data values";
}
// if (is_object($value)) {
// $value = (array)$value;
// // $value = json_decode(json_encode($test_obj), true);
// }
$value = json_encode($value);
echo '<script>';
echo 'console.log( "PHPDebug: ");';
echo 'console.log( "Data Type: '. gettype($value) .'");';
echo 'console.log('. $value .')';
echo '</script>';
}
console_log($query_array);
// detect function place executions
function sayHello($hello) {
echo $hello;
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
}
sayHello($myVar);
/** Laravel dd function dd(), dump and die **/
function dd($data) {
echo '<pre>';
die(var_dump($data));
echo '</pre>';
}
###### Install composer (MacOs), use composer ######
https://getcomposer.org/
https://packagist.org/
https://www.youtube.com/watch?v=I6wm15OWyqg
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer - ???
// ------------- work string, work with strings ------------- //
/*
https://www.w3schools.com/php/php_string.asp
String Reference - https://www.w3schools.com/php/php_ref_string.asp
String Functions - https://www.php.net/manual/en/ref.strings.php
*/
// A string literal can be specified in four different ways:
- single quoted
- double quoted
- heredoc syntax
- nowdoc syntax
// Special characters in double-quoted strings
\n - Newline (ASCII 10)
\r - Carriage return (ASCII 13)
\t - Tab (ASCII 9)
\\ - \
\$ - $
\" - "
\x0 .. \xFF - Hexadecimal (base 16) number
echo "\u(0410}" in UTF-8 is russian "A".
// Heredoc document syntax
// END este identificator (poate orisicare altul)
print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
// Nowdoc syntax
// A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.
// https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;
// How to call a PHP function inside a Heredoc.
$cb = function ($fn) {
return $fn;
};
echo <<<HEREDOC
Hello, {$cb(ucfirst('world'))}
HEREDOC;
// string interpolation
https://riptutorial.com/php/example/22788/string-interpolation
// You can also use interpolation to interpolate (insert) a variable within a string. Interpolation works in double quoted strings and the heredoc syntax only.
// examples
$email = '[email protected]';
print "Send replies to: $email"; // Send replies to: [email protected]
print 'Send replies to: $email'; // Send replies to: $email
// {} example
$name = 'Joel';
// Example using the curly brace syntax for the variable $name
echo "<p>We need more {$name}s to help us!</p>";
// Example of calling a method on an instantiated object
class Person {
function say_hello() {
return "Hello!";
}
}
$max = new Person();
echo "Max says: {$max->say_hello()}";
// functions for work with strings
$greet = function($num) {
return "A $num greetings!";
};
echo "From us all: {$greet(10 ** 3)}";
#> "From us all: A 1000 greetings!"
// Difference between echo and print funcs
/* The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions.
echo can take multiple parameters (although such usage is rare) while print can take one argument.
echo is marginally faster than print.
*/
// Output a formatted string, Produces output according to format.
printf(format,arg1,arg2,arg++); //printf("String %u lorem ipsum in %s.", $arg1, $arg2);
// Format string rules begin with % and then have some optional modifiers that affect
// what the rule does:
%% - Returns a percent sign
%b - Binary number
%c - The character according to the ASCII value
%d - Signed decimal number (negative, zero or positive)
%e - Scientific notation using a lowercase (e.g. 1.2e+2)
%E - Scientific notation using a uppercase (e.g. 1.2E+2)
%u - Unsigned decimal number (equal to or greather than zero)
%f - Floating-point number (local settings aware)
%F - Floating-point number (not local settings aware)
%g - shorter of %e and %f
%G - shorter of %E and %f
%o - Octal number
%s - String
%x - Hexadecimal number (lowercase letters)
%X - Hexadecimal number (uppercase letters)
// concatenare
se face cu "." primeste operanzii ca string-uri si returneaza string
// work with string functions
// output
printf(); // will - output - a formatted string using placeholders
sprintf(); // will - return - the formatted string. Function writes a formatted string to a variable.
// change string
strlen(): // Get The Length of a String () - returns the number of bytes rather than the number of characters! use mb_strlen()
strrev(); // Reverse a String
str_replace(); // Replace Text Within a String - remove white space example str_replace(' ', '', $name_contr_person );
str_ireplace(); // Case-insensitive version of str_replace
explode(); // Split a string by a string, Returns an array of strings
implode(); // Join array elements with a string
intval() // Get the integer value of a variable, convert string to num
nl2br(); // Inserts HTML line breaks before all newlines in a string, foarte util la functia mail()
// search and info of string
strval() // Get string value of a variable
strpos(); // Search For a Specific Text Within a String
mb_strpos(); // Find position of first occurrence of string in a string
str_word_count(); // Return information about words used in a string
mb_strlen() // Get string length, Gets the length of a string.
strstr(); // Find the first occurrence of a string (after selected character)
strtok(); // Find the first occurrence of a string (until selected character)
substr() // Return part of a string
// string compare
strncmp(); // Binary safe string comparison of the first n characters -> strncmp ( string $str1 , string $str2 , int $len ) : int
strcmp(); // Binary safe string comparison -> strcmp ( string $str1 , string $str2 ) : int
// clear strings
trim(str); // Clear spaces in the begin and end of string
stripslashes(); // Remove the backslash
strip_tags(); // Strip HTML and PHP tags from a string
// utils
md5(); // Calculate the md5 hash of a string
serialize() // Generates a storable representation of a value, use for JSON
unserialize() //
urlencode() // URL-encodes string, This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
// work with numbers
print 17 % 3 // for modulus division (returning the remainder of a division operation)
// Examples
// Split long string and add "...";
mb_strimwidth($origin_link_string, 0, 19, "...");
// Split a string by a string,
$str = 'Josanu Andrei Andrei';
$data = explode(' ', $str);
print_r($data);
echo implode( ' | ', $data);
trim($str, ','); // delete the comma
rtrim($str, ','); // delete comma from the right, end of string
ltrim($str, ','); // delete comma from the left, beggin of string
// Example string replace (bb tags to html)
$str = '[i]Hello[/i]! My name is Josanu [b]Andrei[/b]!';
$search = ['[b]', '[/b]', '[i]', '[/i]'];
$replace = ['<b>', '</b>', '<i>', '</i>'];
$str = str_ireplace( $search, $replace, $str );
// Clear string (my function), work with string,
function clear_string($str){
// Not so interesting but works :)
if ( is_string($str)){
$str = trim($str);
$str = str_replace(' ', '', $str);
$str = str_replace('-', '', $str);
} else {
return 'Not a string!';
}
return preg_replace('/[^A-Za-z0-9\-]/', '', $str);
}
// ------------- work math, work with math functions ------------- //
/*
* https://www.php.net/manual/en/book.math
* https://www.w3schools.com/php/php_ref_math.asp
*/
rand() - Generate a random integer
round() — Rounds a float
ceil() — Round fractions up
floor() — Round fractions down
// ------------- work Variables, vars, datatypes, debug, work constants ------------- //
// Check type of values
// check values
get_defined_vars() - Returns an array of all defined variables
get_defined_functions() - Returns an array of all defined functions
get_defined_constants() - Returns an associative array with the names of all the constants and their values
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
isset() - Determine if a variable is set and is not NULL,I n other words, it returns true only when the variable is not null.
gettype() - Get type of var
empty() - Determine whether a variable is empty. In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
is_null() - Finds whether a variable is NULL. In other words, it returns true only when the variable is null.
is_numeric();
is_string();
is_array(); The is_array() function is used to find whether a variable is an array or not.
is_bool();
is_int();
// Scopes in php
Variable scope
// The scope of a variable - is the part of the script in which the variable can be referenced or used.
// PHP's most used variable scopes are local, global.
// A variable declared outside a function has a global scope.
// A variable declared within a function has a local scope, and can only be accessed within that function.
The global keyword - is used to access a global variable from within a function.
// To do this, use the global keyword within the function, prior to the variables.
// check variable, check variable if not empty, empty var
if (isset($var_name)){}
TYPECASTING IN PHP
// The meaning of type casting is to use the value of a variable with different data type.
// https://codelabs.greycampus.com/php/type-casting
// https://www.odinschool.com/learning-hub/php/type-casting
// We can cast following data type variable in PHP
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)
// ------------- work Constants ------------- //
// Core Predefined Constants
https://www.php.net/manual/en/reserved.constants.php
// Magic constants
https://www.php.net/manual/en/language.constants.predefined.php
// __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, or {closure} for anonymous functions.
// __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.
// __FILE__
echo "The full path of this file is: " . __FILE__;
// __DIR__
echo "The directory of this file is: " . __DIR__;
// __FUNCTION__
function myFunction(){
echo "The function name is - " . __FUNCTION__;
}
myFunction(); // Displays: The function name is - myFunction
// __CLASS__
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName(); // Displays: MyClass
// __METHOD__
class Sample
{
public function myMethod(){
echo __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Displays: Sample::myMethod
// __NAMESPACE__
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__;
}
}
$obj = new MyClass();
echo $obj->getNamespace(); // Displays: MyNamespace
DIRECTORY_SEPARATOR - separator sign in directory path - ?
// Declare constants
define("Name", "Value", case-insensitive); //false default
define("Andrei", "Salut Andrei", true)
echo Andrei;
// check defined constant
var_dump(defined('Name'));
// check in class, check constant in class
if(defined("cls::NAME")) echo cls::NAME;
// ------------- work with ¡terators ------------- //
/*
* https://www.abeautifulsite.net/how-to-use-the-php-ternary-operator
* https://www.designcise.com/web/tutorial/whats-the-difference-between-null-coalescing-operator-and-ternary-operator-in-php
*/
// Ternary operator, ternar
$x = $valid ? 'yes' : 'no';
// ?: (Elvis Operator)
expr1 ?: expr2 // equivalent to: (expr1 ? expr1 : expr2);
// ?? (Null Coalescing Operator), PHP 7+
$x ?? $y;
// ??= (Null Coalescing Assignment Operator)
$x = (isset($x) ? $x : $y);
$x = $x ?? $y;
$x ??= $y;
// ------------- work array, work with array's ------------- //
/*
* Arrays are collections of related values.
* An array is a special variable, which can hold more than one value at a time.
* An array is a container that holds multiple values.
* https://www.php.net/manual-lookup.php?pattern=array_values%28%24arr%29&scope=quickref
*/
https://www.w3schools.com/php/php_ref_array.asp
Indexed arrays // - Arrays with a numeric index, array(value1, value2, value3, etc.)
Associative arrays // - Arrays with named keys, array(key=>value,key=>value,key=>value,etc.)
Multidimensional arrays // - Arrays containing one or more arrays
// --- Creating an array, function is used to create an array --- //
$arrayName = array(); // array(value1, value2, value3, etc.),
$arrayName = array('' => , ); // array(key=>value,key=>value,key=>value,etc.)
// Short syntax
// The short array syntax was introduced in PHP 5.4.
// If you’re using an earlier version of PHP, you need to stick with array().
$arrayName = []
$arrayName = [ 'key' => 'value' ];
// Initiate an array and add a value, add values to array, add new value in existing array
// add new elements to extisting arrays
$arrayName[] = 'value';
$arrayName[15] = 'value'; // add to index 15
// --- Helper functions --- //
https://www.php.net/manual-lookup.php?pattern=array_values%28%24arr%29&scope=quickref
// Check if array created
is_array();
// array length
count(); // Finding the size, return number of elements. An empty array is evaluates to false in an if() test expression.
in_array() — Checks if a value exists in an array
implode() - Array to string conversion, Join array elements with a string
print_r( array_values( $arrayName ) ) - Return all the values of an array
array_pop() - Pop the element off the end of array, shortening the array by one element.
array_keys() — Return all the keys or a subset of the keys of an array
array_values() — Return all the values of an array, returns all the values from the array and indexes the array numerically, reset index
array_intersect() — Computes the intersection of arrays
array_diff() — Computes the difference of arrays
// Checks if the given key or index exists in the array
array_key_exists($the_attribute, $object_properties);
// clear from duplicates and reset counter
$cleared_array = array_values(array_unique($all_tax_terms));
// Removes duplicate values from an array, remove identical values from array
https://www.php.net/manual/ro/function.array-unique.php
array_unique($arr1, $arr2);
// Push one or more elements onto the end of array, add elements to the end of array
// Add new value in existing array
array_push($arrname, "Value_1", "Value_2");
// Has the same effect as:
$array[] = $var;
// --- Looping Through Arrays, loop array --- //
// The best and easiest way to iterate through each element of an array is with foreach()
// The foreach() loop gives you the value of each array element
// foreach works only on arrays and objects
https://www.php.net/manual/ro/control-structures.foreach.php
foreach(); // lets you run a code block once for each element in an array.
foreach (array_name as $value) {
statement
}
foreach (array_name as $key => $value)
statement
foreach ( $variable as $key => $value ) {
print "$value";
}
// for each element in the $array array, use the keys as the $key variable, and the values as the $value variable.
foreach ( $assocArray as $key => $value )
echo $key . ' = ' . $value . '<br />';
foreach ($nume as $k => $v) {
echo "Key: " . $k . "Value: " . $v . "<br>";
}
// Concise form of foreach() for use with numeric(indexed) arrays
foreach ($variable as $key ) {
print "$key";
}
// While loop
while ( $i < count($goods) ){
echo $goods[$i]['title'] . " - " . $goods[$i]['price'];
$i++;
}
// For Loop
for ($i = 0, $num_dishes = count($variable); $i < $num_dishes; $i++){
print "Dish number $i is $dinner[$i]\n";
}
// multidimensional array
for ($i = 0; $i < count($Arr["value"]); $i++) {
foreach ($Arr[$keys[$i]] as $key => $value) {
$htmlListTags .= $key . " : " . $value . "<br>";
}
}
// transform multidimensional in onedimensional
$one_dimension = array();
foreach ( $multi_dimension as $element ) {
foreach ( $element as $key => $value ) {
$one_dimension[ $key ] = $value;
}
}
// print with <pre> tag for better view
echo "<pre>";
print_r( $fields );
echo "</pre>";
// If you have an array key that has whitespace or other punctuation in it, interpolate it with curly braces.
$meals['Walnut Bun'] = '$3.95';
$hosts['www.example.com'] = 'website';
echo "A Walnut Bun costs $meals['Walnut Bun']"; print "www.example.com is a {$hosts['www.example.com']}.";
// --- Search in array --- //
// Find an element with a certain key, returns true.
array_key_exists()
// This is true
if (array_key_exists('Shrimp Puffs', $meals)) { print "Yes, we have Shrimp Puffs"; }
// To check for an element with a particular value, use in_array(), return true, check array value
in_array(); // Checks if a value exists in an array
in_array(3, $variable);
array_search() // function is similar to in_array() but if it finds an element and it returns the element key instead of true.
// get last array element
$arr_elements_count = count($multiple_events_arr) - 1;
// - Modifying Arrays - //
// To remove an element from an array, use unset():
unset($dishes['Roast Duck']);
// When you want to print all of the values in an array at once, the quickest way is to use the implode() function.
implode();
$show_variable = implode(', ', $variable); // This function will be print with "," delimiter, given like a first function argument
// The counterpart to implode() is called explode()
explode(', ', $variable);
// Merge one or more arrays, merge array's. Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one.
// It returns the resulting array.
array_merge();
$result = array_merge($array1, $array2);
// - Sorting Arrays - //
// Sorting by values
sort() // sorts an array by its element values, It should only be used on numeric arrays, because it resets the keys of the array when it sorts.
asort() // To sort an associative array by element value
// sort arrays by key with ksort()
ksort()
// The array-sorting functions sort(), asort(), and ksort() have counterparts that sort in descending order. sort,
rsort(), arsort(), and krsort()
// - Multidimensional Arrays - //
// A multidimensional array is an array containing one or more arrays.
https://www.w3schools.com/php/php_arrays_multidimensional.asp
// The dimension of an array indicates the number of indices you need to select an element.
// For a two-dimensional array you need two indices to select an element
// For a three-dimensional array you need three indices to select an element
$meals = array( 'breakfast' => ['Walnut Bun','Coffee'],
'lunch' => ['Cashew Nuts', 'White Mushrooms'],
'snack' => ['Dried Mulberries','Salted Sesame Crab']);
$lunches = [ ['Chicken','Eggplant','Rice'],
['Beef','Scallions','Noodles'],
['Eggplant','Tofu'] ];
$flavors = array( 'Japanese' => array('hot' => 'wasabi', 'salty' => 'soy sauce'),
'Chinese' => array('hot' => 'mustard', 'pepper-salty' => 'prickly ash'));
$specials[0][0] = 'Chestnut Bun';
$specials[0][1] = 'Walnut Bun';
$specials[0][2] = 'Peanut Bun';
$specials[1][0] = 'Chestnut Salad';
$specials[1][1] = 'Walnut Salad';
$specials[1][2] = 'Salad Mesnoi';
// Numeric array
for ( $n = 0 ; $n < count($specials); $n++ ){
for ( $i = 0 ; $i < count($specials[$n]); $i++ )
print "Element [$n][$i] is " . $specials[$n][$i] . "\n";
}
// Examples
$superheroes = array(
"spider-man" => array(
"name" => "Peter Parker",
"email" => "[email protected]",
),
"super-man" => array(
"name" => "Clark Kent",
"email" => "[email protected]",
),
"iron-man" => array(
"name" => "Harry Potter",
"email" => "[email protected]",
)
);
// Printing all the keys and values one by one
$keys = array_keys($superheroes);
for($i = 0; $i < count($superheroes); $i++) {
echo $keys[$i] . "{<br>";
foreach($superheroes[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
/*
multidimensional indexed array initialization
*/
$cars = array(
array(
"name"=>"Urus",
"type"=>"SUV",
"brand"=>"Lamborghini"
),
array(
"name"=>"Cayenne",
"type"=>"SUV",
"brand"=>"Porsche"
),
array(
"name"=>"Bentayga",
"type"=>"SUV",
"brand"=>"Bentley"
),
);
// array traversal
// find size of the array
$size = count($lamborghinis);
// using the for loop
for($i = 0; $i < $size; $i++)
{
foreach($cars[$i] as $key => $value) {
echo $key . " : " . $value . "\n";
}
echo "\n";
}
// multidimensional asociative array initialization
$cars = array(
"Urus" => array(
"type"=>"SUV",
"brand"=>"Lamborghini"
),
"Cayenne" => array(
"type"=>"SUV",
"brand"=>"Porsche"
),
"Bentayga" => array(
"type"=>"SUV",
"brand"=>"Bentley"
),
);
/*
array traversal
*/
// find size of the array
$size = count($lamborghinis);
// array keys
$keys = arra_keys($cars);
// using the for loop
for($i = 0; $i < $size; $i++)
{
echo $keys[$i]. "\n";
foreach($cars[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "\n";
}
echo "\n";
}
// transform string values in num format in array, array transform to num
// https://stackoverflow.com/questions/3570400/how-to-convert-a-comma-separated-string-of-numbers-to-an-array-of-integers
$arr_str = explode (",", trim($text_values));
// transform string values in num format
foreach ($arr_str as $key) {
$arr_num[] = intval($key);
}
// get data from another array and include in finall
function acf_load_phone_field_choices_from_location_cpt( $field ) {
$locations = get_location_cpt_data();
$choices = [];
if ( is_array( $locations ) && ! empty( $locations ) ) {
foreach ( $locations as $location ) {
$choices['phone_' . $location['country_code']] = $location['phone_number'];
}
}
$field['choices'] = $choices;
return $field;
}
/*
*
* ------------- work functions, User Defined Functions, user functions, FUNCTIONS AND SCOPE ------------- *
* https://www.w3schools.com/php/php_functions.asp
*
*/
// Function
function functionName(){
code to be executed
function context
local variables
}
// A function name can start with a letter or underscore (not a number).
// Give the function a name that reflects what the function does!
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
// Passing Arguments
// Function helpers, read arguments,
func_num_args(); // return all function parameters (int)
func_get_arg( int $num ); // return value of argument with number $num (array)
func_get_args(); // return list of all arguments (array)
// example
function test($arg1, $arg2, $arg3, $arg4){
echo func_num_args();
print_r(func_get_args());
echo func_get_arg(0);
}
test($arg1 = "valoare1", $arg2 = "valoare2", $arg3 = "valoare3", $arg4 = "valoare4");
// Passing Arguments by Reference
function add_five(&$value) {
$value += 5;
}
// --- Type declarations --- //
// https://www.php.net/manual/en/language.types.declarations.php
// Type declarations can be added to function arguments, return values, and, as of PHP 7.4.0, class properties.
// Return Type Declarations, by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.
function addNumbers(float $a, float $b) : float {
return $a + $b;
return (int)($a + $b); // make sure the return is the correct type.
}
// declare(strict_types = 1); setup strict typification
function sum( int $fst, int $snd ) : int {} // setting type of input parameters and output results
// --- SCOPES, FUNCTIONS AND SCOPE --- //
// While variables are containers for information, functions are containers for functionality.
// If we need to do something, we almost always want to encapsulate that functionality in a function.
// Local variables
function name(&$a){} // Parameter $a was linked to real variable wich was transmited
// Global variables
declare a variable global type in first function line
array $GLOBALS // take a global variable, function getMonthName($n) {return $GLOBALS["monthes"][$n];}
// we can't assign this array to variable with '=' sign
// we can read all arguments with foreach function
static - comunica compilatorului ca intre chemari variabila nu trebuieste distrusa
declararea si asocierea valorii variabilei are loc o singura data.
// Type declarations, Return Type Declarations
// https://www.php.net/manual/en/language.types.declarations.php
// To specify strict we need to set declare(strict_types=1);
declare( strict_types=1 ); // strict requirement, This must be on the very first line of the PHP file.
function addNumbers( float $a, float $b ) : float { return $a + $b; }
// check if function exist
// https://www.php.net/manual/en/function.function-exists.php
function_exists() // Return true if the given function has been defined
if (!function_exists('function_name')) {
function function_name() {
}
}
//---- work User Defined Functions ----//
// Return the number of arguments passed to the function.
func_num_args() // int
func_get_args() // Array
// Declare function with strict types arguments
function sum(int $fst, int $snd) : int{}
// Connect strict tipization data type
declare(strict_types = 1);
//---- work functions, statements, control structures ----//
// work statements
https://www.php.net/manual/ru/language.control-structures.php
// if
// else
// elseif/else if
// Alternative syntax for control structures
// while
// do-while
// for
// foreach
// break
// continue
// switch
// declare
// return
// require
// include
// require_once
// include_once
// goto
//---- callback functions ----//
// A callback function (often referred to as just "callback") is a function which is passed as an argument into another function.
https://www.w3schools.com/php/php_callback_functions.asp
https://www.php.net/manual/ro/language.types.callable.php
// Alternative syntax for control structures, work with syntax,
************ syntax, alternative syntax, work with syntax ************
// Short syntax, short sintax
https://www.php.net/manual/en/control-structures.alternative-syntax.php#:~:text=PHP%20offers%20an%20alternative%20syntax,%2C%20or%20endswitch%3B%20%2C%20respectively.
// PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch.
// if, while, for, foreach, and switch => endif;, endwhile;, endfor;, endforeach;, or endswitch;
// example
<?php if ( $a == 5 ): ?>
A is equal to 5
<?php endif; ?>
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
<?php
if ( $a == 5 ):
echo "a equals 5";
echo "...";
elseif ( $a == 6 ):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
<?php switch ( $foo ): ?>
<?php case 1: ?>
...
<?php endswitch
<?php for ( $i = 1; $i <= 10; $i++ ) : ?>
# code...
<?php endfor ?>
<?php
// Logical Operators
https://www.php.net/manual/en/language.operators.logical.php
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
// PHP Conditional Statements
// if...else...elseif Statements
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
// The if...elseif...else Statement
// The if...elseif...else statement executes different codes for more than two conditions.
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
//---- work Loops ----//
https://www.w3schools.com/php/php_looping.asp
// The PHP for Loop, loop for
// PHP for loops execute a block of code a specified number of times.
// The for loop is used when you know in advance how many times the script should run.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
for (init counter; test counter; increment counter) {
code to be executed;
}
// init counter: Initialize the loop counter value
// test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
// increment counter: Increases the loop counter value
// The for loop is used when you know in advance how many times the script should run.
for ( $x = 0; $x <= 10; $x++ ) {
echo "The number is: $x <br>";
}
// The PHP foreach Loop
// The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
foreach ($array as $value) {
code to be executed;
}
$colors = array( "red", "green", "blue", "yellow" );
foreach ( $colors as $value ) {
echo "$value <br>";
}
// Example for Associative arrays
foreach ( $arr as $key => $value ) {}
// Example for view multidimensional Array
foreach( $db_results as $number => $number_array )
{
foreach( $number_array as $data => $user_claim_data )
{
print " <br>Array number: $number, contains $data with $user_claim_data. ";
}
}
// PHP while Loops
// PHP while loops execute a block of code while the specified condition is true.
while (condition is true) {
code to be executed;
}
// The PHP do...while Loop
// The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.
do {
code to be executed;
} while (condition is true);
// The PHP switch control structure, switch structure
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
// ------------- work date and time object ------------- //
https://www.w3schools.com/php/php_date.asp
// format
https://thevaluable.dev/php-datetime-create-compare-format/
date(format,timestamp);
// Returns the difference between two DateTime objects, day difference
https://www.php.net/manual/en/datetime.diff.php
$origin = new DateTime('2009-10-11');
$target = new DateTime('2009-10-13');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');
// from old implemented OOP code
private static function show_current_left_time() {
// - Functionality for render first date/time - //
date_default_timezone_set('Europe/Bucharest');
$today = new DateTime();
echo $today->format( 'Y-m-d H:i:s' );
$endDay = new DateTime( self::BF_END_DATE );
// Calculate the difference in days between today and the end date
return $today->diff( $endDay );
}
// $current_time = date_create(date("d.m.Y"));
// $event_date = date_create(date("d.m.Y"));
// $interval = date_diff($event_date, $current_time);
// var_dump($interval->d);
// ------------- work Objects, obiectele, obiecte, work class, work classes, work oop, work oop in php, php oop ------------- //
/*
*
* PHP Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure software.
* OOP focuses on the concepts of encapsulation, inheritance, and polymorphism.
*
* Object Oriented Programming (OOP) este o paradigmă de programare, axată pe ideea încapsulării,
* adică grupării datelor și codului care operează cu ele, într-o singură structură.
*
* https://www.w3schools.com/php/php_oop_what_is.asp
*
*/
// --> Work classes
// stdClass in php
// https://www.geeksforgeeks.org/what-is-stdclass-in-php/
// https://www.w3schools.com/php/php_oop_classes_objects.asp
Class - A class is a template (blueprint) for objects, and an object is an instance of a class.
Instance - Instantiate a class, an individual usage of a class.
While each of these instances is based on the same class, they differ internally by having different property values.
The methods in each instance contain the same instructions, but probably produce different results because they each rely on the particular property values in their instance.
Creating a new instance of a class is called “instantiating an object.”
Method - A function defined in a class.
Property - A variable defined in a class.
Pseudovariabile
$this - apelarea metodelor si proprietatilor in contextul obiectului. Pseudovariable. // It's a link to the object of this method
self - apelarea metodelor si proprietatilor statice in contextul clasei.
// Example of basic structure
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
// The pseudo-variable $this is available when a method is called from within an object context.
}
}
//--> Static methods and properties
// static methods
Static method - A special kind of method that can be called without instantiating a class. Static methods don’t depend on the property values of a particular instance.
Static methods are useful for behavior that is relevant to what the class is for, but not to any one object.
public static function funcName() {
return 'something';
}
To call a static method, you put :: between the class name and the method name instead of ->
// static props
Static Properties - can be called directly - without creating an instance of a class.
Static properties are declared with the static keyword:
class ClassName {
public static $staticProp = "W3Schools";
}
// To access a static property use the class name, double colon (::), and the property name:
ClassName::$staticProp;
// work $this
$this - The $this keyword refers to the current object, and is only available inside methods.
The arrow operator (->) - is your road to the properties (variables) and methods (functions) inside an object.
//--> helper functions
get_class();
class_exists(); // Verifică dacă clasa a fost definită, check if class exists, check class exists
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
// work instanceof
// You can use the instanceof keyword to check if an object belongs to a specific class:
var_dump($objectName instanceof ClassName) : bool;
// Checks if the class method exists
method_exists ( string|object $object , string $method_name ) : bool
//--> about $this keyword
// interesting things about
https://www.phptutorial.net/php-oop/php-this/
https://www.geeksforgeeks.org/this-keyword-in-php/
https://www.w3schools.com/php/php_oop_classes_objects.asp
class Name {
get_class($this);
}
*** Instantiate a class, instantierea clasei ***
// Basic class definitions begin with the keyword class, followed by a class name,
// followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.
// https://www.php.net/manual/en/language.oop5.basic.php
Instance - Instantiate a class, an individual usage of a class.
Creating a new instance of a class is called “instantiating an object.”
While each of these instances is based on the same class, they differ internally by having differ‐ ent property values.
The methods in each instance contain the same instructions, but probably produce different results because they each rely on the particular property values in their instance.
// class declaration
class className
{
// Properties and methods...
public $property = "value";
// public
// protected - visible and accesible only in parent and childs classes
// private - visible only in class, not accesible
$this-> - object context
self:: - class context
public static function method(){
// It's like a standard function
}
// Construct method - A class can have a special method, called a constructor, which is run when the object is created.
// In PHP, the constructor method of a class is always called __construct()
// Cunstructor
public function __construct($parameter){
$this->parametru = $parameter;
}
// Destruct method
public function __destruct(){
$this->parametru = $parameter;
}
}
// Another small example of a class a Instance, getter and setter
class Fruit {
// Properties
public $name;
public $color;
// Methods
// setter
function set_name($name) {
$this->name = $name;
}
// getter
function get_name() {
return $this->name;
}
}
// work classes snipets
// view all classes, find all declared classes
$declared_classes = get_declared_classes();
foreach ($declared_classes as $class) {
# code...
echo $declared_classes . "<br>";
}
// get class methods
$class_methods = get_class_methods();
// Creating an instance of a class
$instance = new SimpleClass();
// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
*** Inheritance / Mostenirea, Extending an Object, extinderea unui obiect, extend class, parent class, clasa parinte ***
// Mecanism al limbajului care permite sa descrie o clasa noua pe baza celui existent (parinte).
// clasa copil poate adauga propriile metode si proprietati in acelasi timp poate sa le utilizeze pe cele ale parintelui.
// subclassing,
// Inheritance in OOP = When a class derives from another class.
// https://youtu.be/T73ieFL3g2g (Rus - simple)
class childClassName extends parentClassName{}
final - se utilizeaza pentru descrierea metodelor clasei, daca este indicat atunci metodele din class-ele copii nu v-or putea fi modificate
nu mai poti modifica metoda sau chiar classa (final class className{})
final public function methodName(){}
// Extend class, child classes
class Vehicle {
final public function funcName() {
// final for final methods, no possibility to extends
}
}
class Car extends Vehicle {}
// final class
final class Car extends Vehicle {}
// exemplu cu test
class Base {
public $a = 'a public';
protected $b = 'b protected_1';
private $c = 'c private';
function printProperties() {
echo '<br>' . $this->a;
echo '<br>' . $this->b;
echo '<br>' . $this->c;
}
}
class Inherited extends Base {
function printProperties()
{
echo '<br>' . $this->a;
echo '<br>' . $this->b;
echo '<br>' . $this->c;
}
}
// parent class
//$obj = new Base();
//echo '<br>' . $obj->a; // a public
//echo '<br>' . $obj->b; // Fatal error: Uncaught Error: Cannot access protected property Base::$b
//echo '<br>' . $obj->c; // Error: Cannot access protected property Base::$b
//$obj->printProperties(); // show responsens
// child class
$obj2 = new Inherited;
//echo '<br>' . $obj2->a; // a public
//echo '<br>' . $obj2->b; // Fatal error: Uncaught Error: Cannot access protected property Inherited::$b
//echo '<br>' . $obj2->c; // Error: Cannot access protected property Inherited::$b
$obj2->printProperties(); // <br>a public<br>b protected_1 Notice: Undefined property: Inherited::$c
*** Encapsulation / Incapsularea, visibility domains, Access Modifiers, access control modifiers ***
// Mecanism al limbajului care permite sa limiteze accesul unor componente ale programei catre altele
// se realizeaza cu ajutorul modificatorilor de acces
// Access Modifiers, Modificatorii de acces, Domeniu de vizibilitate, work access
Public - can be accessed everywhere
Protected - can be accessed within the 'class' itself or extensions of that class
Private - can be accessed within the class itself
// RULES OF METHOD VISIBILITY
// Public method - can be called outside of the class or in a subclass.
// Protected method - can’t be called outside of a class, but can be called in a subclass.
// Private method - can only be called inside of the class it is declared in.
// Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.
Static method - A special kind of method that can be called without instantiating a class.
Static methods don’t depend on the property values of a particular instance.
class ClassName {
public static $var = "Value";
public static function arata() {
return self::$var;
}
}
echo ClassName::$var;
echo ClassName::arata();
// Getter and Setter Methods, geter, seter, work getter, work setter
// https://alexwebdevelop.com/getter-setter-functions/
// example of using getter and setter
class MyClass {
/* Private attribute, cannot be accessed directly */
private $name;
/* Constructor */
public function __construct()
{
$this->name = '';
}
/* Getter function to read the attribute */
public function get_name()
{
return $this->name;
}
/* Setter function to change the attribute */
public function set_name($new_name)
{
if ($this->is_valid_name($new_name))
{
$this->name = $new_name;
}
}
/* Checks if the name is valid */
private function is_valid_name($name)
{
$valid = TRUE;
/* Just checks if the string length is between 3 and 16 */
if (mb_strlen($name) < 3)
{
$valid = FALSE;
}
else if (mb_strlen($name) > 16)
{
$valid = FALSE;
}
return $valid;
}
}
$mc = new MyClass();
$mc->set_name('Alex');
echo $mc->get_name();
*** debug classes ***
// get class methods The get_class_methods() function is an inbuilt function in PHP
var_dump(get_class_methods(WPGlobus_Core));
*** Interfaces ***
// https://www.w3schools.com/php/php_oop_interfaces.asp
// Interfaces allow you to specify what methods a class should implement.
// Interfaces make it easy to use a variety of different classes in the same way.
// When one or more classes use the same interface, it is referred to as "polymorphism".
// !!! It's like a contract. When a class implements an interface, it agrees to implement specific methods in it.
*** Abstract classes ***
// They're a mix between a class and an interface.
*** Indicating a Problem with Exceptions, Exception class, work exceptions ***
// Constructors are great for verifying that supplied arguments are the right type or otherwise appropriate.
// But they need a way to complain if there is a problem. This is where an exception comes in.
// “Throwing” an exception means you use an exception tell the PHP engine that something went wrong.
public function __construct($name, $ingredients) {
if ( !is_array( $ingredients ) ) {
throw new Exception( '$ingredients must be an array' );
}
$this->name = $name;
$this->ingredients = $ingredients;
}
// To handle an exception yourself, do two things:
// 1. Put the code that might throw an exception inside a try block.
// 2. Put a catch block after the potentially exception-throwing code in order to handle the problem.
try {
$drink = new Entree('Glass of Milk', 'milk');
if ($drink->hasIngredient('milk')) {
print "Yummy!";
}
}
catch (Exception $e)
{
print "Couldn't create the drink: " . $e->getMessage();
}
// --> work objects
// Notiuni generale
In the programming world, an object is a structure that combines data about a thing (such as the ingredients in an entrée)
with actions on that thing (such as determining if a certain ingredient is in the entrée). Using objects in a program provides an organ‐ izational
structure for grouping related variables and functions together.
// Pseudo constante globale
https://www.php.net/manual/en/language.constants.predefined.php
__CLASS__ - class info
__METHOD__ - method info
General
// The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the declaration with the keywords public,
// protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class
// itself and by inheriting and parent classes. Members declared as private may only be accessed by the class that defines the member.
Constructor - A special method that is automatically run when an object is instantiated.
Usu‐ ally, constructors set up object properties and do other housekeeping that makes the object ready for use.
// Constructorul este o metoda care se cheama automat la crearea obiectului
// Instantiate an object
$emptyObject = new stdClass() or new stdClass; // Standard way to create an "empty" object is with stdClass(), this is the best method;
$emptyObject = (object)[]; // It's shorter and (object)[] is equivalent to new stdClass();
// Instantiate an object from a class, create object
$ojectName = new className;
// or with parameter for construct method
$ojectName = new className($parameter);
// acces property and methods
$objectName->proprietate ($proprietate)
$objectName->metoda() (function metoda())
// object debug
var_dump( get_object_vars( objectName ) ); // Shows properties of object in detailing mode
// ------------- work namespaces ------------- //
https://www.w3schools.com/php/php_namespaces.asp
// good video
https://www.youtube.com/watch?v=DsTx2S-bDQA
// 1. They allow for better organization by grouping classes that work together to perform a task
// 2. They allow the same name to be used for more than one class
// Rule: A namespace declaration must be the first thing in the PHP file.
// Namespace Alias
namespace Html;
use Html as H;
$table = new H\Table();
// ------------- work autoload ------------- //
https://www.php.net/manual/en/function.autoload.php
https://www.youtube.com/watch?v=NLXtGZ6Ilsw
__autoload — Attempt to load undefined class
__autoload() is deprecated as of PHP 7.2.0, and removed as of PHP 8.0.0
spl_autoload_register(); // Register given function as __autoload() implementation
spl_autoload(); // Default implementation for __autoload()
/**
* Simple autoloader function
*
* @param $class_name - String name for the class that is trying to be loaded.
* https://opensource.com/article/23/4/autoloading-namespaces-php#:~:text=In%20the%20PHP%20language%2C%20autoloading,were%20loaded%20before%20using%20them.
*/
function my_custom_autoloader( $class_name ){
$file = __DIR__.'/includes/'.$class_name.'.php';
if ( file_exists($file) ) {
require_once $file;
}
}
// add a new autoloader by passing a callable into spl_autoload_register()
spl_autoload_register( 'my_custom_autoloader' );
$my_example = new SomeClass1(); // this works!
// ------------- singleton pattern ------------- //
// We use the singleton pattern in order to restrict the number of instances that can be created from a resource consuming class to only one.
// Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.
https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php
https://refactoring.guru/design-patterns/singleton/php/example
https://www.youtube.com/watch?v=NNk05iKtmPs&list=PLAeYwXOK2friGtGcFhE6aBfqf6jW4BjPo&index=8&t=13s
// General singleton class. Simple example
class Singleton {
// Hold the class instance.
private static $instance = null;
// The constructor is private
// to prevent initiation with outer code.
protected function __construct() {
// The expensive process (e.g.,db connection) goes here.
}
// The object is created from within the class itself
// only if the class has no instance.
public static function getInstance() {
if (self::$instance == null)
{
self::$instance = new Singleton();
}
return self::$instance;
}
/**
* Singletons should not be cloneable.
*/
protected function __clone() { }
/**
* Singletons should not be restorable from strings.
*/
public function __wakeup()
{
throw new \Exception("Cannot unserialize a singleton.");
}
}
// ------------- try catch, error handling ------------ //
https://www.w3schools.com/php/php_exception.asp
// Basics & Advanced PHP Exception Handling Tutorial
https://stackify.com/php-try-catch-php-exception-tutorial/
// ------------- class data validation ------------ //
/**
* Save video to the database. *
* @param mixed $video
*/
function myplugin_save_video($video) {
if (!is_a($video, 'MyPlugin_Video')) {
return;
}
}
// ------------- class work helper functions, class helper functions ------------ //
class_exists();
get_class($user);
get_declared_classes();
get_class_methods();
get_class_vars();
//-> snippet example
$all_declared_classes = get_declared_classes();
foreach ($all_declared_classes as $classes) {
echo $classes . "<br>";
}
//---- Work forms, form. form helper, check get ----//
//// Form action include to action atribute
// action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);
$_GET[''];
$_POST[''];
$_REQUEST['']; // super global variable which is used to collect data after submitting an HTML form.
$_SERVER // $HTTP_SERVER_VARS [removed] — Server and execution environment information
// view query string
https://www.php.net/manual/ro/reserved.variables.server.php
var_dump($_SERVER["QUERY_STRING"]);
// Check whether the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {}
// Example, get info from incoming query
if( isset( $_SERVER['REQUEST_METHOD'] )){
echo ( var_dump( $_SERVER['REQUEST_METHOD'] ));
echo ( var_dump( $_SERVER['QUERY_STRING'] ));
echo ( var_dump( $_SERVER['HTTP_ACCEPT_ENCODING'] ));
echo ( var_dump( $_SERVER['REQUEST_URI'] )); // take a query, cererea
echo ( var_dump( $_SERVER['SERVER_PROTOCOL'] ));
echo ( var_dump( $_SERVER['HTTP_HOST'] ));
echo ( var_dump( $_SERVER['HTTP_REFERER'] ));
echo ( var_dump( $_SERVER['REMOTE_HOST'] ));
}
//Form values verification
if(isset($_POST['myField']) {}
if(isset($_POST['myField']) && $_POST['myField'] != ""){}
// More efficient way
if(!empty($_POST['myField'])) {}
// Get Multiple Checkbox Values in PHP,
https://makitweb.com/get-checked-checkboxes-value-with-php/ (much more complicated functions with write in DB)
<form action="<?php //the_permalink($post->ID); ?>" id="feature-checkbox">
<input id="all" type="checkbox" name="laundries_cat[]" value="all">
<input id="24-hours" type="checkbox" name="laundries_cat[]" value="24-hours">
<input id="free-wi-fi" type="checkbox" name="laundries_cat[]" value="free-wi-fi">
<input type="submit">
</form>
if( isset( $_GET['laundries_cat'] ) ){}
if( !empty( $_GET['laundries_cat'] ) ){
$laundries_features = $_GET['laundries_cat'];
foreach ($laundries_features as $value) {
echo $value;
}
}
// ------------- Form validation ------------- //
https://developer.hyvor.com/php/input-validation-with-php#user-inputs
// ------------- work Sessions ------------- //
/*
*
*/
// Start the session, The session_start() function must be the very first thing in your document. Before any HTML tags.
session_start();
// Set session variables
$_SESSION["favcolor"] = "green";
// Show session values
print_r($_SESSION);
// ------------- work json, serialize strings ------------- //
/*
*
http://php.net/manual/en/function.serialize.php
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php
*
*/
//work serialize
serialize — Generates a storable representation of a value
serialize();//Returns a string containing a byte-stream representation of value that can be stored anywhere.
unserialize — Creates a PHP value from a stored representation
unserialize(); //takes a single serialized variable and converts it back into a PHP value.
json_encode(); // Returns the JSON representation of a value
json_decode($json, true);//When TRUE , returned objects will be converted into associative arrays.
json_last_error(); //It will return error code of the last encode/decode operation.
// the function you should use for testing:
function isValidJson($strJson) {
json_decode($strJson);
return (json_last_error() === JSON_ERROR_NONE);
}
// Example of work
//here is my initial string
$sJson = $_POST['json'];
//try to decode it
$json = json_decode($sJson);
if (json_last_error() === JSON_ERROR_NONE) {
//do something with $json. It's ready to use
} else {
//yep, it's not JSON. Log error or alert someone or do nothing
}
// * Short version of convert json to array
$decodedText = html_entity_decode($codedText);
$myArray = json_decode($decodedText, true);
var_dump($myArray);
// * Long my first code version
// Clear strip slashes
$codedString = stripslashes($codedString);
// Clear and replace another characteres
$replaceCharacters = array( '{', '}', '"');
$codedString = str_replace($replaceCharacters, '', $codedString);
// Convert string to array
$codedString = explode(",",$codedString);
// make 2 arrays with different values take until and after ':' sign
for ( $i = 0 ; $i <= 22 ; $i++ ){
$arrayKeys[$i] = strtok($codedString[$i], ":");
$arrayValues[$i] = strstr($codedString[$i], ":");
$arrayKeys[$i] = str_replace(':', '', $arrayKeys[$i]);
$arrayValues[$i] = str_replace(':', '', $arrayValues[$i]);
}
// Combine 2 indexed arrays to make one assoc array
$result = array_combine($arrayKeys, $arrayValues);
// echo '<pre>';
// print_r ($result );
// echo '<pre>';
// :-)))
// ------------- PHP header() Function, php headers, work headers ------------- //
/*
* Definition and Usage
* The header() function sends a raw HTTP header to a client.
* https://www.w3schools.com/php/func_network_header.asp
* https://www.php.net/manual/ru/function.header.php
*/
// It is important to notice that the header() function must be called before any actual output is sent!
header(header, replace, http_response_code)
// header Required. Specifies the header string to send
// replace Optional. Indicates whether the header should replace a previous similar header or add a new header of the same type. Default is TRUE (will replace). FALSE allows multiple headers of the same type
// http_response_code Optional. Forces the HTTP response code to the specified value
// https://www.php.net/manual/ro/function.headers-sent.php
headers_sent(bool) - Checks if or where headers have been sent
if (!headers_sent()) {
header('Location: http://www.example.com/');
exit;
}
headers_list ( void ) : array - Returns a list of response headers sent (or ready to send)
getallheaders() - Fetch all HTTP request headers;
// Examples
// Fetch all HTTP request headers
$headers = getallheaders();
Header("Content-type: text/plain");
print_r(Sheaders);
// Send three HTTP headers to prevent page caching:
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
// Change coding to utf-8
header("Content-Type: text/html; charset = utf-8");
// Redirect
header("Location: http://www.google.com/");
header("Location: {$_SERVER['PHP_SELF']}"); // universal solution to onself redirect
// Working with coding functions
mb_check_encoding() - Check if the string is valid for the specified encoding;
mb_detect_encoding() - Detect character encoding
echo mb_detect_encoding($url, 'UTF-8, ISO-8859-1'); // detect which type is true
'CP1251',
'UCS-2LE',
'UCS-2BE',
'UTF-8',
'UTF-16',
'UTF-16BE',
'UTF-16LE',
'CP866',
// examples redirect, readresare
// extern redirect (in the browser)
header('Location: http://{$_SERVER['SERVER_NAME']}/adress.html');
// intern redirect (on the server)
header("Location: /adress.html");
// ------------- work files, filesystem ------------- //
/*
* https://www.php.net/manual/en/ref.filesystem.php
*/
// some file functions
copy() - Copies file
file_exists() - Checks whether a file or directory exists
file_get_contents() - Reads entire file into a string
file_put_contents() - Write data to a file // This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
file() - Reads entire file into an array
is_dir() - Tells whether the filename is a directory
rename() - Renames a file or directory, // moving it between directories if necessary
touch() - Sets access and modification time of file
unlink() - Deletes a file
filesize() - Returns the size of a file in bytes
// Directory Functions
mkdir() - Makes directory
rmdir() - Removes directory
chdir() - Change directory
chroot() - Change the root directory
closedir() - Close directory handle
dir() - Return an instance of the Directory class
getcwd() - Gets the current working directory
opendir() - Open directory handle
readdir() - Read entry from directory handle
rewinddir() - Rewind directory handle
scandir() - List files and directories inside the specified path
// Examples
https://www.php.net/manual/en/function.copy.php
copy('filepath/filename', 'filepath/filename');
// view site html code
$file = file_get_contents('https://www.php.net');
echo htmlspecialchars($file);
// write in file
file_put_contents('gb.txt', $str, FILE_APPEND); // FILE_APPEND to put text on the end of file
// ############## Upload files ############## //
$_FILES["file"]["tmp_name"] contains the actual copy of your file content on the server while
$_FILES["file"]["name"] contains the name of the file which you have uploaded from the client computer.
$_FILES["file"]["name"] This name includes a file path, which makes file read process more complex
// Use pathinfo( $_FILES['file']['name'], PATHINFO_EXTENSION ) to safely get the extension.
// example, get file from link
if( isset( $_GET['file_link'] ) ){
$url = $_GET['file_link'];
$data = file_get_contents($url);
$new = 'signed_pdf_files/test.pdf';
file_put_contents($new, $data);
echo "succes";
}
// Delete all files from folder, delete file
https://stackoverflow.com/questions/4594180/deleting-all-files-from-a-folder-using-php
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
if (!unlink($file_pointer)) {
echo ("$file_pointer cannot be deleted due to an error");
}
else {
echo ("$file_pointer has been deleted");
}
// ############## Include files ############## //
https://phpdelusions.net/articles/paths
require - will produce a fatal error (E_COMPILE_ERROR) and stop the script
include - will only produce a warning (E_WARNING) and the script will continue
include 'filename';
or
require 'filename';
// https://www.php.net/manual/en/function.include-once.php
include_once
require_once // difference being that if the code from a file has already been included, it will not be included again, and returns TRUE.
// ############## work ftp ############## //
https://www.php.net/manual/ro/function.ftp-connect.php
// my function upload file to ftp, upload ftp,
define( "FTP_SERVER", '' );
define( "FTP_USER_NAME", '' );
define( "FTP_USER_PASS", '' );
function upload_to_ftp( $file_for_send = '', $file_name_for_upload = '' ) {
// create connection
$ftp_conn = ftp_connect( FTP_SERVER ) or die( "Could not connect to FTP_SERVER" );
$login = ftp_login( $ftp_conn, FTP_USER_NAME, FTP_USER_PASS );
// upload file
if ( ftp_put( $ftp_conn, $file_name_for_upload, $file_for_send, FTP_ASCII ) ) {
$response = "Successfully uploaded $file_for_send";
} else {
$response = "Error uploading $file_for_send";
}
// close connection
ftp_close( $ftp_conn );
return $response;
}
// my func
function upload_to_ftp( $file_for_send = '', $file_name = '' ) {
// create connection
$ftp_conn = ftp_connect( FTP_SERVER, FTP_PORT ) or die( "Could not connect to FTP_SERVER" );
if ($ftp_conn){
$login_result = ftp_login( $ftp_conn, FTP_USER_NAME, FTP_USER_PASS );
if ($login_result){
// turn passive mode on
ftp_pasv($ftp_conn, true);
if ( ftp_put( $ftp_conn, $file_name, $file_for_send, FTP_BINARY ) ) {
$response = "uploaded";
} else {
$response = "ftp_error";
}
} else {
$response = 'FTP Login Error';
}
} else {
$response = $ftp_conn;
}
// close connection
ftp_close( $ftp_conn );
return $response;
}
// ------------- work filter ------------- //
https://www.w3schools.com/php/func_filter_var.asp
// ------------- work API, send and get responses, work services, work url ------------- //
/*
* https://www.php.net/manual/en/wrappers.php.php
*/
php:// — Accessing various I/O streams
// Example of get RAW data from POST query
file_get_contents( 'php://input' ) // put this in file wich we get answer
$data = json_decode( file_get_contents( 'php://input' ), true );
https://www.php.net/manual/en/function.parse-url.php
parse_url() - Parse a URL and return its components
// ------------- work Mails ------------- //
/*
*
*
*
*/
// Send Mail function
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if ( mail($to, $subject, $message, $headers)) {
echo "Message sent succesfully.";
} else {
echo "There was a problem while sending E-Mail.";
}
// PHPMailer class
site https://github.com/PHPMailer/PHPMailer#installation--loading
/**
* This example shows sending a message using PHP's mail() function.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php'; //If need smtp
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer mail() test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
// $mail->msgHTML(file_get_contents('contents.html'), __DIR__);
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('file.jpg');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
// ------------- work datatime, data time ------------- //
/*
*
https://www.php.net/manual/en/function.date.php
https://www.php.net/manual/en/timezones.europe.php
*
*/
date() - Format a local time/date Returns a string formatted according to the given format
string using the given integer timestamp or the current time if no timestamp is given.
In other words, timestamp is optional and defaults to the value of time().
gmdate() - Format a GMT/UTC date/time
idate() - Format a local time/date as integer
getdate() - Get date/time information
getlastmod() - Gets time of last page modification
mktime() - Get Unix timestamp for a date
strftime() - Format a local time/date according to locale settings
time() - Return current Unix timestamp
strtotime() - Parse about any English textual datetime description into a Unix timestamp
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
date_default_timezone_set('Europe/Chisinau');
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
// examples
echo date( 'Y' );
// ------------- work DB, work database, work with databases, work databases ------------- //
// about drivers and PDO API
// https://www.php.net/manual/en/mysqli.overview.php#:~:text=An%20Application%20Programming%20Interface%2C%20or,usually%20exposed%20via%20PHP%20extensions.
// MySQLi Object-oriented
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Quick check db connection
$link = mysqli_connect('localhost', 'user', 'password', 'dbname');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($link);
//--> PDO
// interesting reading about PDO
https://www.cluedapp.co.za/php-pdo-with-mysql-postgresql-or-sqlite/
// issues
// issues if 'could not find driver' error msg
// write this in 'php.ini' file
extension=pdo_mysql
// write in console to find driver
php -m | grep pdo_mysql
// install driver thrue terminal
sudo apt-get install php7.4-mysql
// connection example
$host = 'localhost'; // replace with your host name
$dbname = 'database_name'; // replace with your database name
$username = 'root'; // replace with your database username
$password = 'password'; // replace with your database password
// create PDO instance
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// ------------- work Cookies ------------- //
/*
*
*
*
*/
//See the cookie
echo '<pre>';
print_r( $_COOKIE );
echo '</pre>';
// Insert HTML in function
function price_table_view(){
ob_start(); ?>
<?php return ob_get_clean();
}
// ------------- work cURL ------------- //
/*
* https://www.php.net/manual/en/ref.curl.php
*/
// cURL Functions
curl_close() — Close a cURL session
curl_copy_handle() — Copy a cURL handle along with all of its preferences
curl_errno() — Return the last error number
curl_error() — Return a string containing the last error for the current session
curl_escape() — URL encodes the given string
curl_exec() — Perform a cURL session
curl_file_create() — Create a CURLFile object
curl_getinfo() — Get information regarding a specific transfer
curl_init() — Initialize a cURL session
curl_multi_add_handle() — Add a normal cURL handle to a cURL multi handle
curl_multi_close() — Close a set of cURL handles
curl_multi_errno() — Return the last multi curl error number
curl_multi_exec() — Run the sub-connections of the current cURL handle
curl_multi_getcontent() — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
curl_multi_info_read() — Get information about the current transfers
curl_multi_init() — Returns a new cURL multi handle
curl_multi_remove_handle() — Remove a multi handle from a set of cURL handles
curl_multi_select() — Wait for activity on any curl_multi connection
curl_multi_setopt() — Set an option for the cURL multi handle
curl_multi_strerror() — Return string describing error code
curl_pause() — Pause and unpause a connection
curl_reset() — Reset all options of a libcurl session handle
curl_setopt_array() — Set multiple options for a cURL transfer
curl_setopt() — Set an option for a cURL transfer
curl_share_close() — Close a cURL share handle
curl_share_errno() — Return the last share curl error number
curl_share_init() — Initialize a cURL share handle
curl_share_setopt() — Set an option for a cURL share handle
curl_share_strerror() — Return string describing the given error code
curl_strerror() — Return string describing the given error code
curl_unescape() — Decodes the given URL encoded string
curl_version() — Gets cURL version information
// cURL Work Example
https://www.php.net/manual/en/curl.examples-basic.php
// create curl resource, initialize a cURL session
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// useful functions
// php.net/manual/en/function.http-build-query.php
http_build_query() - Generate URL-encoded query string
json_encode() - Returns the JSON representation of a value
json_decode() - Decodes a JSON string
https://www.php.net/manual/en/function.urlencode.php
urlencode() - URL-encodes string // This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.
// example with json
$query_values = json_encode($query_values);
//debug($query_values);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $query_values ));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_values);
curl_setopt($ch, CURLOPT_URL, 'url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Type: application/json",
)
);
$server_output = curl_exec($ch);
$response = json_decode($server_output, true);
// Result Output
// debug($server_output);
curl_close($ch);
return $response;
}
// example from Udemy
// Github Test for API testing
https://docs.github.com/en/rest/activity/events?apiVersion=2022-11-28#list-public-events-for-a-user
// const API_ADDR = 'https://randomuser.me/api';
//const API_ADDR = 'https://api.unsplash.com/photos/random';
//const API_ADDR = 'https://api.github.com/user/starred/httpie/httpie';
//const API_ADDR = 'https://api.github.com/user/josanua/wpforpro_underscore';
//const API_ADDR = 'https://api.github.com/repos/josanua/php-photogallery-oop/branches';
const API_ADDR = 'https://api.github.com/gists';
$curlSession = curl_init();
$headers = [
// "Authorization: Client-ID 7r06Y5mNPA32P0p-jvRIXr7dKhs3U"
// for Github authorization procedure
"Authorization: Client-ID ",
"Accept: application/vnd.github+json",
// "User-Agent: josanua"
];
// single steps methods
// curl_setopt($curlSession, CURLOPT_URL, API_ADDR);
// curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
// array method
curl_setopt_array($curlSession, [
CURLOPT_URL => API_ADDR,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
// CURLOPT_HEADER => true,
CURLOPT_USERAGENT => "josanua",
// CURLOPT_CUSTOMREQUEST => "GET" // HTTP verbs
]);
$response = curl_exec($curlSession);
$statusCode = curl_getinfo($curlSession, CURLINFO_HTTP_CODE);
//$contentType = curl_getinfo($curlSession, CURLINFO_CONTENT_TYPE);
//$contentLength = curl_getinfo($curlSession, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($curlSession);
var_dump($statusCode);
var_dump($response);
// work with query
// clean address from url params
// url 'api/tasks?page=1' will be '/api/tasks'
echo parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
// create an array with path parts
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$parts = explode("/", $path);
// examples with response code
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$parts = explode("/", $path);
$resource = $parts[2];
$id = $parts[3] ?? null;
echo $resource. ", ";
echo $_SERVER["REQUEST_METHOD"];
// create response codes
if($resource != 'tasks') {
// header("HTTP/1.1 404 Not Found");
http_response_code(404); // recommended way to use response codes
exit;
}
// ------------- Miscellaneous (diferite) ------------- //
/*
*
*
*
*/
// check parity, even or odd, paritatea numarului
if ($number % 2 == 0) {
print "It's even";
}
//---- More complicated and usefful methods ----//
// Unzip a fille
$zip = new ZipArchive;
if ($zip->open('archive.zip') === TRUE) {
$zip->extractTo('.');
$zip->close();
echo 'ok';
}
else {
echo 'file not found';
}
// AntiSpam method (Honey Pot) - if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// then send the form to your email
mail( '[email protected]', 'Contact Form', print_r($_POST,true) );
}
// otherwise, let the spammer think that they got their message through
// Generator cifre, patrat cu pas
function squares ($start, $end, $step = 1 ){
for ($i = $start; $i <= $end; $i += $step){
yield $i*$i; // yield in loc de echo
}
}
foreach (squares(1, 10) as $n){
echo $n . " ";
}
// ------------- Libraries ------------- //
/*
* Useful libraries
*/
// Create PDF, generate pdf
// domPDF is an HTML to PDF Converter, (simple and good),
https://github.com/dompdf/dompdf
// check ssl, work ssl
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
// SSL connection
}
// ------------- work errors ------------- //
/*
*
*
*
*/
// Notice "Undefined offset: 0"
https://www.geeksforgeeks.org/how-to-avoid-undefined-offset-error-in-php/
if(isset($array[0])){
echo $array[0];
}
if(!empty($students[5])) {
echo $students[5];
}
// ------------- Encryption, coding, encrypt ------------- //
/*
* Data Encryption in PHP
*/
https://stackoverflow.com/questions/9262109/simplest-two-way-encryption-using-php
http://hgogonis.me/symmetric-encryption-php/
$pltxt = 'Data pentru criptare';
// $cipher_algo = 'aes-128-gcm';
// $cipher_algo = 'AES-256-CFB'; - error - doesn not support AEAD
$passphrase = 'test_key';
$ivlen = openssl_cipher_iv_length($cipher_algo);
$iv = openssl_random_pseudo_bytes($ivlen);
$encryptedText = openssl_encrypt($pltxt, $cipher_algo, $passphrase, $options=0, $iv, $tag);
echo $encryptedText . "\n";
// var_dump(openssl_encrypt($pltxt, $method, $key, OPENSSL_RAW_DATA, $iv ));
$original_plaintext = openssl_decrypt($encryptedText, $cipher_algo, $passphrase, $options=0, $iv, $tag);
echo $original_plaintext . "\n";
// ------------- work text------------- //
/*
* custom funcs to work with text data
*/
/*
* custom func truncate_text, truncate text
https://wp-mix.com/php-shorten-string-character-count/
$text – The text string that you want to shorten
$max – The maximum number of characters allowed (default = 50)
$append – The appended text (default = ellipses)
*/
function truncate_text($text, $max = 50, $append = '…') {
if (strlen($text) <= $max) return $text;
$return = substr($text, 0, $max);
if (strpos($text, ' ') === false) return $return . $append;
return preg_replace('/\w+$/', '', $return) . $append;
}
// ------------- Most common issues, errors ------------- //
/*
* "Headers already sent" error in PHP
* https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php
*/
// ------------- Differences between JS and PHP in OOP ------------- //
// --> Java Script
// Define a parent class
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log("The animal makes a sound");
}
}
// Define a child class that extends the parent class
class Dog extends Animal {
constructor(name) {
super(name);
}
makeSound() {
console.log("The dog barks");
}
}
// Create a new instance of the child class
const myDog = new Dog("Fido");
// Call a method on the instance
myDog.makeSound(); // Outputs "The dog barks"
// --> PHP
// Define a parent class
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
echo "The animal makes a sound\n";
}
}
// Define a child class that extends the parent class
class Dog extends Animal {
public function __construct($name) {
parent::__construct($name);
}
public function makeSound() {
echo "The dog barks\n";
}
}
// Create a new instance of the child class
$myDog = new Dog("Fido");
// Call a method on the instance
$myDog->makeSound(); // Outputs "The dog barks"
In this example, we define a parent class called Animal with a constructor method and a makeSound method.
We then define a child class called Dog that extends the Animal class and overrides the makeSound method with its own implementation.
We create a new instance of the Dog class called $myDog and call the makeSound method on it, which outputs "The dog barks".
// Note here
Note that in PHP, we use the protected access modifier to make the $name property accessible within the class and its subclasses.
We also use the parent::__construct() method to call the parent constructor from within the child constructor.
// ------------- work Composer ------------- //
//--> about env
https://www.php.net/manual/en/reserved.variables.environment.php
// connect env file, .env
// $_ENV
// env in WP
// https://erikpoehler.com/2020/12/30/using-an-env-file-for-database-and-other-credentials/
// composer autoload
// some basic info
https://www.youtube.com/watch?v=NLXtGZ6Ilsw
// create/include files in autoload
// 1. create composer.json file
{
"autoload": {
"psr-4": {
"" : "foldername/"
}
}
}
// 2. execute composer dump-autoload in terminal in main folder
// testing code
class Cars {
public $wheel_count = 4;
private $door_count = 4;
protected $seat_count = 2;
function car_detail() {
echo $this->wheel_count;
echo $this->door_count;
echo $this->seat_count;
// return "This car have " . $this->wheel_count . " wheels";
}
}
$bmw = new Cars();
//$bmw->wheel_count = 6;
$bmw->car_detail();
//echo Cars::$wheel_count;
// ------------- Miscellaneous ------------- //
// check php version, get php version
// bails if PHP version is lower than required
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
// add admin notice here
return;
}
// ------------- work requests, request uri, work url ------------- //
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Allow
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
// Get or Set the HTTP response code
http_response_code(int $response_code = 0): int|bool
// clean request path, parse url
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$parts = explode("/", $path);
$resource = $parts[2];
$id = $parts[3] ?? null;
// create response codes
if($resource != 'tasks') {
// header("HTTP/1.1 404 Not Found");
http_response_code(404); // recommended way to use response codes
exit;
}
// ------------- work error handler ------------- //
set_exception_handler("\\ErrorHandler::handleException");
https://www.php.net/manual/en/class.throwable.php
class ErrorHandler
{
public static function handleException(Throwable $exception): void
{
http_response_code(500);
echo json_encode([
"code" => $exception->getCode(),
"message" => $exception->getMessage(),
"file" => $exception->getFile(),
"line" => $exception->getLine()
]);
}
}
// ------------- work with databases, work databases ------------- //
PDO
// ------------- work with databases, work databases ------------- //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment