So in my HTML markup I have an image tag like this one:
<img src="image_generation.php" alt="template" id="image" />
And the 'src' attribute links to a PHP script that generates an image using a couple of variables defined there which are mostly randomly generated.
Now, what I want to be able to do is to access those random variables in the page which includes the image generation script. I suppose I could send cookies and access them after the image tag as they technically should be readily available to the including file. I don't want to send too much information, just a couple (10-20) variables. Not sure if in that case sessions would be a better choice, as I would have to send several cookies. Sessions also pose a problem as the including script gets the old session and I would have to refresh the page to obtain the values of the previously generated image. I suppose I could also set up a DB and access the DB in the including script, but the variables are temporary and I would have to delete them and that seems like a lot of fuss to me.
The image generation script finishes with:
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
And nothing can be sent to the browser before the header call or else the image won't be displayed. If I use cookies or sessions, the image_generation.php would have to send both the image and set the cookie(s)/session.
None of the options (cookies, sessions or DB) really convince me, as there are problems with each in this particular situation. Can you think of a way to solve this? Thanks.
MAJOR EDIT #1:
Including script gets session of previously generated image without refreshing / Setting cookie(s) and/or a session in included script before / after sending image without output buffering does not pose a problem.
You can use a $_SESSION, but to make the session available in the same script that included the <img> tag (which would have executed before the image script), you would need to make AJAX calls via JavaScript. An AJAX handler that runs at window.onload should have access to the $_SESSION created by the image script, since the image should have fully loaded when it executes.
Example PHP handler getsession.php:
header('Content-type: application/json');
// Simply part of the session into JSON
// Obviously you would want to limit this to only the variables
// that should be sent back, so you don't expose the session on the client side!
echo json_encode(array($_SESSION['var1'],$_SESSION['var2']));
exit();
Example AJAX call (using jQuery since it will be easy to get started with)
// Variable to hold the object returned by PHP
var imgPHPSession;
$(window).load(function() {
$.ajax({
url: 'getsession.php',
dataType: 'json',
success: function(data) {
imgPHPSession = data;
}
});
});
Update:
It can be done entirely in PHP, but would require changing your design a bit such that the variables necessary to generate the image are created in $_SESSION by the main script. They are then available in $_SESSION to image_generation.php to be used as needed, but are already known to the main script.
Update 2:
Since the image vars contain info about how it was created, if the image is not too large, you can actually create it in the main script and store it to disk. The image_generation.php script can still be used as the <img src>, but its purpose would then be to retrieve the correct image from disk and serve it back to the browser and delete it from disk when no longer needed. The $_SESSION is then available to both the main and image scripts.
You can pass you parameters to src attribute, for example:
<img src="image_generation.php/user/1/name/tom/param1/variable2"
or
<img src="image_generation.php?user=1&name=tom
this solution lets you forget about session, cookies - it's stateless
Php can do smart tricks with buffer by ob_* function, so at the beginning of your script you can call ob_start() to buffer every php output, it lets you avoid all 'Header already send' errors.
Your image_generation.php does not need to send any cookie. This script will receive cookie with sessionid (browser attach cookie information to every request to the server) what makes possible identify user session on php side - after that you have access to every session parameters.
Related
I have a download.php page which will be invoked everytime a user clicks "Download" button on my page. The file is around 1 GB. However, the current page got blocked before the file is completely downloaded. Is there a way I can make this an async task so that the user can still use the website while the file is being downloaded to his computer.
Thanks.
If you are using sessions, then before you begin any long running process you should call session_write_close() or you will get blocking site-wide. From the docs there:
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time.
So, if you have a long running script that called session_start() and did not call session_write_close() then the result is, any page that needs to access a session now has to wait for the long running script to finish execution before it can begin. Thus, site-wide blocking.
This may or may not solve your issue, because I'm not sure what you mean by "blocking" in your question.
First Create your download links like this :-
<a class="download" href="/myfiles/video/file.pdf"> Dow
nload file.pdf
then in Jquery :
$(document).ready(function(){
$(document).on('.download', 'click', function(){
var href = $(this).href;
$('<iframe />', { src : href }).appendTo('body');
return false; // prevent from default action, can be done with e.preventDefault() also
}) // __download
}); // __ document ready
This technique use by many big sites like facebook, github etc, and it will not block current page, everything will be working like before but browser will show file save dialog to download file, I did not test this code so there may be some syntex error, Thanks :)
i've got a slight problem with JS enabled detection.
not too big, because i know i'm on the right track.
but here's my deal:
when i try to set a cookie in JS (jQuery) using this code
$(window).load(function(){
$.cookies.set('c_jsEnabled', 'true');
});
or just in plain JS using this code
function setCookie()
{
document.cookie='c_jsEnabled=true';
}
<body onload="setCookie();">
and then try to detect it in PHP using this code
if($_COOKIE['c_jsEnabled'] == 'true')
{
if(file_exists('./main.php'))
{
require_once ('./main.php');
}
echo getIndex();
}
else
{
if(file_exists('./noJS.php'))
{
require_once ('./noJS.php');
}
echo getIndex();
}
setcookie('c_jsEnabled', '');
it takes 2 page refreshes to actually get the right value into PHP.
my guess is that this bascially means that the PHP script is executed before the JS function is fired.
could this be because all codes shown above are in the same script (index.php)?
This is kind of a problem for me, because i want to prevent people from using my website when they have JS disabled.
is there a way to set the cookie before php tries to get the cookie variable?
PHP is always "fired" before JavaScript because PHP is processed on the server and then sends out the HTML and JavaScript for the browser to process and render. You can never expect JavaScript to execute before PHP for this reason.
In your case, use JavaScript to set the cookie and then do a redirect to refresh the page so PHP can get the cookie value and act accordingly.
You should be setting the cookie directly from the PHP file. That way, you know that it exists, and more importantly, you have control of the cookie. You can set it from the client, but that will always execute after the HTML has been sent to the browser, so the PHP file won't get it until the next request.
PHP only sends the cookie header when content is sent to the browser. Javascript then executes after that, so you would need a second load of the page to detect the cookie.
This can trigger infinite redirection loops (especially if the user has cookies disabled), so be careful.
To disable the site to users without Javascript, consider the following.
<div id="noscript" style="width:100%; height:100%; z-index:999; position:absoloute; top:0px; left:0px; background-color:#CC9900; display:block">
Please Enable Javascript!</div>
<script type="text/javascript">
document.getElementById('noscript').style.display = 'none';
</script>
I find the <noscript> tag is unreliable (there was a bug in iOS causing it to only show when there was Javascript, if I remember correctly).
A second option:
You can have the PHP check for a cookie. If it isn't set, have it redirect (header("Location: aaa.html");) to a page with the Javascript to set the cookie and redirect back. (Alternatively, have the PHP output Javascript to set the cookie reload the page.) You then only have to worry about users who "spoof" the cookie, although you will also lock out users who have cookies disabled.
Nope - PHP will always be called before client-side JavaScript, so with this method you'll always have to refresh the page at least once. You're better to develop your site so that non-JS users have a worse-but-still-acceptable experience, or at worst use the <noscript> HTML tag to serve alternative content to those users.
You can't get a cookie in PHP that's being set by JavaScript before the page renders/executes.
You could set the cookie using PHP, however. That will ensure it's set and available regardless of JavaScript or multiple page refreshes.
I set the cookies regularly in a callback page in my Twitter application. Everything works fine.
Now, using jQuery, I submit a form, and the callback function activates a PHP script. That script only needs to set one cookie to the serialized values of $_POST; and the values run fine (both serialized and normal, I echoed them out to debug). The expiration time is set to 1 year ahead. But for some reason, the cookie just won't appear anywhere. Here's the code:
// js/main.js
$('#settings-form').live('submit', function() {
$.post('controllers/settings.php', $(this).serialize(), function(data) { // Everything here works.
if (data == 'OK') // no errors spits out "OK". this works
changeView({'msg': 'Your settings were saved successfully.'}); // This just resets the view and adds a message div at the top. This works
else
changeView({'msg': data}); // This echoes the error if any exists. Doesn't happen, no errors arise
});
return false; // Cancels redirecting after submitting form
});
// controllers/settings.php
setcookie('user_settings', serialize($_POST), strtotime('+1 year'));
I checked all the variables and I even tried setting dummy ones for test (like "boo" instead of serialize($_POST). for some reason that doesn't work.
Any ideas why this is happening? I tried doing a chdir('..'); to make the cookie dir go to the right place, but that doesn't seem to be the problem, checking the cookies inside my browser doesn't seem to work at all, for any path. It just doesn't work at all. I also just tried manually changing the domain and path, but those don't work either.
Firstly, the chdir() thing is a red-herring -- Cookies are domain-specific; the directory path doesn't have any bearing on them.
Cookies can work a bit strangely when you're making ajax type calls, and I think this is what you're seeing -- The server is probably setting the cookie, but the browser may not be setting it in the cookies data it as it's not a page load.
I would suggest you'd be better off using PHP's session handling rather than cookies; it's better for security, less bandwidth (because the whole of the cookie data is transmitted in both directions with every http single request), and more likely to work.
If you really want to use cookies, it may work better if you use Javascript to do it. You can set cookies in your javascript code by accessing document.cookie. (you need to get the syntax right for the cookie string, but JQuery probably has its own functions that makes them easier to work with)
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) );
Is there a way in PHP to get a list of all sessions (and the variables within each) on the server?
Basically, we have a maintenance function which needs to know which users are currently logged into the site. We already store data for each user in a session variable, but I am hoping that I can loop through each of these sessions and pluck out the data I need.
MY PHP is very limited (I am a .Net developer ussually) but if anyone knows if this is even possible (and how to do it) I'd be very grateful. I googled this, and the results I found tended to inidcate that it WASN'T possible, but I find this very hard to accept.
Still, If you can't you can't but I thought my buddies on StackOverflow could give me a definitive answer!
PHP stores session data for each user in a temporary folder on the server. This folder is defined in the php.ini configuration file under the variable session.save_path. Locate this value from within your php.ini file, or alternatively, create a php file with:
<?php echo "Session Save Path: " . ini_get( 'session.save_path');?>
as it's contents, and open the file in your browser.
Once you find the save path for the session data, open up that folder and you'll notice a fairly simple structure. All sessions are stored in the format: sess_$SESSIONID .
Session data is serialized before being stored on disk. As such, objects stored in the session file would have to be deserialized before being usable. However, if you're using plain text, which is stored as-is, to store your session data (ex. $_SESSION['userid'] = 1234) to store information about your users, it should be easy enough to parse out the data you're looking for from within the files.
One more thing ... I haven't looked into it, but it appears as though the session ID that appears in the filename corresponds directly to, for instance, the name of the PHPSESSID cookie stored on the user's computer. So, with this in mind, it may be possible to loop through the files within the temporary session directory, acquire all the $SESSIONID values, set the current session ID using session_id($SESSIONID), start a session with session_start() and access the data you need through PHP without having to parse the contents files themselves. Can anyone confirm whether or not this would be possible?
Edit: Adjusted post to match Itay's comment.
This will get you the data for all sessions, stored in an array and indexed by session id:
<?php
$allSessions = [];
$sessionNames = scandir(session_save_path());
foreach($sessionNames as $sessionName) {
$sessionName = str_replace("sess_","",$sessionName);
if(strpos($sessionName,".") === false) { //This skips temp files that aren't sessions
session_id($sessionName);
session_start();
$allSessions[$sessionName] = $_SESSION;
session_abort();
}
}
print_r($allSessions);
Here's a more succinct way to get a list of sessions via the stored files:
<?php
print_r(scandir(session_save_path()));
?>
I used the #mgroat method in the ajax call, but there is a problem in the header of the HTTP response that the Set-Cookie header appears multiple times and jQuery reports an error:
Set-Cookie header is ignored in response from url:
mysite.com/admin/ajax/main_ajax. Cookie length should be less
than or equal to 4096 characters.
The solution is to add header_remove("Set-Cookie") right after session_start().