So i have three files.
FILE 1 includes FILE 2 which includes FILE 3
FILE 1 needs to print VAR 1 which is defined in FILE 3
how would I do that?
Its not echoing out for me
file 1
<?php
if ($_GET["pg"]==false)
echo "<title>Socal Mods</title>";
else
echo $title_name;
?>
file 2
<?php
if ($_GET["pg"]==false)
include("home.php");
else
include("".$_GET["pg"].".php");
?>
file 3
<?php $title_name="<title>Socal Mods</title>" ?>
file 3 is being parsed into file 1 which is the display container, but the %title_name is not echoing
One thing first about how you access the GET variables. You check the value using $_GET["pg"] == false. Note that this expression will fail to do what you expect in a lot situations. In fact, the value will never be directly false. The only way it will equal to false if it is empty or unset (in which case you will also get a compiler warning, which you should avoid). Usually a safer way to check if the value was set is using isset( $_GET["pg"] ).
The next thing I want to address is a security problem you introduce. You use the GET value directly to include a file with that name. If I was a user with malicious intent, I could easily set the pg value to something, you usually wouldn't expect and which break your website in some way. You generally should avoid using data the user entered somehow (request parameters are user data), and make sure to sanitize them first. A good way to do this, when you plan to use the value as a base to which page you want to include, would be to have some kind of whitelist of acceptable/allowed values. Then you can check if the entered data is in that whitelist and if that is the case, include the correct page. Another simple way would be using a switch statement to simply go through all accepted cases.
Now finally, onto your problem: I'm not sure if this was just a mistake when you posted the code, but file 1 is missing the include of file 2. As such you will never include file 3, and of course the variable will never be set.
Another problem might be the usage of the GET value. If the value does not contain the exact filename (as in casing and no extra whitespace), then the file won't be found. It is a good idea to echo out the filename you want to include in file 2, just to check if you are making any mistakes. The whitelist as explained above would be another way to make sure that you are trying to include the correct file.
Finally, you should enable error reporting on your server, you can do that either in your server configuration, or by adding the following line to the top of your first file (i.e. file 1):
error_reporting( E_ALL );
That way you will get errors and warnings that will tell you if something unexpected happened at runtime, and you might see your mistake easier.
Old answer
In general it works like this:
File 1:
<?php
include 'file2.php';
echo $myVariable; // prints 'Hello World!'
?>
File 2:
<?php
include 'file3.php';
?>
File 3:
<?php
$myVariable = 'Hello World!';
?>
echo $title_name = "<title>Socal Mods</title>";
It means its echoing html, So "Socal Mods" will be seen in title bar instead of the body. I hope you are looking in the titlebar. And to use $title_name in file 1 which is available in file 3 you hv to include file3 in file1.
Is file 3 included in the script? And have you actually validated and confirmed that the file is included? If you change the include statements in your script into require statements, PHP will stop with an error if the file you are looking for does not exist.
There are many reasons why a file might not be found. If the file name contains uppercase letters and the request only contains lowercase letters, you will run into problems if the server uses a case sensitive file system.
Also you should sanitize user input before you use that to include files. You don't want me to be able to include any file anywhere on your server, do you?
Variabes have to be created, set and assigned a value before they can be echoed.
Most probably ( please show us some code ), your problem is not the file includes, but you are trying to echo your variable before it is assigned a value.
Related
I am trying to include 2 php file in two separate <td> tags in the same table.
<td><?php include 'login.php';?> </td>
<td><?php include 'register.php';?> </td>
Both the php files include another php file for connecting to a database (eg. <?php include 'database.php';?>
Now, the problem is, the second file doesn't show up in the table. First file works.
Php files work independently. No problem with the code.
I removed the include in 1.php and everything worked fine - ie. both the files show up in table.
My conclusion is, it goes on including indefinitely. Now, how do I solve this?
regards
Ganesh Kumar
You can use include-once
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
i.e.:
include_once('database.php');
include_once('login.php');
include_once('register.php');
You actually have several options, now that I think about it.
Require_once:
require_once('database.php')
This is the most accepted method for files such as this one that you describe, as it will hard-fail if the file cannot be included. For files that do program instantiation (I.e. database connection) this method is preferred.
Include_once:
include_once('login.php')
I've never found a reason to use this statement over require_once; however, that said, it doesn't mean there isn't one. If you have a file that does some instantiation of something related to your programme that isn't mission-critical, then you could suppose to use this directive over the other.
Define Include Constants:
This method requires a bit more explanation: instead of starting your included file (database.php in our example) off with the code for it, start it off in a manner similar to C/C99/C++.
<?php
if (!defined("INCLUDED_DATABASE"))
{
define("INCLUDED_DATABASE", true);
// add main body of file here
}
?>
This method basically accomplishes the same thing as the include_once and require_once, except that in no circumstances will it ever actually process the body twice in one request, even if you forget to use _once as a suffice to your include/require method. This goes back to the old days of C/C99/C++
where including a file twice would hard-fail the compiler, as duplicate definitions would take place.
Personally, I have always preferred the last option: it's the most strict. Yes, require_once and include_once when used diligently will have the same effect, but suppose someone (not even you necessarily) is modifying the application and accidentally does an include or require without the _once suffix, they will be having a bad day. This method prevents that.
That said, I still use a require_once when necessary, and a require if it can be included multiple times. (Files with that designation are not designed with the define construct.)
I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();
What I am trying to do is change a variable in fileb from filea. Kind of like using fileb as a config file in a way.
Example:
File A:
require_once "fileb.php";
if($power == 'off') {
exit;
}
if($test1 == 'one') {
echo "The first option is selected";
} elseif($test1 == 'two') {
$power = 'off';
}
File B:
$power = 'on';
So in this example a user id prompted for $test1, if they reply with "one" they get a echo. What I want to do is make it so if they reply with "two" it shuts down the page, and not just for them but for everyone. I am trying to do all of this without using a DB, that would be too easy lol. Thanks for the help!
I am trying to do all of this without using a DB, that would be too easy
There's a reason using a database for this is easy. It's the correct way to accomplish this task. Modifying actual PHP code files is a famously bad idea. (And one that somebody on Stack Overflow has almost weekly, it seems.)
If you include the file as part of the executing code, you can use the variable as any other. This allows you to manipulate the variable in a transient way, but not manipulate the code which creates the variable.
What you're trying to do is persist that changed variable. In order to do that, it needs to be written somewhere outside of the application. Databases are really good for that sort of thing. You could also write to a simple text file (a string of text, structured XML, etc.) though in that case you'll have to manually watch out for concurrent writes and other such errors. (Databases are really good at that too, which makes them ideally suited for multi-thread/multi-user applications like web apps.)
I suppose you could treat the PHP file itself as an editable text file like any other. (Since PHP is, after all, just text.) But, again, that's a really bad idea. For one thing, parsing out exactly the value you want and writing back a change only to that value is going to be very difficult. Also, you run the risk of breaking a file which is treated as executable code which opens up all sorts of potential risks.
Just write to a database, or to a file, or to any other simple data persistence medium outside of the application.
Your fileb is lacking the <?php ... ?> tags. Without those, you "code" is never seen as code. it'll just be treated as plain text.
file b:
<?php
$power = 'on';
file c:
Hello
<?php
$foo = 'world!';
file a:
<?php
include('fileb.php');
echo $power;
include ('filec.php'); // "Hello" is immediately output
echo $foo; // tell PHP to put the $foo var, which will print out "world!"
OK, so I have searched around for long enough to finally post this one here. Sure enough, it has been asked before a zillion time...
What I have, is one file, which includes another. No magic here. The trouble is, the included file then includes another file, which... includes yet another... Yep, a pain. Actually it's all working quite nicely, except that I now wanted to read the URL of the original file in the last of the included files.
So I thought in the original file, file_1.php I just say
$var_foo = dirname(__FILE__);
or
$var_foo = $_SERVER['SCRIPT_NAME'];
and then read that value in the first include, file_2.php, passing it on like
$var_foo_2 = $var_foo;
then in file_3.php
$var_foo_3 = $var_foo_2
etc, until I arrive at the final file, file_4.php, where I'd like to know the exact value of the original file's URL. Passing it on the first level works OK, but then it gets lost somewhere along the way. Tried going GLOBAL in file_1 -- to no avail.
Since file_3 and file_4 must both execute to produce data, setting a breakpoint a la echo / exit to spoof the current value (if any) is no option. I can live without that particular value, but I just would like to have it -- for the fun of it... Any ideas how to accomplish this?
Your examples use filesystem paths, not "URLs";I am assuming the filepath of the parent file is what you actually want.
You don't need to "pass" the variable on each included page. It will automatically be available to the code on the new page.
(If it is not, you may not be in the right scope: e.g., if you're inside a class or function, you'll need to pass it deliberately or use some other method - global, maybe, or even define the filename as a constant instead of a variable.)
main script
$parent_filename = __FILE__;
// alternatively
// define( 'PARENT_FILENAME',__FILE__ );
include "other-file.php";
other-file.php
include "other-dir/somefile.php";
other-dir/somefile.php
print $parent_filename;
// alternatively
// print PARENT_FILENAME;
/* prints something like:
/path/to/main.php
*/
As mentioned before, the issue has been solved like so:
set variable before the first include
add variable to query string
Thanks all for the input, appreciated.
From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.