Include a php library and cant access it from another php page - php

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');

Related

include_once when using header files

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.

Include php file that includes another php file?

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?

Include PHP file with condition opened but closed in another included PHP file

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"

Proper way to require file that requires db connection

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.

Variable scope and includes

I have the following problem: in index.php, I have set the variable $activelang. I
$activelang = active_language ();
echo $activelang; //works perfectly
Later in my index.php code, I include a new php file.
include ('myotherfile.php');
If I try to use $activelang in myotherfile.php, it does not work! I am not using it inside a function, and I tried using global $activelang and it doesnt work either
All of these is happening in a wordpress install, but the code I am talking about is plain php. I am using php 5.3
Why is this happening? As I undestand it, the include works as a copy paste in my main file, so I shouldnt be having any problems with variable scope, right?
include should be used to include files, not some network resources.
if you bother to run the code you posted here you'll be surprized, as it will print $activelang all right.
When working with WordPress templates you should create functions in your functions.php file for handling includes and then call those functions in your templates.
So in functions.php you should have:
function myOtherFile() {
include('myotherfile.php');
}
And in index.php call myOtherFile()
Now, if you still have trouble with scope try this:
function myOtherFile($activelang) {
include('myotherfile.php);
}
And then in index.php do this:
$activelang = active_language();
myOtherFile($activelang);
If that doesn't work then I think your problem is being caused elsewhere. Because like Col. Shrapnel said, the code you posted here works.

Categories