Encoding/Escaping JSON Control Characters - php

I'm using MariaDB's COLUMN_JSON() function. As this bug illustrates, the function properly escapes double quotes, but not other characters that should be encoded/escaped.
Here's a silly example query to demonstrate how the JSON column is created.
SELECT CONCAT('[', GROUP_CONCAT(COLUMN_JSON(COLUMN_CREATE(
'name', `name`,
'value', `value`
)) SEPARATOR ','), ']') AS `json`
FROM `settings`
If the name or value contain invalid JSON characters, json_decode will fail.
I've written a PHP function to escape/encode the value that comes from the query, but it seems like there should be a better way.
/**
* Makes sure the JSON values built by COLUMN_JSON() in MariaDB are safe for json_decode()
* Assumes that double quotes are already escaped
*
* #param string $mysql_json
* #return string
*/
public static function jsonEscape($mysql_json)
{
$rtn = '';
for ($i = 0; $i < strlen($mysql_json); ++$i) {
$char = $mysql_json[$i];
if (($char === '\\') && ($mysql_json[$i + 1] !== '"')) {
// escape a backslash, but leave escaped double quotes intact
$rtn .= '\\\\';
} elseif (($ord = ord($char)) && ($ord < 32)) {
// hex encode control characters (below ASCII 32)
$rtn .= '\\u' . str_pad(dechex($ord), 4, '0', STR_PAD_LEFT);
} else {
$rtn .= $char;
}
}
return $rtn;
}
Examine the string character-by-character like this doesn't perform well. Perhaps there's a string replacement or regular expression that would be more performant?

Based on a comment from Halcyon, I switched to a str_replace() solution, and it performs much better! The performance difference between trim(json_encode(13), '"') and '\\u' . str_pad(dechex(13), 4, '0', STR_PAD_LEFT) is just barely better, but it makes the intent more clear.
private static $json_replace_search;
private static $json_replace_replace;
/**
* Makes sure the JSON values built by GROUP_CONCAT() and COLUMN_JSON() in MariaDB are safe for json_decode()
* Assumes that double quotes are already escaped
*
* #param string $mysql_json
* #return string
*/
public static function jsonEscape($mysql_json)
{
if (is_null(self::$json_replace_search)) {
// initialize
self::$json_replace_search = [];
self::$json_replace_replace = [];
// set up all of the control characters (below ASCII 32)
for ($i = 0; $i < 32; ++$i) {
self::$json_replace_search[$i] = chr($i);
self::$json_replace_replace[$i] = trim(json_encode(self::$json_replace_search[$i]), '"');
}
}
// replace them
return str_replace(self::$json_replace_search, self::$json_replace_replace, $mysql_json);
}
/**
*
* #param string $mysql_json
* #return mixed
*/
public static function jsonDecode($mysql_json)
{
return json_decode(self::jsonEscape($mysql_json));
}

Related

PHP json Scanning escaped character

