skip to Main Content

I didn’t found a solution for my project on stack.

I’m using a php include txt file and i need a backup solution in my code.

For example:
My code is using Description.txt and if a client deletes this file i need to use the second file Description2.txt as a backup.

Something like this:

<php

? include Description.txt ! Description2.txt

# If file Description.txt no long exist, use Description2.txt as a backup.

?>

Thank you in advanced!

2

Answers


  1. Attempting to include a file that doesn’t exists will emit an E_WARNING. You can avoid that by using file_exists()

    If (file_exists('description.txt'))
        include 'description.txt'
    else
        include 'otherdescription.txt'
    
    Login or Signup to reply.
  2. 1 === (@include 'Description.txt') || (include 'Description2.txt');
    

    From the PHP manual (https://php.net/include):

    Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1.

    Some details as the expression may appear shy:

    • The include is not a function, but a language construct. As the example above forms a complex expression, it is within parenthesis.

    • Using || this way is a left-hand shorthand, PHP won’t execute the right-hand side if the left-hand side is true

    Written as an if clause:

    if (1 !== (@include 'Description.txt')) {
        include 'Description2.txt';
    }
    
    • If your customer not only deletes but also puts PHP code inside the file, anything is possible.

    • The @ error suppression operator will likely hide such circumstances, I only treat this kind of code as it is.


    Likely better for a .txt case (the same semantics otherwise apply):

    <pre><?= htmlspecialchars(
            @file_get_contents('Description.txt')
                ?: file_get_contents('Description2.txt')
    ) ?></pre>
    

    See https://php.net/file_get_contents (and the return value again) as well as for ?: the ternary operator ("It is possible to leave out the middle part of the ternary operator") that is able to do shorthand and return the value (here file contents).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search