Fail to include file within while loop - php

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.

Related

file_get_contents not working when parameters included in a relative url

I am trying to create a simple web service that will give a result depending on parameters passed.
I would like to use file_get_contents but am having difficulties getting it to work. I have researched many of the other questions relating to the file_get_contents issues but none have been exactly the situation I seem to having.
I have a webpage:
example.com/xdirectory/index.php
I am attempting to get the value of the output of that page using:
file_get_contents(urlencode('https://www.example.com/xdirectory/index.php'));*
That does not work due to some issue with the https. Since the requesting page and the target are both on the same server I try again with a relative path:
file_get_contents(urlencode('../xdirectory/index.php'));
That does work and retrieves the html output of the page as expected.
Now if I try:
file_get_contents(urlencode('../xdirectory/index.php?id=100'));
The html output is (should be): Hello World.
The result retrieved by the command is blank. I check the error log and have an error:
[Fri Dec 04 12:22:54 2015] [error] [client 10.50.0.12] PHP Warning: file_get_contents(../xdirectory/index.php?id=100): failed to open stream: No such file or directory in /var/www/html/inventory/index.php on line 40, referer: https://www.example.com/inventory/index.php
The php.ini has these set:
allow_url_fopen, On local and On master
allow_url_include, On local and On master
Since I can get the content properly using only the url and NOT when using it with parameters I'm guessing that there is an issue with parameters and file_get_contents. I cannot find any notice against using parameters in the documentation so am at a loss and asking for your help.
Additional Notes:
I have tried this using urlencode and not using urlencode. Also, I am not trying to retrieve a file but dynamically created html output depending on parameters passed (just as much of the html output at index.php is dynamically created).
** There are several folks giving me all kind of good suggestions and it has been suggested that I must use the full blown absolute path. I just completed an experiment using file_get_contents to get http://www.duckduckgo.com, that worked, and then with a urlencoded parameter (http://www.duckduckgo.com/?q=php+is+cool)... that worked too.
It was when I tried the secure side of things, https://www.duckduckgo.com that it failed, and, with the same error message in the log as I have been receiving with my other queries.
So, now I have a refined question and I may need to update the question title to reflect it.
Does anyone know how to get a parameterized relative url to work with file_get_contents? (i.e. 'file_get_contents(urlencode('../xdirectory/index.php?id=' . urlencode('100'))); )
Unless you provide a full-blown absolute protocol://host/path-type url to file_get_contents, it WILL assume you're dealing with a local filesystem path.
That means your urlencode() version is wrongly doing
file_get_contents('..%2Fxdirectory%2Findex.php');
and you are HIGHLY unlikely to have a hidden file named ..%2Fetc....
call url with domain, try this
file_get_contents('https://www.example.com/inventory/index.php?id=100');
From reading your comments and additional notes, I think you don't want file_get_contents but you want include.
see How to execute and get content of a .php file in a variable?
Several of these answers give you useful pointers on what it looks like you're trying to achieve.
file_get_contents will return the contents of a file rather than the output of a file, unless it's a URL, but as you seem to have other issues with passing the URI absolutely....
So; you can construct something like:
$_GET['id'] = 100;
//this will pass the variable into the index.php file to use as if it was
// a GET value passed in the URI.
$output = include $_SERVER['DOCUMENT_ROOT']."/file/address/index.php";
unset($_GET['id']);
//$output holds the HTML code as a string,
The above feels hacky trying to incorporate $_GET values into the index.php page, but if you can edit the index.php page you can use plain PHP passed values and also get the output returned with a specific return $output; statement at the end of the included file.
It has been two years since I used PHP so I am just speculating about what I might try in your situation.
Instead of trying fetching the parsed file contents with arguments as a query string, I might try to set the variables directly within the php script and then include it (that is if the framework you use allows this).
To achive this I would use pattern:
ob_start -> set the variable, include the file that uses the variable -> ob_get_contents -> ob_end_clean
It is like opening your terminal and running the php file with arguments.
Anyway, I would not be surprised if there are better ways to achieve the same results. Happy hacking :o)
EDIT:
I like to emphasize that I am just speculating. I don't know if there are any security issues with this approach. You could of course ask and see if anyone knows here on stackoverflow.
EDIT2:
Hmm, scrap what I said last. I would check if you can use argv instead.
'argv' Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. http://php.net/manual/en/reserved.variables.server.php
Then you just call your php script locally but without the query mark indicator "?". This way you can use the php interpreter without the server.
This is likely to be the most general solution because you can also use argv for get requests if I am understanding the manual correctly.

Passing file url with variables into Postmark causing file not found issue

So I'm using Postmark to send emails and the class I have requires a variable as the message body, as below:
$email->to(Input::post('email'))->subject("Verify Your Email Address")->html_message($html)->send();
This works fine if I set $html as just plain html.
What I am trying to do is send the contents of another php file from my site as this html.
I have tried:
$Vdata = file_get_contents('verification.php');
this works fine but as soon as I try and pass variables in it gives me an error:
file not found error
And sends a blank email, for example:
$Vdata = file_get_contents('verification.php?url=blah');
Essentially I just need $html to be the contents of verification.php?url=blah so that I can pass in variables to that file.
Can anyone help?
You're doing a local file inclusion, which means filenames ONLY. URLs are not permitted (query strings in particular) because you're NOT doing an HTTP request. PHP is going to look for a file whose name literally contains ?, u, r, etc... which of course doesn't exist.
If you want to use query strings, then you have to use a full-blown absolute URL, including the protocol:
include('http://....?url=...');
However, this is incredibly inefficient, and also highly dangerous. Since you're now EXECUTING the file specified in the url. you're going to get its output, not the raw PHP code in the file.
If you want to pass data to an included file, then just variables:
$foo = 'bar';
include('test.php');
and use look for/use those variables in the file.

