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.
Related
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.
I would like to include at the beginning of my script a PHP file that open a IF condition. Then i write my script, and to finish I include another PHP file that close the conditon.
This bring me to a "Parse error: syntax error, unexpected end of file in ..." error.
This will be better to understand with this simple example :
header.php
if(aConditionalTest()) {
footer.php
} // endIf
mypage.php
include_once 'header.php';
echo 'my awesome content';
include_once 'footer.php';
FYI: I would like to do this for example :
to check everywhere that a user is authorized before displaying the content
implement a webpage caching system (see http://www.phpfastcache.com/ in "Example" section, "Caching Whole Webpage")
THANKS!
edit : Explain more precisely WHY I want to do this for using phpfastcache :
http://www.phpfastcache.com/ says :
Caching Whole Webpage PHP Cache whole web page :
You can use phpFastCache to cache the whole webpage easy too. This is simple
example, but in real code, you should split it to 2 files:
cache_start.php and cache_end.php. The cache_start.php will store the
beginning code until ob_start(); and the cache_end.php will start from
GET HTML WEBPAGE. Then, your index.php will include cache_start.php on
beginning and cache_end.php at the end of file.
That's just what I try to do!
According to their piece of code below, this brings to the situation where the condition is opened in "cache_start.php" and then closed in "cache_end.php"
cache_start.php
use phpFastCache\CacheManager;
$cache = CacheManager::Memcached();
$keyword_webpage = md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
// try to get from Cache first.
$resultsItem = $cache->getItem($keyword_webpage)
if(!$resultsItem->isHit()) {
ob_start();
cache_end.php
// GET HTML WEBPAGE
$html = ob_get_contents();
$resultsItem->set($html)->expireAfter(1800);
$cache->save($resultsItem);
}
echo $resultsItem->get();
mypage.php
include_once 'cache_start.php';
// my awesome content to cache goes here...
include_once 'cache_end.php';
myotherpage.php
include_once 'cache_start.php';
// my other great content to cache goes here...
include_once 'cache_end.php';
So the reason WHY I want to put the phpfastcache code in 2 separate files is that I have many different PHP pages to cache, so I would like to avoir repeating all this code on each page...
Hope this edit will help you better understand why I would do that, even if I understood, as I feared, that is is not possible.
Give it a try:
how can I achieve this ?
Do it the evil way and eval all instead of including :) Like
eval(file_get_contents('header.php').'<?php echo "my awesome content";?>'.file_get_contents('footer.php'));
That can be a solution, if you want to join the dark side :)
SideNote: In this solution, you have to keep an eye on global variables!!
But please, thing about the fact, that you want to spread conditions over seperate files, what in my opinion is very very very bad practise.
Did i really answer this 8]
I try it in other way.
Only rule: works only in global space (where else :-))
So you want to open an if() in cache_start.php and close it cache_end.php. (for ob_cache reasons)
But if the condition isn't changed why not doing the condition twice!
In each file test for if(condition)!
Or set up an variabale like $cach_op_started=true and test for it in the second if() in cache_end.php
Thing boths should work for you.
Its a little funny that i didnt see that solution at the first time :)
Last Note:
You can also use auto prepend and append files in PHP if you want to.
That can be configurated in php.ini.
The files will automaticly loaded before and after an script, always.
http://www.webdevsecrets.com/using-phps-auto_prepend_file-and-auto_append_file/
Have a nice time.
So I understand that the problem is that when you don't want a certain user to see the contents of a page, the rest of the page isn't loaded and that is whats causing the error?
If so, why don't you just always include the files and in the specific page you set the conditions for who can view what?
I use ob_start() in my header, and ob_end_flush in my footer which works great.
and then check with my SESSION variables on the specific page's content if the logged in user has the right to see the content, else display a message like:"You are not authorized to see this content"
For a class that I am in I need to create a simple form that when the data is sent to the next page, it just creates text using the data entries from that previous page. The instructions require us to use an "include" or "require" at least once. I don't understand how one could use a require / include if the application is just Page with a form -> Submit -> Next page.
The require/include would require a third page, wouldn't it? Or am I missing something with the include/require? How should I go about incorporating one?
You would normaly use an include to add some functionality to your program which you do not want to re-code in your program. For example to include certain libraries. You can also do it to make your code look neat by moving your functions or class definitions to include files then you add them to your script whereever needed. That being said, it is not a must condition that you can only use includes in a certain scenario. You can use them anytime. Even for simple things. For example you can have an file named includes.php which contains this
<?php
$name=$_POST["name"];
?>
Then in your file which receives form submit, lets say process.php, you can say
<?php
include "includes.php";
echo $name;
?>
Also just a clarification of difference between include and require. In the simplest sense a script will continue to execute even if an include fails, but if a require call fails then the script will stop execution. You can also then use include_once or require_once to stop mistakenly including one file multiple times
I have a form that submits to itself and when I submit I get a header and the background but no content on the page, nothing below title in the html. It doesnt write to my database either, no errors, and the styles are there.
I think it has to do with my mysql connection.
I've uploaded everything here https://www.yousendit.com/download/bHlCVWRuTkFTRTUzZUE9PQ
This is for my project as I learn php and mysql and this is a wall I cant get past. Please help!
In index.php file you have:
require_once "quoteit-functions.php";
require_once "quoteit-post.php";
and than you have in quoteit-post.php file:
require_once "quoteit-functions.php";
remove that line because that file is automatic included in that file, instance is used from index.php file.
This was the solution via my teacher late last night:
The main problem that you don't see anything displayed was because you close the connection in quoteit-post.php - and that's before you attempt to reuse "$db" to display and do the count. I moved it out to index.php.
Hi guys consider I have a .php page that I need to include somewhere else.
page.php:
<?php
dosomecmd();
doothercmd();
//etc
?><html>pagehtml</html>
Is there a way to include this page but not printing the html inside? (I just need to execute those command)
I could do with ob
ob_start();
include('page.php');
ob_discard();
But i would prefer a faster way.
Thanks
Edit: i know i can sepearate html and php (and i already do) but that page.php is non else than a "static" cache I make, but sometimes I need to execute some command inside that cache instead to printing automatically it out
Edit2: of course i don't need everyime to not output the html (otherwise I could just delete all html) I need to return; only based on the results of my cmds up there
Thanks all i find a solution (add return;)
Would it be easier to have a common page with only the php that you need to share, and include it in both page.php and your other page?
you can try to seperate with
$_SERVER['REQUEST_URI']
also I wouldn't recommend that
Try to separate the PHP logic at the start of your current script into another file, then include that into both of your scripts.