I am writing a JSONScanner class that basically takes a string and scans the whole thing to construct a JSONObject. Currently I'm writing read_string() method, to read a string. When reading a string that escapes '\', I get some invalid output.
Here is my JSONScanner class
class JSONScanner {
private $in;
private $pos;
public function __construct($in) {
$this->in = $in;
$this->pos = 0;
}
#########################################################
############### Method used for debugging ###############
#########################################################
public function display() {
$this->pos = 1;
echo $this->read_string($this->get_char());
}
#########################################################
#########################################################
private function read_string($quote) {
$str = "";
while(($c = $this->get_char()) != $quote) {
if($c == '\\') {
$str .= $this->get_escaped_char();
} else {
$str .= $c;
}
}
return $str;
}
private function get_escaped_char() {
$c = $this->get_char();
switch($c) {
case 'n':
return '\n';
case 't':
return '\t';
case 'r':
return '\r';
// display the characters being escaped
case '\\':
case '\'':
case '"':
default:
return $c;
}
}
private function get_char() {
if($this->pos >= strlen($this->in)) {
return -1; // END OF INPUT
}
return substr($this->in, $this->pos++, 1);
}
}
Here is my running code
$str = '{"a\\":1,"b":2}';
$jscan = new JSONScanner($str);
$jscan->display();
With the above string, I'm getting
a":1,
However when I try
$str = '{"a\\\":1,"b":2}';
$jscan = new JSONScanner($str);
$jscan->display();
I get what I need, which is
a\
Why am I needing to put 2 backslashes to escape 1 backslash?
EDIT:
I was trying the same json string on json_decode, and it gave me the same results, with 2 backslashes, nothing but with 3 backslahes it gave me a\. Why is that? Isn't escaping a backslash takes 2 consecutive ones \\?
$str = '{"a\\":1,"b":2}';
This is a PHP string literal, which has its own escaping rules. The actual string you're representing with the above is:
{"a\":1,"b":2}
If you want to represent one backslash in a PHP string literal, you need to write two backslashes. So the correct string representation for what you want is:
$str = '{"a\\\\":1,"b":2}';
It happens to work with three backslashes, because \\ becomes one \ and the next \ isn't followed by any special character, so it by itself also represents a single backslash.

PHP ldap_add function to escape ldap special characters in DN syntax

I'm trying to add some users to my Ldap DB but I get some errors (invalid dn syntax) when I use some special characters like ",.". I need a function that escape all characters. I try preg_quote but I get some errors in some cases.
Thanks in advance
Code:
$user = 'Test , Name S.L';
if(!(ldap_add($ds, "cn=" . $user . ",".LDAP_DN_BASE, $info))) {
include 'error_new_account.php';
}
EDIT Jan 2013: added support for escaping leading/trailing spaces in DN strings, per RFC 4514. Thanks to Eugenio for pointing out this issue.
EDIT 2014: I added this function to PHP 5.6. The code below is now a like-for-like drop-in replacement for earlier PHP versions.
if (!function_exists('ldap_escape')) {
define('LDAP_ESCAPE_FILTER', 0x01);
define('LDAP_ESCAPE_DN', 0x02);
/**
* #param string $subject The subject string
* #param string $ignore Set of characters to leave untouched
* #param int $flags Any combination of LDAP_ESCAPE_* flags to indicate the
* set(s) of characters to escape.
* #return string
*/
function ldap_escape($subject, $ignore = '', $flags = 0)
{
static $charMaps = array(
LDAP_ESCAPE_FILTER => array('\\', '*', '(', ')', "\x00"),
LDAP_ESCAPE_DN => array('\\', ',', '=', '+', '<', '>', ';', '"', '#'),
);
// Pre-process the char maps on first call
if (!isset($charMaps[0])) {
$charMaps[0] = array();
for ($i = 0; $i < 256; $i++) {
$charMaps[0][chr($i)] = sprintf('\\%02x', $i);;
}
for ($i = 0, $l = count($charMaps[LDAP_ESCAPE_FILTER]); $i < $l; $i++) {
$chr = $charMaps[LDAP_ESCAPE_FILTER][$i];
unset($charMaps[LDAP_ESCAPE_FILTER][$i]);
$charMaps[LDAP_ESCAPE_FILTER][$chr] = $charMaps[0][$chr];
}
for ($i = 0, $l = count($charMaps[LDAP_ESCAPE_DN]); $i < $l; $i++) {
$chr = $charMaps[LDAP_ESCAPE_DN][$i];
unset($charMaps[LDAP_ESCAPE_DN][$i]);
$charMaps[LDAP_ESCAPE_DN][$chr] = $charMaps[0][$chr];
}
}
// Create the base char map to escape
$flags = (int)$flags;
$charMap = array();
if ($flags & LDAP_ESCAPE_FILTER) {
$charMap += $charMaps[LDAP_ESCAPE_FILTER];
}
if ($flags & LDAP_ESCAPE_DN) {
$charMap += $charMaps[LDAP_ESCAPE_DN];
}
if (!$charMap) {
$charMap = $charMaps[0];
}
// Remove any chars to ignore from the list
$ignore = (string)$ignore;
for ($i = 0, $l = strlen($ignore); $i < $l; $i++) {
unset($charMap[$ignore[$i]]);
}
// Do the main replacement
$result = strtr($subject, $charMap);
// Encode leading/trailing spaces if LDAP_ESCAPE_DN is passed
if ($flags & LDAP_ESCAPE_DN) {
if ($result[0] === ' ') {
$result = '\\20' . substr($result, 1);
}
if ($result[strlen($result) - 1] === ' ') {
$result = substr($result, 0, -1) . '\\20';
}
}
return $result;
}
}
So you would do:
$user = 'Test , Name S.L';
$cn = ldap_escape($user, '', LDAP_ESCAPE_DN);
if (!ldap_add($ds, "cn={$cn}," . LDAP_DN_BASE, $info)) {
include 'error_new_account.php';
}
PHP 5.6 Beta released ldap_escape() function recently and it is in effect, However, this version is not production ready at present, you can very use it for your development purposes as of now.
Just a heads up if your not on PHP 5.6 yet, you can mirror the exact PHP 5.6 function ldap_escape() using the methods I created below, keep in mind this is meant for use in a class. The above answer doesn't perform exactly like the ldap_escape function, as in it doesn't escape all characters into a hex string if no flags have been given, so this would be more suitable for a drop in replacement for earlier versions of PHP, in an object oriented way.
I've documented every line for an easier understanding on whats going on. Scroll down for output.
Methods (Compatible with PHP 5 or greater):
/**
* Escapes the inserted value for LDAP.
*
* #param string $value The value to escape
* #param string $ignore The characters to ignore
* #param int $flags The PHP flag to use
*
* #return bool|string
*/
public function escapeManual($value, $ignore = '*', $flags = 0)
{
/*
* If a flag was supplied, we'll send the value
* off to be escaped using the PHP flag values
* and return the result.
*/
if($flags) {
return $this->escapeWithFlags($value, $ignore, $flags);
}
// Convert ignore string into an array
$ignores = str_split($ignore);
// Convert the value to a hex string
$hex = bin2hex($value);
/*
* Separate the string, with the hex length of 2,
* and place a backslash on the end of each section
*/
$value = chunk_split($hex, 2, "\\");
/*
* We'll append a backslash at the front of the string
* and remove the ending backslash of the string
*/
$value = "\\" . substr($value, 0, -1);
// Go through each character to ignore
foreach($ignores as $charToIgnore)
{
// Convert the characterToIgnore to a hex
$hexed = bin2hex($charToIgnore);
// Replace the hexed variant with the original character
$value = str_replace("\\" . $hexed, $charToIgnore, $value);
}
// Finally we can return the escaped value
return $value;
}
/**
* Escapes the inserted value with flags. Supplying either 1
* or 2 into the flags parameter will escape only certain values
*
*
* #param string $value The value to escape
* #param string $ignore The characters to ignore
* #param int $flags The PHP flag to use
* #return bool|string
*/
public function escapeWithFlags($value, $ignore = '*', $flags = 0)
{
// Convert ignore string into an array
$ignores = str_split($ignore);
$escapeFilter = ['\\', '*', '(', ')'];
$escapeDn = ['\\', ',', '=', '+', '<', '>', ';', '"', '#'];
switch($flags)
{
case 1:
// Int 1 equals to LDAP_ESCAPE_FILTER
$escapes = $escapeFilter;
break;
case 2:
// Int 2 equals to LDAP_ESCAPE_DN
$escapes = $escapeDn;
break;
case 3:
// If both LDAP_ESCAPE_FILTER and LDAP_ESCAPE_DN are used
$escapes = array_merge($escapeFilter, $escapeDn);
break;
default:
// Customize your own default return value
return false;
}
foreach($escapes as $escape)
{
// Make sure the escaped value isn't inside the ignore array
if( ! in_array($escape, $ignores))
{
$hexed = chunk_split(bin2hex($escape), 2, "\\");
$hexed = "\\" . substr($hexed, 0, -1);
$value = str_replace($escape, $hexed, $value);
}
}
return $value;
}
Tests (be aware that LDAP_ESCAPE constants are only available in PHP 5.6):
// Value to escape
$value = 'testing=+<>"";:#()*\x00';
$php = ldap_escape($value, $ignore = '*');
$man = $this->escapeManual($value, $ignore = '*');
echo $php; // \74\65\73\74\69\6e\67\3d\2b\3c\3e\22\22\3b\3a\23\28\29*\5c\78\30\30
echo $man; // \74\65\73\74\69\6e\67\3d\2b\3c\3e\22\22\3b\3a\23\28\29*\5c\78\30\30
$php = ldap_escape($value, $ignore = '*', LDAP_ESCAPE_DN);
$man = $this->escapeManual($value, $ignore = '*', LDAP_ESCAPE_DN);
echo $php; // testing\3d\2b\3c\3e\22\22\3b:\23()*\5cx00
echo $man; // testing\3d\2b\3c\3e\22\22\3b:\23()*\5cx00
$php = ldap_escape($value, $ignore = '*', LDAP_ESCAPE_FILTER);
$man = $this->escapeManual($value, $ignore = '*', LDAP_ESCAPE_FILTER);
echo $php; // testing=+<>"";:#\28\29*\5cx00
echo $man; // testing=+<>"";:#\28\29*\5cx00
Github Gist link: https://gist.github.com/stevebauman/0db9b5daa414d60fc266
Those characters must escaped to be part of the data of a distinguished name or relative distinguished name. Escape the character (as in all LDAP) with a backslash 2 hex digit, such as \2a. Anything else would not be in compliance with the standards body documents. See RFC4514 for more specific information regarding the string representation of distinguished names.

Prevent quoting of certain values with PHP json_encode()

When using PHP's json_encode to encode an array as a JSON string, is there any way at all to prevent the function from quoting specific values in the returned string? The reason I ask is because I need javascript to interpret certain values in the object as actual variable names, for example the name of an existing javascript function.
My end goal is to use the outputted json as the configuration object for an ExtJS Menu component, so the fact that everything gets quoted prevents me from successfully setting such properties as "handler" (click event handler function) of the child items arrays.
What we do is (and that's what Zend_Json::encode() does too), is to use a special marker class that encapsulates Javascript expressions in a special class. The encoding then walks recursively through our array-to-be-encoded, replaces all marker instances with some string. After using the built-in json_encode() we simply do a string replace to replace each special string with the __toString() value of the respective marker instance.
You can either use Zend_Json directly (if that's possible) or check how they do it and adapt the code to your needs.
Bill's function almost worked, it just needed the is_assoc() function added.
But while I was sorting this out, I cleaned it up a bit. This seems to work quite well for me:
<?php
/**
* JSObject class.
*/
class JSObject {
var $jsexp = 'JSEXP:';
/**
* is_assoc function.
*
* Determines whether or not the object is an associative array
*
* #access public
* #param mixed $arr
* #return boolean
*/
function is_assoc($arr) {
return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
}
/**
* Encode object
*
* Encodes the object as a json string, parsing out items that were flagged as objects so that they are not wrapped in double quotes.
*
* #param array $properties
* #return string
*/
function encode($properties = array()) {
$is_assoc = $this->is_assoc($properties);
$enc_left = $is_assoc ? '{' : '[';
$enc_right = $is_assoc ? '}' : ']';
$outputArray = array();
foreach ($properties as $prop => $value) {
if ((is_array($value) && !empty($value)) || (is_string($value) && strlen(trim(str_replace($this->jsexp, '', $value))) > 0) || is_int($value) || is_float($value) || is_bool($value)) {
$output = (is_string($prop)) ? $prop.': ' : '';
if (is_array($value)) {
$output .= $this->encode($value);
}
else if (is_string($value)) {
$output .= (substr($value, 0, strlen($this->jsexp)) == $this->jsexp) ? substr($value, strlen($this->jsexp)) : json_encode($value);
}
else {
$output .= json_encode($value);
}
$outputArray[] = $output;
}
}
$fullOutput = implode(', ', $outputArray);
return $enc_left . $fullOutput . $enc_right;
}
/**
* JS expression
*
* Prefixes a string with the JS expression flag
* Strings with this flag will not be quoted by encode() so they are evaluated as expressions
*
* #param string $str
* #return string
*/
function js($str) {
return $this->jsexp.$str;
}
}
No, json_encode can't do that. You need to construct your JS expression by hand then:
$json = "{'special':" . json_encode($string) . " + js_var,"
. "'value': 123}";
(Try to still use json_encode for fixed value parts, like in above example.)
The json_encode function does not provide any functionality for controlling the quotes. The quotes are also necessary for JavaScript to properly form the object on the JavaScript side.
In order to use the returned value to construct an object on the JavaScript side, use the json_encoded string to set flags in your association.
For example:
json_encode( array( "click_handler"=> "FOO" ) );
JavaScript side in the AJAX:
if( json.click_handler == "FOO" ) {
json.click_handler = Your_Handler;
}
After these steps you can pass your object off somewhere.
my quickfix was this:
$myobject->withquotes = 'mystring';
$myobject->withoutquotes = '##noquote## mystring ##noquote##';
and later
str_replace(array('"##noquote## ', ' ##noquote##"'), '', json_encode($myobject))
result is something like this
{"withquotes":"mystring","withoutquotes":mystring}
This is what I ended up doing, which is pretty close to what Stefan suggested above I think:
class JSObject
{
var $jsexp = 'JSEXP:';
/**
* Encode object
*
*
* #param array $properties
* #return string
*/
function encode($properties=array())
{
$output = '';
$enc_left = $this->is_assoc($properties) ? '{' : '[';
$enc_right = ($enc_left == '{') ? '}' : ']';
foreach($properties as $prop => $value)
{
//map 'true' and 'false' string values to their boolean equivalent
if($value === 'true') { $value = true; }
if($value === 'false') { $value = false; }
if((is_array($value) && !empty($value)) || (is_string($value) && strlen(trim(str_replace($this->jsexp, '', $value))) > 0) || is_int($value) || is_float($value) || is_bool($value))
{
$output .= (is_string($prop)) ? $prop.': ' : '';
if(is_array($value))
{
$output .= $this->encode($value);
}
else if(is_string($value))
{
$output .= (substr($value, 0, strlen($this->jsexp)) == $this->jsexp) ? substr($value, strlen($this->jsexp)) : '\''.$value.'\'';
}
else if(is_bool($value))
{
$output .= ($value ? 'true' : 'false');
}
else
{
$output .= $value;
}
$output .= ',';
}
}
$output = rtrim($output, ',');
return $enc_left.$output.$enc_right;
}
/**
* JS expression
*
* Prefixes a string with the JS expression flag
* Strings with this flag will not be quoted by encode() so they are evaluated as expressions
*
* #param string $str
* #return string
*/
function js($str)
{
return $this->jsexp.$str;
}
}
Following the lead of Stefan Gehrig I put this rough little class together. Example below. One must remember to use the serialize method if one has used the mark method, otherwise the markers will persist in the final json.
class json_extended {
public static function mark_for_preservation($str) {
return 'OINK' . $str . 'OINK'; // now the oinks will be next to the double quotes
}
public static function serialize($stuff) {
$json = json_encode($stuff);
$json = str_replace(array('"OINK', 'OINK"'), '', $json);
return $json;
}
}
$js_arguments['submitHandler'] = json_extended::mark_for_preservation('handle_submit');
<script>
$("form").validate(<?=json_extended::serialize($js_arguments)?>);
// produces: $("form").validate({"submitHandler":handle_submit});
function handle_submit() {alert( 'Yay, pigs!'); }
</script>

PHP Like thing similar to MySQL Like, for if statement?

I want an if statement that uses same thingy like mysql something LIKE '%something%'
I want to build an if statement in php.
if ($something is like %$somethingother%)
Is it possible?
The reason for me asking this question is that I don't want to change the MySQL command, it's a long page with many stuff on it, I don't want to build a different function for this.
Let me know if this is possible, if possible then how to do it .
if ($something is like %$somethingother%)
Is it possible?
no.
I don't want to change the MySQL command, it's a long page with many stuff on it
Use some good editor, that supports regular expressions in find & replace, and turn it to something like:
if(stripos($something, $somethingother) !== FALSE){
}
I know, this question isn't actual but I've solved similar problem :)
My solution:
/**
* SQL Like operator in PHP.
* Returns TRUE if match else FALSE.
* #param string $pattern
* #param string $subject
* #return bool
*/
function like_match($pattern, $subject)
{
$pattern = str_replace('%', '.*', preg_quote($pattern, '/'));
return (bool) preg_match("/^{$pattern}$/i", $subject);
}
Examples:
like_match('%uc%','Lucy'); //TRUE
like_match('%cy', 'Lucy'); //TRUE
like_match('lu%', 'Lucy'); //TRUE
like_match('%lu', 'Lucy'); //FALSE
like_match('cy%', 'Lucy'); //FALSE
look on strstr function
Use this function which works same like SQL LIKE operator but it will return boolean value and you can make your own condition with one more if statement
function like($str, $searchTerm) {
$searchTerm = strtolower($searchTerm);
$str = strtolower($str);
$pos = strpos($str, $searchTerm);
if ($pos === false)
return false;
else
return true;
}
$found = like('Apple', 'app'); //returns true
$notFound = like('Apple', 'lep'); //returns false
if($found){
// This will execute only when the text is like the desired string
}
Use function, that search string in another string like: strstr, strpos, substr_count.
strpos() is not working for so i have to use this preg_match()
$a = 'How are you?';
if (preg_match('/\bare\b/', $a)) {
echo 'true';
}
like in this e.g i am matching with word "are"
hope for someone it will be helpful
But you will have to give lowercase string then it will work fine.
Example of strstr function:
$myString = "Hello, world!";
echo strstr( $myString, "wor" ); // Displays 'world!'
echo ( strstr( $myString, "xyz" ) ? "Yes" : "No" ); // Displays 'No'
If you have access to a MySQL server, send a query like this with MySQLi:
$SQL="select case when '$Value' like '$Pattern' then 'True' else 'False' end as Result";
$Result=$MySQLi->query($SQL)->fetch_all(MYSQLI_ASSOC)[0]['Result'];
Result will be a string containing True or False. Let PHP do what it's good for and use SQL for likes.
I came across this requirement recently and came up with this:
/**
* Removes the diacritical marks from a string.
*
* Diacritical marks: {#link https://unicode-table.com/blocks/combining-diacritical-marks/}
*
* #param string $string The string from which to strip the diacritical marks.
* #return string Stripped string.
*/
function stripDiacriticalMarks(string $string): string
{
return preg_replace('/[\x{0300}-\x{036f}]/u', '', \Normalizer::normalize($string , \Normalizer::FORM_KD));
}
/**
* Checks if the string $haystack is like $needle, $needle can contain '%' and '_'
* characters which will behave as if used in a SQL LIKE condition. Character escaping
* is supported with '\'.
*
* #param string $haystack The string to check if it is like $needle.
* #param string $needle The string used to check if $haystack is like it.
* #param bool $ai Whether to check likeness in an accent-insensitive manner.
* #param bool $ci Whether to check likeness in a case-insensitive manner.
* #return bool True if $haystack is like $needle, otherwise, false.
*/
function like(string $haystack, string $needle, bool $ai = true, bool $ci = true): bool
{
if ($ai) {
$haystack = stripDiacriticalMarks($haystack);
$needle = stripDiacriticalMarks($needle);
}
$needle = preg_quote($needle, '/');
$tokens = [];
$needleLength = strlen($needle);
for ($i = 0; $i < $needleLength;) {
if ($needle[$i] === '\\') {
$i += 2;
if ($i < $needleLength) {
if ($needle[$i] === '\\') {
$tokens[] = '\\\\';
$i += 2;
} else {
$tokens[] = $needle[$i];
++$i;
}
} else {
$tokens[] = '\\\\';
}
} else {
switch ($needle[$i]) {
case '_':
$tokens[] = '.';
break;
case '%':
$tokens[] = '.*';
break;
default:
$tokens[] = $needle[$i];
break;
}
++$i;
}
}
return preg_match('/^' . implode($tokens) . '$/u' . ($ci ? 'i' : ''), $haystack) === 1;
}
/**
* Escapes a string in a way that `UString::like` will match it as-is, thus '%' and '_'
* would match a literal '%' and '_' respectively (and not behave as in a SQL LIKE
* condition).
*
* #param string $str The string to escape.
* #return string The escaped string.
*/
function escapeLike(string $str): string
{
return strtr($str, ['\\' => '\\\\', '%' => '\%', '_' => '\_']);
}
The code above is unicode aware to be able to catch cases like:
like('Hello 🙃', 'Hello _'); // true
like('Hello 🙃', '_e%o__'); // true
like('asdfas \\🙃H\\\\%🙃É\\l\\_🙃\\l\\o asdfasf', '%' . escapeLike('\\🙃h\\\\%🙃e\\l\\_🙃\\l\\o') . '%'); // true
You can try all of this on https://3v4l.org/O9LX0
I think it's worth mentioning the str_contains() function available in PHP 8 which performs a case-sensitive check indicating whether a string is contained within another string, returning true or false.
Example taken from the documentation:
$string = 'The lazy fox jumped over the fence';
if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
}
if (str_contains($string, 'Lazy')) {
echo 'The string "Lazy" was found in the string';
} else {
echo '"Lazy" was not found because the case does not match';
}
//The above will output:
//The string 'lazy' was found in the string
//"Lazy" was not found because the case does not match
See the full documentation here.
like_match() example is the best
this one witch SQL reqest is simple (I used it before), but works slowly then like_match() and exost database server resources when you iterate by array keys and every round hit db server with request usually not necessery. I made it faster ferst cutting / shrink array by pattern elements but regexp on array works always faster.
I like like_match() :)

