Is There Any Legitimate Use for Bare Strings in PHP

Is there any legitimate use for bare strings in PHP?

Nope, I can not see a single instance where it would make sense, and it always is dangerous. Using strings without quotes should absolutely be reserved to address constants. I don't understand how the inventors of PHP could decide to introduce this ridiculous behaviour at all - it makes the proper use of constants almost impossible (because if you try to access a constant that has not been defined, PHP will silently and stupidly generate a string) without giving any benefit.

Is there a better way to write HTML strings in PHP?

PHP knows several kinds of syntax to declare a string:

  • single quoted

    ' … '
  • double quoted

    " … "
  • heredoc syntax

    <<<DELIMITER

    DELIMITER
  • nowdoc syntax (since PHP 5.3.0)

    <<<'DELIMITER'

    DELIMITER

So you don’t have to use the double quotes per se.

Is it okay to use array[key] in PHP?

It is not considered as OK -- even if it will work in most cases.


Basically, when PHP sees this :

echo $array[key];

It will search for a constant, defined with define, called key -- and, if there is none, if will take the 'key' value.


But, if there is something like this earlier in your code :

define('key', 'glop');

It will not take

echo $array['key'];

anymore ; instead, it'll use the value of the key constant -- and your code will be the same as :

echo $array['glop'];


In the end, not putting quotes arround the key's name is bad for at least two reasons :

  • There is a risk that it will not do what you expect -- which is very bad

    • It might, today...
    • But what about next week / month / year ?
    • Maybe, one day, you'll define a constant with the wrong name ;-)
  • It's not good for performance :

    • it has to search for a constant, before using 'key'
    • And, as said in a comment, it generates notices (even if you disable error_reporting and display_errors, the notices/warnings/errors are still generated, even if discarded later)

So : you should not listen to that guy on this point : he is wrong : it does matter.


And if you need some "proof" that's "better" than what people can tell you on stackoverflow, you can point him to this section of the manual, as a reference : Why is $foo[bar] wrong?

How do I check if a string contains a specific word?

Now with PHP 8 you can do this using str_contains:

if (str_contains('How are you', 'are')) { 
echo 'true';
}

RFC

Before PHP 8

You can use the strpos() function which is used to find the occurrence of one string inside another one:

$haystack = 'How are you?';
$needle = 'are';

if (strpos($haystack, $needle) !== false) {
echo 'true';
}

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result); strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').

mysqli_real_escape_string, should I use it?

You should use prepared statements and pass string data as a parameter but you should not escape it.

This example is taken from the documentation:

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {

/* bind parameters for markers */
$stmt->bind_param("s", $city);

/* execute query */
$stmt->execute();

/* bind result variables */
$stmt->bind_result($district);

/* fetch value */
$stmt->fetch();

printf("%s is in district %s\n", $city, $district);

/* close statement */
$stmt->close();
}

Note that the example does not call mysqli_real_escape_string. You would only need to use mysqli_real_escape_string if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.

Related

  • How can I prevent SQL injection in PHP?

PHP Array key strings without quotation marks

How can you overcome the E_NOTICEs that complain that you forgot quotes around your strings?

Add quotes around your strings.

$_GET['mode']

Also it sounds like the error_reporting level on your local server is not sufficient. It should be high, so that you see these sorts of mistakes as you develop your website/application.

On your production server it may be set lower.

How can I change my php server settings so that writing $x[y] == $x['y']?

Unclear what you mean...

$x[y] 

and

$x['y'] 

is nothing to do with server settings

It's all about not having erroneous code.

$x[y] 

is looking to find a constant called y and if that constant doesn't exist, it warns you and tries again assuming that you mistyped and that y is a string with a value 'y' (the equivalent of)

$x['y'] 

Fix your code and use 'y' so that PHP doesn't have to guess what you mean, or issue warnings to tell you that you've done something wrong

PHP string functions: which ones will work with UTF-8?

Core PHP SBCS string functions

Assuming the default encoding of PHP is set to UTF-8, these string functions will work:

  • echo Output one or more strings
  • html_entity_decode Convert all HTML entities to their applicable characters
  • htmlentities Convert all applicable characters to HTML entities | better use
  • htmlspecialchars_decode Convert special HTML entities back to characters
  • htmlspecialchars Convert special characters to HTML entities
  • implode Join array elements with a string
  • join Alias of implode
  • nl2br Inserts HTML line breaks before all newlines in a string
  • print Output a string
  • quotemeta Quote meta characters
  • str_repeat Repeat a string
  • str_rot13 Perform the rot13 transform on a string
  • strip_tags Strip HTML and PHP tags from a string
  • stripcslashes Un-quote string quoted with addcslashes
  • stripslashes Un-quotes a quoted string

Unfortunately all other string functions do not work with UTF-8.
Obstacles:

  • case handling or spaces does not work with UTF-8
  • string lengths in parameters and return values are not in character lengths
  • string processing causes data corruption
  • string function is comletely ASCII oriented

In some cases functions can work as expected when parameters are US-ASCII and
lengths are byte lenghts.

Binary string function are still useful:

  • bin2hex Convert binary data into hexadecimal representation
  • chr Return a specific character (=byte)
  • convert_uudecode Decode a uuencoded string
  • convert_uuencode Uuencode a string
  • crc32 Calculates the crc32 polynomial of a string
  • crypt One-way string hashing
  • hex2bin Decodes a hexadecimally encoded binary string
  • md5_file Calculates the md5 hash of a given file
  • md5 Calculate the md5 hash of a string
  • ord Return ASCII value of character (=byte)
  • sha1_file Calculate the sha1 hash of a file
  • sha1 Calculate the sha1 hash of a string

Configuration functions do not apply:

  • get_html_translation_table Returns the translation table used by htmlspecialchars and htmlentities
  • localeconv Get numeric formatting information
  • nl_langinfo Query language and locale information
  • setlocale Set locale information

Regular expression functions and encoding and transcoding functions are not considered.

Extentions

In quite a few cases, Multibyte String
offers an UTF-8 variant:

  • mb_convert_case Perform case folding on a string
  • mb_parse_str Parse GET/POST/COOKIE data and set global variable
  • mb_split Split multibyte string using regular expression
  • mb_strcut Get part of string
  • mb_strimwidth Get truncated string with specified width
  • mb_stripos Finds position of first occurrence of a string within another, case insensitive
  • mb_stristr Finds first occurrence of a string within another, case insensitive
  • mb_strlen Get string length
  • mb_strpos Find position of first occurrence of string in a string
  • mb_strrchr Finds the last occurrence of a character in a string within another
  • mb_strrichr Finds the last occurrence of a character in a string within another, case insensitive
  • mb_strripos Finds position of last occurrence of a string within another, case insensitive
  • mb_strrpos Find position of last occurrence of a string in a string
  • mb_strstr Finds first occurrence of a string within another
  • mb_strtolower Make a string lowercase
  • mb_strtoupper Make a string uppercase
  • mb_strwidth Return width of string
  • mb_substr_count Count the number of substring occurrences
  • mb_substr Get part of string

And iconv provides a bare minimum of string functions:

  • iconv_strlen Returns the character count of string
  • iconv_strpos Finds position of first occurrence of a needle within a haystack
  • iconv_strrpos Finds the last occurrence of a needle within a haystack
  • iconv_substr Cut out part of a string

Lastly Intl has a lot of extra and powerful Unicode features (but no regular expressions) as part of i18n. Some features overlap with other string functions. With respect to string functions these are:

  • IntlBreakIterators
  • Grapheme Functions


Related Topics



Leave a reply



Submit