Broad Network


PHP Double Quoted String and Heredoc

PHP String with Security Considerations - Part 1

Foreword: In this part of the series, I talk about PHP Double Quoted String and what is known as HereDoc.

By: Chrysanthus Date Published: 29 Oct 2018

Introduction

This is part 1 of my series, PHP String with Security Considerations. In this part of the series, I talk about PHP Double Quoted String and what is known as HereDoc. You should have read the previous series before coming here, as this is the continuation.

A string is a series of characters. A Western European character occupies a space of 1 byte in the computer memory. A string literal is delimited by a pair of single quotes or a pair of double quotes. In this tutorial, we are concerned with double quoted strings.

Try the following code:

<?php

    $str = "I am a man of peace.";

    echo $str;

?>

String Access and Modification by Characters
The characters in a string are similar in their positions, to elements in an array. You can access each character using index in []. Remember, index counting begins from 0 (not 1). Try the following code:

<?php

    $str = "I like what I see.";

    echo $str, '<br>';

    echo $str[7], '<br>';

    $str[7] = "t";

    echo $str;

?>

The output is:

    I like what I see.
    w
    I like that I see.

The index is used just as with the array. You can use {} in place of [] here. Try the following:

<?php

    $str = "I like what I see.";

    echo $str, '<br>';

    echo $str{7}, '<br>';

    $str{7} = "t";

    echo $str;

?>

The output is the same.

If you use negative indices, you start accessing from the back of the string. The last character is for index, -1, since index zero is already for the first position; last-but-one character is for index, -2, third-to-the-last character for index, -3, and so on. Try the following code:

<?php


    $str = "I like what I see.";

    echo $str, '<br>';

    echo $str[-2], '<br>';

    $str[-2] = "t";

    echo $str;

?>

The output is:

I like what I see.
e
I like what I set.

Use of indexing to access characters in a string, has some issues. I will addres that at the end of this series.

Escaped Sequences
Escaped Sequences or Escaped Characters are special characters. A character here actually consists of two characters with the first one being the backslash. Common escaped sequences and their meanings are:

        Sequence     Note                 Description
        t                 horizontal tab     (HT, TAB)
        v                 vertical tab         (VT)
        n                 newline             (NL)
        r                 return                 (CR)
        f                 form feed             (FF)
        \                 backslash        
        $                 dollar sign        
        "                 double-quote

Any of these special characters will have some effect in the program or be replaced by the single character it represents.

Within a double quoted string, if you want double quote, use " . If you want single quote, just type the single quote, ' . If you type, ' you will get ' and not ' , from within a double quoted string.

Note: the character, { or } cannot be escaped in a double quoted string.

Try the following code:

<?php

    $str1 = "some text some" text.";
    $str2 = "some text some' text.";
    $str3 = "some text some' text.";
    $str4 = "some text {some} text.";
    $str5 = "some text {some} text.";

    echo $str1, '<br>';
    echo $str2, '<br>';
    echo $str3, '<br>';
    echo $str4, '<br>';
    echo $str5, '<br>';

?>

The output is:

    some text some" text.
    some text some' text.
    some text some' text.
    some text {some} text.
    some text {some} text.

Expansion of Variable
A variable within double quotes expands (is replaced by) to its value. Try the following code:

<?php

    $tf = 'twenty five';

    $str = "I will give you $tf apples.";

    echo $str;

?>

The output is:

    I will give you twenty five apples.

Variable Parsing
The word, parsing means changing something towards the final result. Again, in this tutorial we are dealing with double quoted strings.

Simple Syntax
The above variable expansion is of simple syntax. Try another code, which follows:

<?php

    $juice = "orange";

    echo "He drank some $juice juice.", '<br>';
    echo "He drank some juice made of $juices.";

?>

The output is:

    He drank some orange juice.
    He drank some juice made of .

Note that in the second line, the variable has not expanded. Within a string, the variable should not be followed by a character that can be part of the variable name. If that happens, the variable is replaced by NULL, which is not printed.

An array variable in double quotes is replaced by the word, Array, which is not the expansion you would have loved to get. However, the value of an array element, represented by the keyed variable (e.g. $juices[0]), is expanded to its value, within double quotes. Try the following:

<?php

    $juices = array("apple", "orange", "kind" => "strawberry");

    echo "He drank some $juices juice.", '<br>';
    echo '<br>';
    echo "He drank some $juices[0] juice.", '<br>';
    echo "He drank some $juices[1] juice.", '<br>';
    echo "He drank some $juices[kind] juice.", '<br>';

?>

