Quick question, I have:
include_once("connection.php");
within my header and then on my internal pages I have:
<?php include 'header.php';?>
Do I still need to add:
include_once("connection.php");
on my internal pages? The reason I ask is: Right now I only have it within the header and sometimes my forms will save to the database and sometimes they will not. I'm just trying to find out what the best practice is.
No, includes are made "recursively".
FYI : "include" is faster than "include_once" because it doesn't check for included files
I usually do it manually, with a call to require() instead:
index.php
require("Config.php")
$c = Config();
Config.php
<?php
if(!DEFINED("CLASS_CONFIG_PHP__")) {
DEFINE("CLASS_CONFIG_PHP__", 1);
// All library code here
}
?>
This way, I'm sure everything is only defined once, and require will make sure the included file has no errors (will fail at that line if there are errors in it).
include_once() will include a file only once regardless of how many times you call it with the same parameter. include() will throw an error if its called twice with the same parameter.
if you have include('connection.php') in your header and all internal pages use this header then you wont need to include this in internal pages too.
However, it is bad practice to mix view layer with business logic layer. Read a bit on MVC patterns and how to use it. Connection should be done in a back end where all the database functions are called. Once header.php is called then you are in rendering mode and you should only be rendering content at that stage.
Related
My PhP files contain some long string constants and I'm trying to factor them out. So I created "my_string_constants.php" and used include in header.php. So far that works fine.
Now another file, page.php also requires the string constants and header.php. The scheme below tries to clarify these dependendies.
The string constants now seem available in my header only, not the rest of my page. I tried to resolve this by adding global ... to each string constant in string_constants.php. This resolved the error of "Unknown variable" but my string constants still seem unavailable to most of the page content.
What's the right way to get this working?
UPDATE
The issue's been solved. I should have used define(myString instead of $myString = .... By doing so, I need just one include in header.php and the constants will be available to page.php as well.
Thanks a million, you guys are great.
One thing you would want to do is distinguish a constant from a variable. Especially if other developers end up working on this, they will be confused by your terminology.
For constants, you do not need to declare them as global and they are defined like so:
define('MY_CONSTANT', 'Value');
It seems to me that the constants file is acting as your site wide configuration file, so to me, it makes sense to have that on every page, regardless of whether header is used or not. I would normally create a bootstrap file for this purpose.
bootstrap.php:
<?php
require_once(__DIR__ . '/constants.php');
require_once(__DIR__ . '/database.php');
require_once(__DIR__ . '/session.php');
You get the point, then every accessible page needs to include this bootstrap file and then possibly the header.
page.php:
<?php
require_once(__DIR__ . '/bootstrap/bootstrap.php');
require_once(__DIR__ . '/header.php');
?>
<h1>Page Title</h1>
In header.php, since it requires these constants, you can handle this in two ways, either check that the constants are defined (meaning, bootstrap was included first) or just use another require_once to make sure that file was loaded.
if (!defined('MY_CONSTANT')) exit('Bootstrap failure');
or
require_once(__DIR__ . '/bootstrap/constants.php');
Going to many directories or "files" deep regarding includes can really cause issues later when you are trying to debug. As a rule I try to only go one level deep in regards to including files. I.e. Create a folder called includes and place everything in there. If there is a file that needs multiple variables, functions etc, then include them in the needed pages at that point doing several includes like so:
<?php
include("includes/header.php");
includes("includes/functions.php");
?>
There are also other issues in regards to having multiple includes, like if you have sessions or cookies some LAMP stacks will require you to declare
session_start();
at the top of every page including all included php files that may need access to that session or cookie.
So to answer your question I believe the simplest solution would be to re-organize your site or script.
in the header page ontop u write
include 'header.php';
and in header.php you write
include 'my_string_constants.php';
so in this case the page.php calls the header and in the header the my_string_constants is being called...is this what you mean?
I don't use php very often and was wondering if someone could answer this question for me.
I have a folder structure like so:
-pages/rightCol.php
-pages/privacyPolicy.php
index.php
In my index file I have a connection to the database like this:
ob_start();
require($_SERVER['DOCUMENT_ROOT'] . "/inc/db.inc.php");
That works fine.
I wanted to separate out some repeated code between pages so I created the rightCol.php file. It needs the connection to the database. So right now I create a query result at the top of the index file and use the statement:
This works.
I also wanted to include it in the privacyPolicy.php page. This does not work because I do not want to put the query code at the top of every page that requires the rightCol.php file.
I would like to put the db stuff inside the rightCol.php. When I try this, then my privacyPolicy.php file works but then my index breaks. Probably because I require the db file twice, once at the top of the index and once in the rightCol.php file.
How can I set this up properly where I do not need to repeat code.
Thanks
EDIT
I changed my call to use require_once.
The privacyPolicy.php page works fine but when I view my index.php it has errors.
Error: No DB selected.
Include the db/inc.php only at the start of your index.php and open the connection. That way, it will stay open throughout the whole script. Then just close it at the very end of your site;
If you are having problem knowing where to include and not ( and still for some unknown reason want to include it more then once ), then get used to require_once method. This way the file will be included only once and the 2nd attempt will be ignored.
Well, the quick way to solve the problem is to use require_once. But i highly recommend that you use a micro-framework like Slim.
I have been trying to include a file in my template which includes some functions I was intending to use for validation of the access level a member has in order to tailor content for different types of users in Joomla 2.5. The trouble is even though I have used the standard PHP include statement, none of the functions appear to be usable in the template. Instead calling the functions causes any pages using the template to crash. I could hard code the functions at the top of the template which is working, but I also have plans to use some the functions elsewhere in my web application, so it makes sense to store them in an include file. Does anyone have some insight into why the functions do not work from an include, but do when added to the top of the template? The following is the top few lines of my template with the include statement:
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
JHtml::_('behavior.framework', true);
include ("/includes/checkAccess.php");
Please note the functions all work fine when hard-coded into the template, so it is definitely a problem with the include. Also, the include path above appears to be correct because if the include line above is added, the template still works fine unless a call is made to one of the functions it contains.
This certainly works if the folder "includes" is in the same directory
include(dirname(__FILE__)."/includes/checkAccess.php");
I have figured it out. The include path I had above was not correct even though it wasn't throwing an error (unless I called a function from the include). The following is correct and succeeds in pulling the functions through into the template:
include ("./includes/checkAccess.php");
You could include the functions inside a Joomla file which is already active on every page instead of the templates which usually read certain things and exclude others.
Is there a functions file Joomla already uses? You could include it at the bottom of that. Also make sure none of your variables or globals can conflict with Joomla, make sure they're all very much unique.
For access checks, I would use the build-in ACL (Access Control List).
Read more about ACL.
This has been on my mind for quite some time and I figured I should seek an answer from experts.
I want to know if it is a poor programming technique to funnel all PHP requests through a single file. I have been working on a website and not sure if it will scale with growth because I am not 100% certain of how PHP handles the include() function.
To better explain how I have build my quasi framework here is a snippet of my root .htaccess file:
# > Standard Settings
RewriteEngine On
# Ignore all media requests
RewriteRule ^media/ - [L]
# Funnel all requests into model
RewriteRule ^(.*)$ _model.php [QSA]
So everything except content within the media directory is passed into this single script.
Inside _model.php I have all my input sanitisation, user authentication, session data gets pulled from the database, any global variables (commonly used variables like $longTime, $longIP etc...) are set. Requests are routed via interpreting the $_SERVER["REQUEST_URI"] variable.
Essentially I have a switch() statement which chooses which module to include(). What I don't understand is: when PHP executes, will it execute every single include() regardless of whether or not the case directive is true?
I am concerned that after time I will have a lot of these modules - and if PHP does at runtime include all the modules it will end up occupying too much processing power and RAM...
--
Edit:
I am really just asking if PHP will 'read' all those files that it potentially might have to include. I know that it shouldn't actually execute the code.
If one of my include() is a 2GB file which takes a long time to process, will PHP always read over that file before executing?
--
Edit:
I have found another similar question (I did search a lot before posting this one)
PHP behavior of include/require inside conditional
I think I can close this off.
No, PHP will execute include in the moment the code fragment is reached.
This is quite important, because you can have php include file with code directly. E.g.
File1:
<?php echo "Foo"; ?>
File2:
<?php
echo "Before";
include("File1");
echo "After";
?>
Sometimes your PHP processor won't even know at compiletime which file to include. Imagine something like include("File".mt_rand(1,10));. PHP won't know the filename to include up to the very moment it reaches the include statement.
will PHP include the file even if the condition is not met?
No, include and require statements are interpreted and evaluated in the same way as other PHP statements. PHP does not scan the script for includes prior to executing.
This can be verified with a simple test:
if(false)
{
include('does_not_exist.php');
}
The above produces no error or warnings. If the include was read before execution, you would see a warning like:
Warning: include(does_not_exist.php): failed to open stream: No such file or directory ...
Warning: include(): Failed opening 'does_not_exist.php' for inclusion ...
Im loading the php rss parsing library simplepie onto my site and i include it in the header.php file like so:
<?php
// Make sure that SimplePie is loaded
require_once('inc/simplepie.inc');
$feed = new SimplePie('rss.com'); <-- This is a example url
// Make sure the content is being served out to the browser properly.
$feed->handle_content_type();
?>
Then i try to access the object from another page called page.php and it gives me this error:
Fatal error: Call to a member function get_items() on a non-object in /home/callofdu/public_html/wp-content/themes/Starkers/page.php on line 13
I get the error from this line of code:
<?php
foreach ($feed->get_items() as $item)
{}
?>
Its weird because if i include both of those chuncks of code together on the same php page it all works fine.
I just am not understanding something, please help.
Several things could be wrong here:
Code order is incorrect.
Realise that when you require or include a PHP file, the entire code of that file will be executed at that point. In other words: interpret the command require_once as "Insert file contents here", and check whether the order of lines of code are still right.
You are calling page.php in a separate request.
If you use your browser to manually surf to page.php after the completeion of the previous page, $feed will no longer exist. If you do want it to live on between requests, do the following:
a. Replace all instances of $feed with $_SESSION['feed']
b. In the first line of every file that you surf to (so not the require'd files), put session_start();
The require and include calls in php basically take the contents of that file and slap in place.
So if you follow the linear path that php taking while running a script, you have to make sure that the library is called before you use it.
Basically in practice, if you are executing page.php as a standalone then you will need to require it in that script also, however, if page.php is being included in the first script you mentioned then you don't need to require it again, but make sure the library is included before page.php
ie
<?php
// Make sure that SimplePie is loaded
require_once('inc/simplepie.inc');
$feed = new SimplePie('rss.com');
// Make sure the content is being served out to the browser properly.
$feed->handle_content_type();
require_once "page.php";
?>
doesn't need to be required in both
As for the differences between the require and include calls check out
http://www.php.net/manual/en/language.control-structures.php
EDIT:
After seeing this is Wordpress related, remember variable scoop. Variables do not inherent from a functions parent. So in page.php try:
<?php
global $feed;
foreach ($feed->get_items() as $item)
{}
?>
You need to include the libraries on EVERY page you're using the library's functions.
I think it is relative paths issue. Try using absolute paths. Or check if path to rss.com is okay. May be you need to call it in another way: $feed = new SimplePie('../rss.com');