Using $_GET in PHP include with variable in the include URL - php

Firslty, please forgive the ineloquent phrasing of my question.
What I am trying to do, is create a simple odbc script, and store it in a file which will be included in my main PHP file several times with different variables.
When including them, I want to specify some variables to pass to it.
My example would be:
Main page
include("table-fields.php?table=sometable");
table-fields.php
$table = $_GET['table'];
odbc_exec(some database function WHERE TBL= $table);
However, if my understanding is correct, as $_GET is global, it would be looking for main.php?table=
Would the better choice be to just set the variable before including, e.g.:
$table = some table;
include("table-fields.php");
table-fields.php
odbc(some database function WHERE TBL= $table);
I want to try and avoid that if possible.
Thanks, Eds

When including a file, the contents of that file is outputted into the current file, it's not requested with HTTP, so all you need to do is :
$table = "sometable";
include("table-fields.php");
and in the included file, just use the variable :
odbc(some database function WHERE TBL= $table);
as the included content would work just like if you wrote it in the main file etc.

You have to declare the variable before the include and it will be available in the code under it.
$_GET is used to get data from HTTP request.
As you pointed out, this would be the correct way:
$table = some table;
include("table-fields.php");
Just imagine the include as a copy and paste inside your code. The code inside the included content will be replazing the include call.

Related

How to know if a script was included inside another script

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

Is there an equivalent to <jsp:include in PHP that can also handle parameters and default values

I have a PHP page that lists many products that each consist of HTML that -depending on the product- does or does not show certain information. I extracted this "product HTML" into a separate PHP file that I include many times. The external file uses variables for each of the product's attributes and also if statements so that parts of the HTML are not rendered at all when an attribute is not set.
The problem is that many of the attributes have default values that I do not want to set each time I call the include
So is there a mechanism in PHP that lets me include another PHP file in such a way that:
I can provide parameters to the file,
uses a default value for the parameters when I do not provide a value,
can be used multiple times in one file.
(This is the way <jsp:include works.)
Keep in mind that I cannot use simple variables (as far as I know) because they keep their value between two separate include calls.
When you include a file in PHP, that file has access to the current scope. So, we need a "clean" scope with no variables and populate the one we need. The best way to go is using a function and the PHP extract method:
function product($data){
extract($data);
require(....path to file);
}
Now call it:
product(array(
'foo' => 'bar',
....
));
This way, on the included file you got a $foo variable with 'bar' value and nothing else. This is how MVC frameworks deal with views.
Edit:
<?PHP
function product($data){
extract($data);
?>
<HTML content>
<?PHP
}
?>
Now "require_once" the file with this and call it like before.

Read parent URL from included file

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.

Can't pass a PHP variable to file_get_contents()

I am a newbie coder trying to build a simple web app using PHP. I am trying to send an HTML email that has a variable that will change each time it is sent. The code to initiate the email is 'email.php' and contains:
$body = file_get_contents('welcome/green2.html.php');
Within the 'green2.html.php' file, I have a variable called $highlight that needs to be populated. The $highlight variable is defined within the 'email.php' file. I had tried to simply add within the 'green2.html.php' file, however it is not being parsed. I get a blank space where the variable should be when it is output.
Also, I have done an include 'welcome/green2.html.php' within the 'email.php' file. When I echo it, the $highlight var is shown on the resulting page, but not if I echo $body.
Any help would be much appreciated!
Have you tried the str_replace function? http://php.net/manual/en/function.str-replace.php.
Add a placeholder in HTML (for instance #name# for name, #email# for email), and then use the string replace function once you've loaded the content of the file.
$bodytag = str_replace("#name#", $name, $myfile);
Loading a file via file_get_contents() will not cause it to be parsed by PHP. It will simply be loaded as a static file, regardless of whether it contains PHP code or not.
If you want it to be parsed by PHP, you would need to include or require it.
But it sounds like you're trying to write a templating system for your emails. If this is what you're doing, you'd be better off not having it as PHP code to be parsed, but rather having placeholder markers in it, and then using str_replace() or similar functions to inject variables from your main program into the string.
Hope that helps.
Use http://php.net/manual/en/function.sprintf.php put a %s in your code instead of the variable read the content and put the string into the sprintf with the variable you want to put that's it. Hope this will help.

How to load the result of a php function into a variable

I have a php file on my server that takes in two inputs through the URL and then comes back with a result. When a page is loaded, I'd like to have the result of that calculation already loaded. For example:
$var = load("http://mysite.com/myfile.php?&var1=var1&var2=var2");
I know that load isn't a real function for this, but is there something simple that suits what I'm looking for? thanks
Use file_get_contents
$foo = file_get_contents('http://mysite.com/myfile.php?&var1=var1&var2=var2');
Or, a better solution if the file is located on your server:
include('myfile.php');
and either set the $_GET variables in the included script itself, or prior to including it.
If they are running on the same server, consider calling the script directly?
$_GET["var1"] = "var1";
$_GET["var2"] = "var2";
include "myfile.php";
You could use file_get_contents, but it may be a more practical solution to simply include the file and call the function directly in the file, rather than trying to manually load the file.

Categories