dreaming in PHP
PHP Pro Tips and Gotchas
-
Using the extract function on an associative array that has a key "this" will cause an error.
-
Use
+=
to append the values in one array to another without having to initalize a new variable.$oldArray += [ "some" => "thing" , "another" => "thing" ]
-
bindParam vs bindValue -> bindParam is byRef meaning the value of the variable can change after calling bindParam
-
LIKE expressions may expose a SQL Injection vulnerability
-
PDO:FETCH_CLASS will use __set() magic method when it encounters an undefined property. Properties are case-sensitive.
-
Autoloading classes is quick to implement, less error-prone than include/require, and does not have a significant impact on performance. Easy PSR-4 Implementation
-
PHP has integer literals, "not a number"(
NAN
), negative and positive infinity(INF
, -INF
), and min/max integer and float values.
-
Unserializing values can be dangerous because it"s so complicated.
-
Operator Precedence
- exponent
- types, increment, decrement
- multiplication, division, modulo
- addition, subtraction, string concatenation
- bit shift
- comparison
- equality, spaceship
- other bitwise operators (and, or, xor, not)
-
Some considerations for persistent connections are:
- Busy servers may exhaust max connection settings.
- Will only help on multi-threaded/process servers (IIS, Apache).
-
File Upload -- MAX_FILE_SIZE hidden input
- File uploads must be multipart/form-data.
-
Possible memory leaks -- long-running processes vulnerable
-
Rewriting output : ) can programmatically add vars to forms and urls = ) – CSRF Mitigation, filters, error messages, etc.
-
For benchmarks, use hrtime instead of microtime.
- The range function can be used to list each letter of the alphabet or range of characters.
- Checking isset on a hash set is much faster than in_array.
$a += 3
results in faster execution than $a = $a + 3
See this.
- The spaceship operator can be used for value object comparison.
- Be wary of incrementing/decrementing float constants. See this.
- Switch statements will execute the statement for each case <= target value if there is no break statement.
-
Switch statements may execute faster than a series of if statements. This is because the condition is evaluated only once and the result is compared to each case statement.
- A semicolon can be used instead of a colon after a case in a switch statement.
- Recursive function/ method calls with over 100-200 recursion levels can smash the stack and cause a termination of the current script. See this.
- Objects can be dynamically extended (given added behavior/functionality at-run-time) using Closure::bindTo
$this
is a psuedo-variable.
->
is called the Object Operator.
- Constructor methods are exempt from signature compatibility rules when extended.
- If you assign a closure/anonymous function to a property, you have to enclose it in parentheses to call it.
($obj->bar)();
- Constant expressions must be used to initialize a class property.
- Destructors | Be aware:
- Calling exit in a destructor will prevent other destructors from executing.
- The working directory in the script shutdown phase can be different with some SAPIs.
- Attempting to throw an exception from a destructor causes a fatal error.
- Classes of the same type can access each other"s private/protected members.
- Visibility of a classes members can be relaxed but not restricted.
- Scope Resolution Operator (::) is also known as Paamayim Nekudotayim.
- It"s possible to reference the class using a variable. The variable"s value can not be a keyword (e.g.
self
,
parent
and
static
).
- A type declaration is considered more specific in the following case:
- A type is removed from a union type.
- A class type is changed to a child class type.
- A float is changed to int.
-
Use the
extends
keyword to combine interfaces.
interface A {
public function foo();
}
interface B {
public function bar();
}
interface C extends A, B {
public function baz();
}
-
Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class"s protected properties or methods, the anonymous class can extend the outer class. To use the private properties of the outer class in the anonymous class, they must be passed through its constructor
-
Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace declarations, because such constructs are interpreted as relative namespace expressions.
- Methods can be declared as
final
.
- More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by
self::
,
parent::
,
static::
,
or, if going up in the class hierarchy, forward_static_call(). The function
get_called_class()
can be used to retrieve a string with the name of the called class and static::
introduces its scope.
- "Late static bindings" was named with an internal perspective in mind. "Late binding" comes from the fact that
static::
will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
- A reference is required to write to the same object property. Variables whose values are set to an object can read from the same properties.
- One notable interaction is between the finally block and a return statement. If a return statement is encountered inside either the try or the catch blocks, the finally block will still be executed. Moreover, the return statement is evaluated when encountered, but the result will be returned after the finally block is executed. Additionally, if the finally block also contains a return statement, the value from the finally block is returned.
- Exceptions cannot be cloned. Attempting to clone an
Exception
will result in a fatal E_ERROR
error.
- If you assign, pass, or return an undefined variable by reference, it will get created.
- If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function. You can avoid this by using the
$GLOBALS
array.
- References inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. In other words, the reference behavior of arrays is defined in an element-by-element basis; the reference behavior of individual elements is dissociated from the reference status of the array container.
function &collector() {
static $collection = [];
return $collection;
}
$collection = &collector();
$collection[] = "foo";
-
There are three scenarios where a
TypeError
may be thrown. The first is where the argument type being passed to a function does not match its corresponding declared parameter type. The second is where a value being returned from a function does not match the declared function return type. The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only)
-
User Submitted Data:
- Will this script only affect the intended files?
- Can unusual or undesirable data be acted upon?
- Can this script be used in unintended ways?
- Can this be used in conjunction with other scripts in a negative manner?
- Will any transactions be adequately logged?
Sessions
-
Use strict mode should be enabled for sessions.
- A user id can be prefixed to a session id. PHP >= 7.1.0.
- A timestamp should be used when generating a session id.
- Use read only sessions to mitigate DoS attacks.
Garbage Collection colors:
- Black
- In use or free.
- Grey
- Possible member of cycle.
- White
- Member of garbage cycle.
- Purple
- Possible root of cycle.
See this paper.
go back;