Since the keyed array variables are in a string (quotes), the key, kind (in the last echo statement) should not be in quotes.

The output is:

    He drank some Array juice.

    He drank some apple juice.
    He drank some orange juice.
    He drank some strawberry juice.

Note the replacement of the array variable by the word, Array at the first output line.

It is not only keyed array variables that can be parsed within double quotes; object properties can also be parsed. Try the following:

<?php

    class people
        {
            public $john = "John Smith";
            public $jane = "Jane Bond";
            public $robert = "Robert Paulsen";
        }

    $person = new people();

    echo "Mr. $person->john has come.", '<br>';
    echo "Mr. $person->jane has come.", '<br>';
    echo "Mr. $person->robert's wife has come.", '<br>';

?>

The output is:

    Mr. John Smith has come.
    Mr. Jane Bond has come.
    Mr. Robert Paulsen's wife has come.

Note: Simple Syntax is when you have a scalar variable, a keyed array variable or an object property variable. An array variable (without key) within double quotes is replaced by the word, Array. An object variable (without property) causes a fatal error and the program stops running.

Complex Syntax
Simple syntax refers to scalar variables, keyed array variables and object property variables. Anything outside this is complex variable or curly variable.

Elaborated expressions can result in a value. You should have seen this with PHP operators. If you want an expression (simple or elaborated) to result in a value within double quotes, just enclose the expression with curly brackets.

Try the following code for scalar variables:

<?php

    $great = 'fantastic';
    echo "This is { $great}";

?>

The output is:

    This is { fantastic}

This output is wrong because there is a space between the opening curly bracket and the $ symbol that begins the variable. Try the following code where the space has been removed:

<?php

    $great = 'fantastic';
    echo "This is {$great}";

?>

The output is:

    This is fantastic

Correct result! There should be no space between the { and $ .

You can have simple keyed array variable wrapped in braces. Try the following:

<?php

    $juices = array("apple", "orange");

    echo "He drank some {$juices[1]} juice.";

?>

The output is:

    He drank some orange juice.

You can have simple object property variable wrapped in braces. Try the following:

<?php

    class people
        {
            public $john = "John Smith";
        }

    $person = new people();

    echo "Mr. {$person->john} has come.", '<br>';

?>

The output is:

    Mr. John Smith has come.

You must have an elaborated keyed array variable wrapped in braces. Try the following which involves a 2 dimensional array:

<?php

    $products = array("firstArticle" => array("name" => "Perfume"));

    echo "The name of the first article is {$products[firstArticle][name]}.";

?>

The output is:

    The name of the first article is Perfume.

You must have an elaborated object property variable wrapped in braces. Try the following where the value of a property is an array:

<?php

    class people
        {
            public $john = array("apple");
        }

    $person = new people();

    echo "John drank {$person->john[0]} juice.";

?>

The output is:

    John drank apple juice.

Heredoc
Assume that you are typing in a text editor. If you want more than one consecutive spaces, you press the keyboard spacebar the corresponding number of times. If you want a newline, you press the Enter key. If you want a number of consecutive newlines, you press the Enter key the corresponding number of times. The result is an overall formatting with spaces and newlines.

PHP can send this overall formatting to the console or a text editor file, but on condition that you use the heredoc syntax. This would also send the overall formatting to the web page at the browser, but the web page would not display consecutives spaces and it would not display newlines. This is because the web page needs but a number of “&nbsp;” for consecutive spaces and <br> for a new line.

The overall formatting can be seen in its entirety (all text) in the text editor page or the console.

Consider the following script:

<?php

    $str = <<<EOF
    some spaces    yes  space
a line and yes a line
    another line and         spaces
EOF;

    echo $str;

?>

The heredoc syntax begins with <<<. This is followed by an identifier without $ and without space, after it. The Enter key is pressed. The identifier may optionally be in double quotes. Then you type the string content giving any number of consecutives spaces you want and just pressing the Enter key at the end of each line. The last line of the syntax, is the same identifier, and should be typed at the beginning of the last line. Immediately after that you type a semicolon and then press the Enter key (no space before pressing the Enter key). So, the heredoc string has an opening identifier and a closing identifier, which are the same, e.g. EOF above.  You can choose any name you want for the identifier. The heredoc string above is assigned to the variable, $str. Choose any name for this variable. The variable content can be printed to the console. Read and try the above code, if you have not already done so.

Note: All the interpolation rules (expansion and replacement of escape sequence with effect) mentioned above, are applicable to heredoc.

That is it for this part of the series. We stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

NEXT

Comments