"file_get_contents" does not work as expected - php

I setup a function to get the output of another page. But i am only getting back the file contents. I cant figure out why? Here is my code:
$from = date('d.m.Y');
$to = date('d.m.Y', strtotime('+30 day', time()));
$postdata = http_build_query(
array(
'set' => $from,
'to' => $to
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$list = file_get_contents($_SERVER['DOCUMENT_ROOT'] . 'Events.php', false, $context);

file_get_contents() on filesystem will read the file as a text file. You have to call it through its uri instead to get it to execute.
it is not 1 function, but two, alternating what it does given filesystem (pretty much fopen the file, read the entirety of the file, return the content), and what it does given a url (do a GET call on the url, get its contents, return the entirety of its contents)
so just replace $_SERVER['DOCUMENT_ROOT'] with $_SERVER['HTTP_HOST'] and you should be ok

If you want to include another local php file you have to include() or require() it.
$list = include($_SERVER['DOCUMENT_ROOT'] . 'Events.php');
While include() throws a warning if the file does not exist or is unreadable, require() throws a fatal error. With this way you get what the named file returns using the return-keyword.
To get the php output you can use ob_start():
ob_start();
include($_SERVER['DOCUMENT_ROOT'] . 'Events.php');
$list = ob_get_clean();
Another way is to use a separate http-Get but this means more overhead.

Related

Receive PHP code with an POST request

I need to send a POST request to another file called global.php, for this I try this code below:
$url = 'global.php';
$data = array('stack' => 'overflow');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
This is the global.php file that should process the request:
if(isset($_POST['stack'])){
echo 'exists';
}else{
echo 'error';
}
The problem is that instead of the command var_dump ($ result); show exists, it shows the PHP code? how can I solve this problem?
And why when I try to do the same thing using ajax it returns me the text exists and not PHP code?
You should use full url, to process php file through server.
$url = 'http://YOURURL.com/global.php';
AJAX call is made from browser, to absolute URL, thats why You are getting desired response.

file_get_contents return all php code

I want to send a POST request to some file when I load index.php. I use this code:
$query = http_build_query(array('ajax' => 'gwonline', 'session' => $current_session));
$contextData = array (
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents(PATH::Includes . 'ajax.php', false, $context);
$result_decoded = json_decode($result, true);
echo '<div id="gwonline">' . ($result_decoded['isonlinestr'] ?: '<span class="fa fa-circle" style="color:orange"></span> Unavailable') . '</div>';
The problem is, $result ends with getting the PHP code instead of whatever the file actually printed. How can I fix it without changing the site to http://... as it's not an option for me at the moment.
Use include with output buffering. file_get_contents is reading the file from the filesystem, it isn't going to use PHP to analyze it. The only reason it works when you use http:// is because then the web server is serving the file, not the filesystem.
ob_start();
include "ajax.php";
$result = ob_get_clean();

error writing xml data from post request in PHP

im trying to simulate a webservice post request via my local machine using PHP, and im getting some problems.
First of all, I have a php file that is sending an xml file via Post, inside an array:
<?php
$xml = file_get_contents('localstorage.xml');
$url = 'http://127.0.0.1/projects/My_webservice/rebreFitxer1.php';
$post_data = array('xml' => $xml, );
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
?>
Then in the other side i have another php file that loads the xml content and writes it on a xml file.
<?php
header('Content-type: text/xml');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$postText = file_get_contents('php://input'); // load the content loaded via POST
$postText = utf8_encode($postText);
$datetime = date('ymdHis');
$xmlfile = "myfile" . $datetime . ".xml"; //new file name
$FileHandle = fopen($xmlfile, 'w') or die("can't open file");
// open the new file in writing mode
fwrite($FileHandle, $postText);
fclose($FileHandle);
?>
What i get from this is a bad formed xml wich i tried to convert encoding but nothing seems to operate.
Here's what i get:
xml=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf-8%22%3F%3E%0A%3CXml...........etc
---^
It seems that symbols "< >" are not well written--> Nom%3ERetard%3C%2FNom%3E%0A++++++%3C
but i dont know how to fix it
I'm new on php and im sure that there's something i've done bad...
Thanks in advance
Your XML should be stored in $_POST["xml"] variable. So you can try:
<?php
$postText = $_POST["xml"];
?>

Performance issue with php remote url fread operation

I have a performance problem with my script (below).
The fread operation takes a lot of time, I get times like:
$time_split2 == 0.00135s
$time_split3 == 15.01747s
I have tested it even with a remote script that does nothing except echoing OK message - there is still the aprox. 15 seconds execution time
What could be the problem or how could I solve it another way.
I would prefer not to use curl (would that speed up things?) since the curl is not always installed with PHP, and I would like my code to be portable
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array('Content-type: application/x-www-form-urlencoded', 'Custom-header: test'),
'content' => $postdata,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$time_split = microtime(true);
$fp = fopen('http://someremotedomain/script.php', 'r', false, $context);
$time_split2 = microtime(true);
while(!feof($fp))
$result .= fread($fp, 4096);
fclose($fp);
$time_split3 = microtime(true);
$time_split2 = round($time_split2 - $time_split, 5);
$time_split3 = round($time_split3 - $time_split, 5);
UPDATE
I have used your suggestions - file_get_contents() + Connection: close - it doesn't work yet - file_get_contents() works with a delay and returns an empty string but - I have isolated the problem, here is the $postdata:
$postdata = http_build_query(
array('body' => $mail_html_content,
'from' => 'test <test#test.com>',
'to' => 'test2 <test2#test.com>',
)
);
when I remove 'body' from the array - file_get_contents() works fine and without any delays - how could this create a problem - $mail_html_content contains just a simple HTML string and it is not a big string
UPDATE 2
I have isolated the problem even more - when the length of the $postdata string exceeds 1024 chars, file_get_contents() starts to return empty values, below that value everything works fine, since method POST isn't limited by length of the data (at least for such low numbers) what could be the problem now??
You should try file_get_contents() instead of use while(!feof($fp)).
E.g.
/* EDIT: header should be something like that */
$opts = array(
'http' => array(
'method'=>"POST",
'header'=>"Content-Type: text/html; charset=utf-8",
),
);
$context = stream_context_create($opts);
$result = file_get_contents('http://someremotedomain/script.php', false, $context);
For other header information look here
Reason
according to fread documentation:
Note:
If you just want to get the contents of a file into a string, use file_get_contents() as
it has much better performance than the code above.

Retrieving a PHP file using file_get_content(), cURL() or fopen() all return PHP code itself

I'm retrieving a PHP file using file_get_content(), cURL() or fopen() all return PHP code itself. It's not retrieving just the HTML code itself that PHP is outputting. How can I overcome this please?
It's basically generating an HTML newsletter preview for my customer that is generated from their CMS. However I want them to be able to copy and paste the HTML it generates into Mailchimp or such like. It just fetches the entire PHP source code though as well as the HTML :(
Hope you can help.
Thanks in anticipation.
Pete
Trying to read a local PHP file will return its source code, since its a "local" file, and is not parsed by the server.
If you wish to read the result of the PHP file you must request it from the server.
Meaning instead of doing:
$data = file_get_contents('x.php');
You should be doing
$data = file_get_contents('http://mysite.com/path/x.php');
Which will be parsed in the server, and then returned to you.
Cheers! :)
Shai.
This will work in localhost. Try this one: $url = "http://localhost/box.php";
function isAllBoxContents($boxid,$pageNum)
{
$postdata = http_build_query( array('myBoxid' => "$boxid", 'isAllBoxContents' => "all",'pageNum' => "$pageNum",'innerReq' => true ));
$opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ));
$context = stream_context_create($opts);
$url = "http://localhost/box.php";
$result = file_get_contents( $url, false, $context);
$cacheFileName = "isAllBoxContents".$boxid.$pageNum;
cacheMe($cacheFileName,$result);
}

Categories