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
…
DELIMITERnowdoc 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
anddisplay_errors
, the notices/warnings/errors are still generated, even if discarded later)
- it has to search for a constant, before using
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_NOTICE
s 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 stringshtml_entity_decode
Convert all HTML entities to their applicable charactershtmlentities
Convert all applicable characters to HTML entities | better usehtmlspecialchars_decode
Convert special HTML entities back to charactershtmlspecialchars
Convert special characters to HTML entitiesimplode
Join array elements with a stringjoin
Alias of implodenl2br
Inserts HTML line breaks before all newlines in a stringprint
Output a stringquotemeta
Quote meta charactersstr_repeat
Repeat a stringstr_rot13
Perform the rot13 transform on a stringstrip_tags
Strip HTML and PHP tags from a stringstripcslashes
Un-quote string quoted with addcslashesstripslashes
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 representationchr
Return a specific character (=byte)convert_uudecode
Decode a uuencoded stringconvert_uuencode
Uuencode a stringcrc32
Calculates the crc32 polynomial of a stringcrypt
One-way string hashinghex2bin
Decodes a hexadecimally encoded binary stringmd5_file
Calculates the md5 hash of a given filemd5
Calculate the md5 hash of a stringord
Return ASCII value of character (=byte)sha1_file
Calculate the sha1 hash of a filesha1
Calculate the sha1 hash of a string
Configuration functions do not apply:
get_html_translation_table
Returns the translation table used by htmlspecialchars and htmlentitieslocaleconv
Get numeric formatting informationnl_langinfo
Query language and locale informationsetlocale
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 stringmb_parse_str
Parse GET/POST/COOKIE data and set global variablemb_split
Split multibyte string using regular expressionmb_strcut
Get part of stringmb_strimwidth
Get truncated string with specified widthmb_stripos
Finds position of first occurrence of a string within another, case insensitivemb_stristr
Finds first occurrence of a string within another, case insensitivemb_strlen
Get string lengthmb_strpos
Find position of first occurrence of string in a stringmb_strrchr
Finds the last occurrence of a character in a string within anothermb_strrichr
Finds the last occurrence of a character in a string within another, case insensitivemb_strripos
Finds position of last occurrence of a string within another, case insensitivemb_strrpos
Find position of last occurrence of a string in a stringmb_strstr
Finds first occurrence of a string within anothermb_strtolower
Make a string lowercasemb_strtoupper
Make a string uppercasemb_strwidth
Return width of stringmb_substr_count
Count the number of substring occurrencesmb_substr
Get part of string
And iconv provides a bare minimum of string functions:
iconv_strlen
Returns the character count of stringiconv_strpos
Finds position of first occurrence of a needle within a haystackiconv_strrpos
Finds the last occurrence of a needle within a haystackiconv_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
Extending Session Timeout in PHP via the .Htaccess
Woocommerce - Overriding Billing State and Post Code on Existing Checkout Fields
Download Multiple Files in One Http Request
Php: Change Color of Text Based on $Value
PHP Email - How to Avoid Mail Ending Up in Spam Box
Is There a Call_User_Func() Equivalent to Create a New Class Instance
Simulate PHP Array Language Construct or Parse with Regexp
How to Get Results from the Wikipedia API with PHP
In PHP What Does |= Mean, That Is Pipe Equals (Not Exclamation)
Remove Duplicates from an Array Based on Object Property
Using Mod_Rewrite with Xampp and Windows 7 - 64 Bit
Getimagesize() Not Returning False When It Should
How to Use a PHP Includes Across Multiple Directories/Sub Directories with Relative Paths
JavaScript Cookies VS PHP Cookies
Good Tutorial on How to Update Your MySQL Database with a PHP Form