Making file_get_contents() session aware in PHP - 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.

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.

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();

session_name and session_id gives you the current scripts session; Not the remove server. You need to use something that understands http. Curl would do, or you can use something like SimpleBrowser, which completely emulates a browser.

Related

Unable to read a cookie from perl when set by a php webpage

I have 2 webpages under the same host. 1 in php and 1 in perl cgi.
The php page is setting a cookie "c" under a domain "d.com" and path "/".
In perl I am trying to read the value of the cookie "c".
I tried the following code :
use CGI;
use CGI::Cookie;
my $query = new CGI;
print $query->header();
#... some more code ...
$thecookie = $query->cookie(-name=>'c', -domain=>"d.com", -path=>"/");
print $thecookie;
Any help/idea would be appreciated.
Thanks.
For anyone that had this issue. The solution was simple.
The problem is that the cookie was set to "secure" which force the browser to send the cookie only over https.
Since the perl page was accessed via http, the browser was not returning the cookie. Simple as that.
Accessing the page via https fixed the issue.

PHP load function not working

I am using formmail by tactite to have the info submitted from my form get emailed to me. After the user hits the submit button, it goes to a "Thank You" page that by default just has some text, I'm trying to change that to load up a thank you page that I created and it doesn't work, what am I doing wrong?
Thanks!
Here's what doesn't work:
// MSG_THANKS_PAGE is the default page that's displayed if the
// submission is successful
// Parameters: none
$aMessages[MSG_THANKS_PAGE] = load('http://nimbledesigns.com/kelsie/thankyou.html');
This is what i had there before that DOES work:
$aMessages[MSG_THANKS_PAGE] = 'Thanks!<br /><br />'.
'Go Back'.
'';
Tere is no load() function built into PHP. Most likely what you're looing for is file_get_contents(), which'll retrieve the contents of a file (local or otherwise) as a string.
If that URL points back to your own server, you may want to save yourself a full HTTP round-trip and simply use a local path ... = file_get_contents('/path/to/that/thank/you/file.html').
File_get_Contents()
use
$aMessages[MSG_THANKS_PAGE] = file_get_contents('http://nimbledesigns.com/kelsie/thankyou.html');
instead.
Documentation
file_get_contents() - http://php.net/manual/en/function.file-get-contents.php
Alternatives'
If that file is on your server, then you may only need to do this:
$aMessages[MSG_THANKS_PAGE] = file_get_contents('thankyou.html');
That will stop PHP from using the HTTP stream connector and will use the File IO connector instead, which is going to be faster with less overhead (although the difference may only be viewable when your server is running slowly)
Redirects
You could also redirect them to the page, by issuing this command before you send any data to the browser:
header('Location: thankyou.html');
exit();
This will redirect their browser to the file. Again assuming it resides on your server. You could replace that with a the full address if required http://nimbledesigns.com/kelsie/thankyou.html
As stated earlier, file_get_contents is your best bet. There is no load() function.
But why not just redirect to the page?
It says how to here: http://www.tectite.com/fmhowto/redir.php
(I'm assuming that's the form mailer you're using, and "tactite" was a typo).
haven't used php load for a long time, but isn't it just for xml and returns an object?
is this? http://php.net/manual/en/domdocument.load.php

PHP: invoking remote server from my php server?

how can I invoke a php script on a remote server from my server code ?
I'm currently using:
header('Location: http://www.url.com/script.php?arg1=blabla');
in my code, but it doesn't work.
thanks
If you mean by invoking just "calling" it, so you only need it to run, then you can use curl.
If you mean by invoking that you want it to act the same as include, then you can't trough http (the server does ofcourse not return code, but runs it). You might be able to obtain the file trough other means (ftp?), and then include it, but that seems like a bit of a hack.
If you mean by invoking that you want to redirect the user to the page, then this should work:
header('Location: http://www.site.nl/');
exit;
(your script continues to run after a header call, so you might need to call that exit). How doens't your code work for you? (I'm guessing because you want one of the other options)
If you only want to invoke the script you can simply use $result = file_get_contents('http://www.example.com/');.
Your version using header() will as said above redirect the user.
Use cURL, it gives you much wider manipulation options.

How to set a cookie with a php script thats executed by Flash?

