Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making file_get_contents() session aware in PHP

Preamble: My app is mod_rewrite enabled and I have index.php page that downloads vaious pages based on Request_URI and prints them as page content.

Problem: File() or File_get_contents() function is excellent at downloading my other app pages. But as soon as I try to use it to download a page that is session enabled, I start having problems.

The main problem is that when I try to pass existing session id to url from the page I download, e.g.

  $url = "http://localhost/EmplDir/AdminMenu.php";
  return implode('',file($url. "&" . session_name() . "=". session_id()));

My page never loads (or file() never loads content). I suspect I shoud use curl functions here, but it has too many options. My be an advice which curl options to use to make downloadable pages know about current PHP session would be helpful.

P.S. The above seems to be true both for Windows and Linux.

like image 838
AlexA Avatar asked Mar 14 '26 12:03

AlexA


2 Answers

You didn't separate the query string from the rest of the URL with a ?

Try

return file_get_contents($url. "?" . session_name() . "=". session_id());

You will also need to be sure the server doesn't use the session.use-only-cookies configuration setting.

There's no reason why the script shouldn't see the query string and act on it, you can persuade yourself by writing a script which just does var_dump($_GET) and requesting that as above. If you see the query arguments in the output then you simply need to debug your script to see why it doesn't behave as expected given the session id.

NOTE: I'm assuming that you wanting to request a file from the same domain as your application, otherwise using your session id for a remote site doesn't make much sense.

like image 136
Paul Dixon Avatar answered Mar 16 '26 02:03

Paul Dixon


If your script doesn’t alter any superglobal variables, you could just include it:

ob_start();
include $_SERVER['DOCUMENT_ROOT'].'/EmplDir/AdminMenu.php';
return ob_get_clean();
like image 25
Gumbo Avatar answered Mar 16 '26 02:03

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!