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
Attempting to
include
a file that doesn’t exists will emit an E_WARNING. You can avoid that by usingfile_exists()
From the PHP manual (https://php.net/include):
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 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):
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).