I have a file with php and html codes mixed, like this:
echo "<tr class='somthing'>";
What is the best way to keep my php files with only php code?
php. Make sure you save the file to your "server's" document root directory. Typically this is the folder named "htdocs" in your Apache folder on Windows, or /Library/Webserver/Documents on Mac, but can be set by the user manually.
The best way to prevent direct access to files is to place them outside of the web-server document root (usually, one level above). You can still include them, but there is no possibility of someone accessing them through an http request.
The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.
There is some contention about this, so I will simply say that whatever you choose, stick with it.
Generally, you can use a templating system (e.g., Smarty) to keep your files formally clean of PHP code, but this has some drawbacks in the speed department.
Alternatively, you can use minimal code by breaking out the display related portions and using small PHP snippets therein, e.g.
<?php foreach ($myArray as $myElement): ?>
<tr>
<td><?php echo $myElement; ?></td>
</tr>
<?php endforeach; ?>
Of course this doesn't completely separate your code from your HTML, but that's nearly impossible to do for anything nontrivial; in my opinion, Smarty templates are just different code, not the absence of code. This approach is advocated by some frameworks such as codeigniter and Zend Framework (thought you can use them with Smarty as well, it is not the default).
One important thing to remember is that your display logic is just that: logic. Whatever method you choose, you will never be 100% free of code (or code-like markings which are interpreted by other code/applications) in the display until you use static-only displays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With