Making file_get_contents() session aware in PHP
Solution 1
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.
Solution 2
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();
AlexA
Freelance Python developer. Data engineer. LinkedIn Profile: https://www.linkedin.com/in/alexey-a-181a614/ AWS Certified Solutions Architect associate Tools: Django, Python, AWS, Celery, mysql, Postgresql, jquery, Backbone.js
Updated on June 09, 2022Comments
-
AlexA almost 2 years
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.
-
Gumbo about 15 yearsIt would make a valid URI. The
&
is allowed in the URI path. -
AlexA about 15 yearsI've set session.use-only-cookies=0, reloaded Apache. same problem. file() doesn't pages with session_id in URL.
-
kliron about 15 yearsOK, it's valid but not what was intended!
-
PiTheNumber over 11 yearsalso you can use the SID constant:
return file_get_contents($url. "?" . SID);
-
OZZIE over 10 yearsThat won't work if you need additional parameters in the url :(
-
Gumbo over 10 years@OZZIE Use
$_GET
for that.