I have a flash upload script, that uses a .php file as the processor. I need the processor file to set a cookie with a gallery ID that was created by php script, and pass it on to the confirmation page. Except when Flash runs the php file... it doesnt set the cookie. It does set the session variable, which was good enough, but now Im using lighttpd for the site (including the confirmation page) and apache for the actual uploader processor script (because lighttps sucks at uploading large files), so the session vars don't get transferred between the 2 server software.
How can I transfer a variable from the php processor (running on apache) to a confirmation page running lighttpd?
Well I would assume that it doesn't set a cookie as it was called by a flash script not a browser, and cookies are stored by the browser.
The only ways I can think of are a mysql database, or simply a text file.
Just thought of a second solution which is probably less efficient than Nico's but may be better suited to you. If the cookie being sent to Flash isn't being sent to the browser also, you could use Flash's ExternalInterface class to pass the contents of the cookie to a javascript function which would set the cookie in the browser. Or you could call a javascript function which will make an AJAX call to fetch the contents of the cookie.
Not sure if we're doing the same thing, but I had a similar problem, not being able to set a cookie from a php script run through flash. However I later realized it failed because I was missing arguments.
flash.swf:
sendToURL('script.php?val=dataFromFlash');
script.php:
//setcookie('flashData', $_GET['val']); //this did not work
setcookie('flashData', $_GET['val'], '0', '/'); //this worked
The PHP manual says that only the name argument is required, but I had to specify the expire and date arguments to get this to work. Perhaps this is because, as Nico's answer indicates, it is not sent through a browser? Anyway, hope this helps.
here find best solution for store all upload images data in flex with php script
$array = array();
$array["large_filename"] = $image_file_name;
$array["large_path"] = DIR_WS_IMAGES_TEMPIMAGES . $image_file_name;
$setcookie = serialize($array); setcookie( "ImageCookie",
$setcookie, time()+(60*60*24*15) );

how to prevent PHP's file_get_contents( )

one of my php page returns data like this:
<?php
//...
echo "json string";
?>
but someone else use file_get_contents() to get my data and use in other website.
can anybody tell me what can i do to prevent such thing happen.
i consider if i can get the request's domain name to echo something else.but i dont know
the function to get request's domain name.and if the request is sent by a server,that
will be unhelpful. My English is poor, to express doubts, please bear with.
you can also use sessions. if somewhere in your application, before the user gets the json data, you start a session, then in this page where you are outputting json data, you can check for the session variable. this way only users that have passed the session generator page, can view your output.
suppose you have page A.php that generates the session. use this code before outputting anything in this page.
session_start();
$_SESSION['approvedForJson'] = true;
then in your page where you are outputting json data, before outputting anything, call session_start() again. the beginning of your PHP code is a good place to call it.
then before outputting the json data, check if the session variable for approved users exists, or not.
if ( isset($_SESSION['approvedForJson']) && $_SESSION['approvedForJson'] ) {
echo "json data";
} else {
// bad request
}
You can use $_SERVER['REMOTE_ADDR'] to get the address of the client address. You can also check $_SERVER['HTTP_REFERER'] and block external requests that way, but it's less reliable. There's probably a few other techniques involving $_SERVER that you can try.
Your fighting an uphill battle here. I am assuming your serverside process that responds in json is being consumed via javascript in your users browsers... so there is no easy way to encrypt it. You might try some of the techniques used to prevent xspf (see http://en.wikipedia.org/wiki/Cross-site_request_forgery ). If you developed the client to pass along some session token that is uniq per client you could reduce some of the problem. But, chances are whoever is stealing your data is gonna figure out whatever mechanism you put in place ... assuming this is some sort of ajax type thing. If its a server-server thing then as sli mentions, setting up some restrictions based on the remote ip would help, plus setting up some sort of API authentication tokens would help even more (see oauth for some pointers)
You could also using .htaccess with apache block every external request to the page if it get's called internally or block every request that is not from your domain:
Google search thingie
EDIT
You could also use some php file which includes the file which can not be read. So for example you have file.php:
<?php
$allowedFiles[] = 'somefile.php';
$allowedFiles[] = 'someotherFile.php';
$allowedFiles[] = 'jsonReturnFile.php';
if(in_array($_GET['file'], $allowedFiles)){
include( "include/".$_GET['file'] );
}
?>
Then you can allow file_ get _contents() on that file and write a rewriteRule in your .htacces to disallow any request to the include/ folder.
RewriteRule include* - [F,NC]
That will return a 403 forbidden error for a request to that directory or any file in the directory.
Then you can do you JSON request to something like: file.php?file=jsonReturnFile.php&someothherParamReadByJsonFile=1
And when someone tries to get the file contents for the JSON file they will get the forbidden error, and getting the file contents for the include.php won't return anything usefull.

Categories