Zend_Db_Select where() and Zend_Db_Adapter quoteInto()

Are Zend_Db_Select's where() method, when including the optional value to quite into, and Zend_Db_Adapte's quoteInto() methods basically the same as far as escaping SQL?
In other words, are these two pieces of quote identical and equally secure?
$select->where($this->getAdapter()->quoteInto('id = ?', 3));
$select->where(id = ?, 3);
Thanks!
Zend_Db_Select::_where() is using Zend_Db_Abstract::quoteInto() to quote the value(s) you specify as the second parameter in Zend_Db_Select::where() when assembling the sql string.
From line 983 of Zend_Db_Select:
/**
* Internal function for creating the where clause
*
* #param string $condition
* #param mixed $value optional
* #param string $type optional
* #param boolean $bool true = AND, false = OR
* #return string clause
*/
protected function _where($condition, $value = null, $type = null, $bool = true)
{
if (count($this->_parts[self::UNION])) {
require_once 'Zend/Db/Select/Exception.php';
throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION);
}
if ($value !== null) {
$condition = $this->_adapter->quoteInto($condition, $value, $type);
}
$cond = "";
if ($this->_parts[self::WHERE]) {
if ($bool === true) {
$cond = self::SQL_AND . ' ';
} else {
$cond = self::SQL_OR . ' ';
}
}
return $cond . "($condition)";
}
As I understand it where does this already so specifying it would be redundant.

Categories