PHP - Sending GET variables as a Path in and Include/Require Statement - php

I have a situation where I would like to use a php file "query.php" to look take either a $_POST or $_GET value as the MySQL query. It looks like this:
<?php
//verify data has been sent via POST or GET and set strings
//find supplied table name
if(isset($_POST['tblName'])){
$strSuppliedTableName = $_POST['tblName'];
}
if(isset($_GET['tblName'])){
$strSuppliedTableName = $_GET['tblName'];
}
else{
$strSuppliedTableName = 'roles';
}
//find supplied field name or default to all fields in the table
if(isset($_POST['fieldName'])){
$strSuppliedFieldName = $_POST['fieldName'];
}
else if(isset($_GET['fieldName'])){
$strSuppliedFieldName = $_GET['fieldName'];
}
else{
$strSuppliedFieldName = '*';
}
//query db
$query = 'SELECT ' . $strSuppliedFieldName . ' FROM ' . $strSuppliedTableName;
$results = mysql_query($query) or die(mysql_error());
?>
Following that, I want to include this file "query.php" in another file that will manage the results. I'm trying to make this as modular as possible.
<?php
require_once("query.php?tblName=classes");
......... (while loop, yadi yadi
However, I recieve an error:
Warning: require_once(query.php?tblName=classes) [function.require-once]: failed to open stream: No such file or directory
Is it not acceptable to pass GET values to your included file? PHP won't process this?

You do not need to pass variables in a get or POST like way when including or requiring files, the variables are shared between the files, as long as the values are set before the including happens.
i.e.:
file1.php called as file1.php?var2=value2
<?php
$var1 = "value1";
$var2 = $_GET['value'];
include "file2.php";
?>
file2.php:
<?php
echo $var1.' '.$var2;
?>
will output:
value1
value2

As a shortcut, you can use $_REQUEST inside, which is an amalgam of the _GET, _POST, _COOKIE, and _ENVIRONMENT superglobals. Exactyl which ones go into it is under control of the request_order .ini setting.
Alternatively, an utterly reliable method to check which METHOD you're handling is $_SERVER['REQUEST_METHOD']. This value is always set when handling an HTTP request, and will be GET, POST, HEAD, etc... Unlike checking for the presence of a form field, it's utterly dependable - the form field may not be submitted (unchecked checkbox?), it may be renamed in the HTML but you forget to change the script, etc...
As for your require(), unless you specify an absolute url (http://...), PHP will interpret its argument as a request for a local file, and will not pass it through the HTTP layer. Unless you have a file named query.php?tblName..., it'll be "file not found" and the require() fails.

the right way to do this is to define your data as variables in your mother file and then in your child file use those variables.
in the code you gave the parser looks for the file 'query.php?tblName=classes' and obviously it does not exist.

include/require both take a filename as a spec, not a URI. PHP doesn't parse it as a URI, so what you're trying won't work.
Better to set up an object that the included/required file can then inspect.

Related

Fail to include file within while loop

So, I have a small script fetching some information from a database.
What it basically needs to do is include a svg generated in 'miescudo.php'.
$sql = "SELECT u.id, u.id_facebook, t.*
FROM user_facebook u
LEFT JOIN user_team t ON u.id = t.id_user
WHERE u.id_facebook='100003809660283'";
$result = mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<div>'.include('miescudo.php').'</div>';
}
I get the following error message:
Warning: include(miescudo.php?id=1
): failed to open stream: No such file or directory in full-path-goes-here/tusequipos.php on line 56 Warning: include(): Failed opening 'miescudo.php?id=1
But yet, when I include the file the same way but outside my while loop it works fine.
I assume that the following is the reason to this error, but I haven't figured out how to fix it:
// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
Any help and advice is much appriciated.
Oh, and I don't need any reminders about not using the deprecated mysql_* functions. I am well aware and will update this piece of code accordingly - I promise!
include doesn't understand non-absolute URLs. It does NOT do an http request unless the string you're passing in as an argument is a full-blown url, which means including the protocol:
include('http://example.com/path/to/script.php'); // does an HTTP request
include('/path/to/script.php'); // local request only
include('http://example.com/script.php?foo=bar'); // does an HTTP request
include('script.php?foo=bar'); // local request only, will look for a "...?foo=bar" file
Unless an HTTP request is done, your query parameters are going to be treated as if they're literally part of the filename. So PHP wouldn't look for script.php and pass in foo=bar. It'll look for a file whose name is literally script.php?foo=bar.
You can't include a file with a GET-Parameter, since the GET-Parameter won't be noticed. Either you have to read the output over the HTTP-Protocol (if allow_url_fopen is enabled, you can just use file_get_contents()) or you can simply use the variable (maybe you need to declare it as global) if you include the script. And remember to use the absolute filepath.

What's wrong with this include statement?

This function is returning the content of the file rather the result of fetch_link_settings_overide() within it.
The issue is not with the overide function as after the initial error I commented out my modification just to be sure it wasn't something I had done there.
function fetch_link_settings(){
include( plugins_url()."/plugin-child/plugin_overrides.php");
return fetch_link_settings_override();
}
Adding the content of the derived function plugin-child/plugin_overrides.php as we are not getting anywhere currently.
function fetch_link_settings_override(){
global $post;
// If the destination url is set by the user, use that. Otherwise, use the permalink
$destination_url = get_post_meta($post->ID, '_promo_slider_url', true);
// ASAdd additional place to look in the case of the post being via the PODS advert track
if( ! $destination_url )
$destination_url = get_post_meta($post->ID, 'okd_advert_link', true);
if( ! $destination_url )
$destination_url = get_permalink($post->ID);
// If the target attribute is set by the user, use that. Otherwise, set it to _self
$target = get_post_meta($post->ID, '_promo_slider_target', true);
if( ! $target ) $target = '_self';
// Setup the disable links variable
$disable_links = get_post_meta($post->ID, '_promo_slider_disable_links', true);
return compact('destination_url', 'target', 'disable_links');
}
You write this:
include( plugins_url()."/plugin-child/plugin_overides.php");
Why is plugins_url() there? The include function is strictly based on the file system:
The `include` statement includes and evaluates the specified file.
As explained in the WordPress docs, the plugins_url() would give you the full web URL which is 100% different than the file system WordPress is installed on:
Retrieves the absolute URL to the plugins directory (without the
trailing slash) or, when using the $path argument, to a specific file
under that directory.
So perhaps it should be like this:
include("/plugin-child/plugin_overides.php");
Or perhaps you need the plugin_dir_path()?
include(plugin_dir_path( __FILE__ ) . "/plugin-child/plugin_overides.php");
But that seems wrong. Where would /plugin-child/plugin_overides.php? Try doing this:
include("/full/path/to/wordpress/and/this/plugin-child/plugin_overides.php");
Just replace /full/path/to/wordpress/and/this/ with the actual file system path to /plugin-child/plugin_overides.php.
EDIT: Since the original poster is persistent in using plugins_url() despite all of the suggestions otherwise, here is my detailed response:
…you said “you cannot load raw functions via a URL with include” well
this is not relevant because even if I add $some_var = 'smith'; as the
first statement in the included file, it is not visible in the
function using the include.
Apologies. Functions, classes, strings, constants… Just about anything that you want to be raw, unprocessed PHP will simply not be passed via an http:// or https:// URL because Apache will parse the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file.
Additionally the original poster contents the following:
You can’t help me because what you are saying does not make sense or
you are not explaining yourself adequately. Look at these examples:
include realpath(dirname(FILE) . "/" . "relative_path");
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
All taken from the official PHP documentation. They all use
functions returning components that are concatenated with the rest of
the url. I also tried this typing the filepath explicitly and the
result is the same.
The examples cited are as follows:
include realpath(dirname(FILE) . "/" . "relative_path");
This is a filesystem level include which is the most common way PHP files are included into other files.
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
These are both data URLs. Not http or https. So again when you use plugins_url() what you are getting is a full http:// or https:// URL in which Apache parses the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file. Or as very clearly explained in the PHP documentation you are linking to; emphasis mine:
If "URL include wrappers" are enabled in PHP, you can specify the file
to be included using a URL (via HTTP or other supported wrapper - see
Supported Protocols and Wrappers for a list of protocols) instead of a
local pathname. If the target server interprets the target file as PHP
code, variables may be passed to the included file using a URL request
string as used with HTTP GET. This is not strictly speaking the same
thing as including the file and having it inherit the parent file's
variable scope; the script is actually being run on the remote server
and the result is then being included into the local script.
Going back to your example, you say now the contents of plugin_overides.php is $some_var = 'smith';. How exactly? If it is a PHP file like this:
<?php
$some_var = 'smith';
?>
When you call that file via a URL generated by the following code:
include(plugins_url() . "/plugin-child/plugin_overrides.php");
Assuming your website is http://some.cool.website/ the you are basically making a call like this:
http://some.cool.website/plugin-child/plugin_overides.php
So the output of plugin_overides.php would be 100% blank. If you wanted to get output of that file, you could do the following:
<?php
$some_var = 'smith';
echo $some_var;
?>
And that would return smith. Meaning the absolute ONLY output you would get from that call is pure text. Nothing else.
Now I see you actually have posted the contents of plugin_overides.php. My example explanation above is still apt, but still a basic question. This is your function; just the interface & return for example:
function fetch_link_settings_override(){
// Other code removed. Just a structural illustration for now.
return compact('destination_url', 'target', 'disable_links');
}
Do you actually call fetch_link_settings_override() in plugin_overides.php when it runs? Well, if that function does not run, then there is 100% no way you will ever get any output. But assuming good faith, look at your return statement here:
return compact('destination_url', 'target', 'disable_links');
If you are returning compact, then you are returning an array. You cannot simply return a bare array as a URL call like this http://some.cool.website/plugin-child/plugin_overides.php. The output at most would be simply the word Array.
If the goal is to take that array & do something, then you should use json_encode in fetch_link_settings_override and then use json_decode on the receiving side of that. So the return statement would be something like this:
return json_encode(compact('destination_url', 'target', 'disable_links'));

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

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.

How to declare a variable in php while including files?

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.

PHP include with HTTP get paramters

How would one go about using php include() with GET paramters on the end of the included path?
IE:
include("/home/site/public_html/script.php?id=5");
How would one go about using php include() with GET paramters on the end of the included path?
You could write into $_GET:
$_GET["id"] = 5; // Don't do this at home!
include(".....");
but that feels kludgy and wrong. If at all possible, make the included file accept normal variables:
$id = 5;
include("....."); // included file handles `$id`
You don't, include loads files via the local filesystem.
If you really wanted to, you could just do this, which would have the same result.
<?php
$_GET['id'] = 5;
include "/home/site/public_html/script.php";
?>
but then you might as well just define the variable and include it
<?php
$id = 5;
include "/home/site/public_html/script.php";
?>
and reference the variable as $id inside script.php.
Well you could use:
include("http://localhost/include/that/thing.php?id=554&y=16");
But that's very seldomly useful.
It might be possible to write a stream wrapper for that, so it becomes possible for local scripts too.
include("withvars:./include/that/thing.php?id=554");
I'm not aware if such a solution exists yet.

Categories