PHP Include operator can't seem to find php script

I am having an odd problem that continues to baffle me. I appreciate your advice....
In a PHP 5.3 script I am including another PHP script using the following code;
include 'moninit.php?id=1234'; // initialize array variables
moninit.php is stored as C:\xampp\htdocs\CarmelServices\moninit.php
In php.ini the include path is:
include_path = "C:\xampp\htdocs\CarmelServices"
So, the include should execute moninit.php but I get the following error returns;
Warning: include(moninit.php?id=1234) [function.include]: failed to
open stream: No error in C:\xampp\htdocs\CarmelServices\SensorW.php on
line 48
Warning: include() [function.include]: Failed opening
'moninit.php?id=1234' for inclusion
(include_path='C:\xampp\htdocs\CarmelServices') in
C:\xampp\htdocs\CarmelServices\SensorW.php on line 48
If I execute moninit.php directly using a browser, it works fine. So, somehow the include cant seem to find moninit. SensorW is also in the same folder as moninit.
Very odd, at least to me. Thanks!
include does not execute a PHP script; it only inserts the contents of the file into the currently-running script.
In your example, you are telling the PHP interpreter to find and open a file named 'moninit.php?id=1234' which does not exist. You may wish to include 'monit.php' itself or find another way (such as cURL) to execute the script and retrieve the response.
You cannot pass array variables with it, it's included directly in your script and will inherit any variables in the available scope. So you can assign to an array and use that instead.
$data = array('id' => '1234');
include 'moninit.php'; // In moninit.php, use $data instead
If you're just routing the parameters passed, don't worry - they already work.
#GeorgeCummins' answer explains how include() works. Also, you can only pass it the name of the file. You can't pass it variables like you're doing. It's a file name, not a URL.

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

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.

passing URL variables to exec() with php

I have a dedicated server that I use to crunch lots of data. The way I have it now, I can open a script with a process ID like example.php?ex_pid=123 and just let it go. It downloads a small portion of data, processes it, then uploads it into a database then starts again.
Ideally, I would like to call example.php?ex_pid=123 directly and not by passing a variable to example.php like exec('./example.php'.' '.EscapeShellArg($variable)); to keep it from acting globally.
I don't care about the output, if it could execute in the background, that would be brilliant. The server is an Ubuntu distribution btw.
Is this even possible? If so, any help and examples would be more then appreciated.
You could do something like:
exec("./example.php '".addslashes(serialize($_GET))."');
And then in example.php do something like this:
count($_GET) == 0 && $_GET = unserialize(stripslashes($_SERVER['argv'][1]))
The main issue with that is that ?ex_pid is GET data which is generally associated with either including the file or accessing it through a browser. If you were including the file or accessing it from a web browser this would be trivial, but running it as CLI, your only option would be to pass it as an argument, unfortunately. You can pass it as ex_pid=123 and just parse that data, but it would still need to be passed as an argument but doing that you could use parse_str() to parse it.
Depending on what the script does, you could call lynx to call the actual page with the get data attached and generate a hash for an apikey required to make it run. Not sure if that is an option, but it is another way to do it how you want.
Hope that helps!
I had a real problem with this and couldn't get it to work running something like example.php?variable=1.
I could however get an individual file to run using the exec command, without the ?variable=1 at the end.
What I decided to do was dynamically change the contents of a template file , depending on the variables I wanted to send. This file is called template.php and contains all the code you would normally run as a $_GET. Instead of using $_GET, set the value of the variable right at the top. This line of code is then searched and replaced with any value you choose.
I then saved this new file and ran that instead.
In the following example I needed to change an SQL query - the template file has the line $sql="ENTER SQL CODE HERE";. I also needed to change the value of a a variable at the top.
The line in template.php is $myvar=999999; The code below changes these line in template.php to the new values.
//Get the base file to modify - template.php
$contents=file_get_contents("template.php");
$sql="SELECT * FROM mytable WHERE foo='".$bar."'";
$contents=str_replace("ENTER SQL CODE HERE",$sql,$contents);
//Another search
$contents=str_replace("999999",$bar,$contents);
$filename="run_standalone_code".$bar.".php";
//If the file doesnt't exist, create it
if(!file_exists($filename)){
file_put_contents($filename, $contents);
}
//Now run this file
$cmd="/usr/local/bin/php ".$filename." >/dev/null &";
exec($cmd);
I had completely forgotten about this question until #Andrew Waugh commented on it (and I got an email reminder).
Anyways, this question stemmed from a misunderstanding as to how the $argv array is communicated to the script when using CLI. You can pretty much use as many arguments as you need. The way I accomplish this now is like:
if (isset($argv)) {
switch ($argv[1]) {
case "a_distinguishing_name_goes_here":
$pid = $argv[2];
sample_function($pid);
break;
case "another_name_goes_here":
do_something_else($argv[2]);
break;
}
}

Categories