YII compress your application output using gzip - yii

what is the benefit of below code that is two events.
what its actually doing ??
require_once($yii);
$app = Yii::createWebApplication($config);
Yii::app()->onBeginRequest = function($event)
{
return ob_start("ob_gzhandler");
};
Yii::app()->onEndRequest = function($event)
{
return ob_end_flush();
};
$app->run();
please explain the function of this code in my application.what it does ?? and how can it help me ??

The above code buffers the content and gzips it according to browser, rather than sending it straight away.
Yii::app()->onBeginRequest = function($event)
{
return ob_start("ob_gzhandler");
};
The above means that when the requests starts, it will buffer the content, and using the callback will set the content as gzip,deflate or none, depending on browser.
Yii::app()->onEndRequest = function($event)
{
return ob_end_flush();
};
The above code simply means that at the end of the request, it will output the buffer contents.

It buffers the content, and just before sending it the browser, asks if the browser can accept zipped content. If it can, it will zip the HTML before supplying. Otherwise, it will supply it unzipped.
Zipped content reduces the size of the HTML the browser needs to download, which can increase performance. How much performance gain your users will see depends on the size of the HTML - bigger pages will see more benefit, while tiny pages may actually take longer to render, because the browser has to unzip the content first. Use Firebug or Chrome Developer Toolbars to see whether it's worth it.
Also, check the impact on the server side. Again, the downside of increased server load can outweigh the increased client-side page render speed. Hence, it works best with lots of caching.
This is normally something you do when you are optimising the site, looking for performance gains.

if you want add gzhanlder straight to main config file you Can Set Following lines in main.php
'onBeginRequest'=>create_function('$event', 'return ob_start("ob_gzhandler");'),
'onEndRequest'=>create_function('$event', 'return ob_end_flush();'),
this Two lines Add GzipHandler

Related

How do I save the PDF to server? css2pdf#cloudformatter xeponline

I was wondering if anyone knew of a way to save the resulting PDF document to the server, instead of prompting the user to download it locally?
Using this:
http://www.cloudformatter.com/CSS2Pdf
Many thanks
Edit:
I am using the following JS to initiate the PDF.
$(function(){
$('#generatePDF').click(function(e) {
e.preventDefault();
var pdfdata = xepOnline.Formatter.Format('printableInvoice',
{
pageWidth:'216mm',
pageHeight:'279mm',
render: 'base64'
}
);
console.log(pdfdata);
});
});
Leaving the answer in place as the comments below are relevant. The original answer was how to get the source information (using the "base64" option), not the final PDF.
So to get the final PDF that is in memory, if you examine the code in Github:
https://github.com/Xportability/css-to-pdf/blob/master/js/xepOnline.jqPlugin.js
starting at the "else" at line 602 ... this "else" is executed if you force anything other than a download. If you chose "newwin" or "embed" as the method and the browser sniffing JS did not force it back to download (it does on Safari, IE and also mobile browsers), then this "else" is executed.
On a successful AJAX post, the function "xepOnline.Formatter.__postBackSuccess" is executed. This function starts at line 863. At line 865, the base64 encoded bytes of the actual PDF are loaded. If you debug your site and debug at that line of code, you can get the value of the var "base64" which will be the base64 encoded bytes.
So, if you only had Firefox and Chrome to consider, then you could do some mod to the code to post the result back to the server and not display it. If you have all those browsers to consider, you will need to add some option (like say option:'memory' which skips all browser sniffing, runs the AJAX version but with its own success function.
I can look at adding this to the library but you are free to pull it and make some mods yourself.

AWS SDK PHP version 2 - retrieving image dimensions?

Is it possible to retrieve the dimensions of an image stored on Amazon S3?
If the answer is no, are there any other ways around it other than downloading the image to my server to which sounds inefficient?
I'm using version 2 of the AWS SDK for PHP.
I've been looking through what is returned from the following code but doesn't seem to give dimensions.
$result = $s3->getObject(array(
'Bucket' => 'BUCKET_NAME',
'Key' => 'KEY_NAME'
));
var_dump($result);
I'm not 100% familiar with SDK2. With 1.5 you could do this
getimagesize($s3->get_object_url($bucket,$filename));
I think this is still possible as long as you can access publicly the image (or you have to find your way around authorized urls)
Obviously, your php must be enabled to open remote files.
I agree with the db cache. I run every image filename through a class that checks mysql for a match. If it finds one, it returns width, height and a preformatted sizetag ready to go. If the image and size are not found, it uses getimagesize() to return the same info, which it stores for next time. I also built in a resize method should I want to cheat a bit and resize the sizetag (but not the file) proportionally on the fly.
I don't know if storing the info is faster than getimagesize() as it downloads. S3 is pretty fast.
Due to lack of response I'll presume it's not possible... Didn't r3ally want to do it with JavaScript but this is how I did it.
<img src="image.jpg" id="image" />
<script>
// This runs after the image has loaded
$('#image').load(function() {
// Use the below code to get the height and width
// document.getElementById('image').width
// document.getElementById('image').height
});
</script>

Reliably getting favicons in Chrome extensions, chrome://favicon?

I'm using the chrome://favicon/ in my Google Chrome extension to get the favicon for RSS feeds. What I do is get the base path of linked page, and append it to chrome://favicon/http://<domainpath>.
It's working really unreliably. A lot of the time it's reporting the standard "no-favicon"-icon, even when the page really has a favicon. There is almost 0 documentation regarding the chrome://favicon mechanism, so it's difficult to understand how it actually works. Is it just a cache of links that have been visited? Is it possible to detect if there was an icon or not?
From some simple testing it's just a cache of favicons for pages you have visited. So if I subscribe to dribbble.com's RSS feed, it won't show a favicon in my extension. Then if I visit chrome://favicon/http://dribbble.com/ it won't return right icon. Then I open dribbble.com in another tab, it shows its icon in the tab, then when I reload the chrome://favicon/http://dribbble.com/-tab, it will return the correct favicon. Then I open my extensions popup and it still shows the standard icon. But if I then restart Chrome it will get the correct icon everywhere.
Now that's just from some basic research, and doesn't get me any closer to a solution. So my question is: Is the chrome://favicon/ a correct use-case for what I'm doing. Is there any documentation for it? And what is this its intended behavior?
I've seen this problem as well and it's really obnoxious.
From what I can tell, Chrome populates the chrome://favicon/ cache after you visit a URL (omitting the #hash part of the URL if any). It appears to usually populate this cache sometime after a page is completely loaded. If you try to access chrome://favicon/http://yoururl.com before the associated page is completely loaded you will often get back the default 'globe icon'. Subsequently refreshing the page you're displaying the icon(s) on will then fix them.
So, if you can, possibly just refreshing the page you're displaying the icons on just prior to displaying it to the user may serve as a fix.
In my use case, I am actually opening tabs which I want to obtain the favicons from. So far the most reliable approach I have found to obtain them looks roughly like this:
chrome.webNavigation.onCompleted.addListener(onCompleted);
function onCompleted(details)
{
if (details.frameId > 0)
{
// we don't care about activity occurring within a subframe of a tab
return;
}
chrome.tabs.get(details.tabId, function(tab) {
var url = tab.url ? tab.url.replace(/#.*$/, '') : ''; // drop #hash
var favicon;
var delay;
if (tab.favIconUrl && tab.favIconUrl != ''
&& tab.favIconUrl.indexOf('chrome://favicon/') == -1) {
// favicon appears to be a normal url
favicon = tab.favIconUrl;
delay = 0;
}
else {
// couldn't obtain favicon as a normal url, try chrome://favicon/url
favicon = 'chrome://favicon/' + url;
delay = 100; // larger values will probably be more reliable
}
setTimeout(function() {
/// set favicon wherever it needs to be set here
console.log('delay', delay, 'tabId', tab.id, 'favicon', favicon);
}, delay);
});
}
This approach returns the correct favicon about 95% of the time for new URLs, using delay=100. Increasing the delay if you can accept it will increase the reliability (I'm using 1500ms for my use case and it misses <1% of the time on new URLs; this reliability worsens when many tabs are being opened simultaneously). Obviously this is a pretty imprecise way of making it work but it is the best method I've figured out so far.
Another possible approach is to instead pull favicons from http://www.google.com/s2/favicons?domain=somedomain.com. I don't like this approach very much as it requires accessing the external network, relies on a service that has no guarantee of being up, and is itself somewhat unreliable; I have seen it inconsistently return the "globe" icon for a www.domain.com URL yet return the proper icon for just domain.com.
Hope this helps in some way.
As of Oct 2020, it appears chrome extensions using manifest version 3 are no longer able to access chrome://favicon/* urls. I haven't found the 'dedicated API' the message refers to.
Manifest v3 and higher extensions will not have access to the
chrome://favicon host; instead, we'll provide a dedicated API
permission and different URL. This results in being able to
tighten our permissions around the chrome:-scheme.
In order to use chrome://favicon/some-site in extension. manifest.json need to be updated:
"permissions": ["chrome://favicon/"],
"content_security_policy": "img-src chrome://favicon;"
Test on Version 63.0.3239.132 (Official Build) (64-bit)
chrome://favicon url is deprecated in favor of new favicon API with manifest v3.
// manifest.json
{
"permissions": ["favicon"]
}
// utils.js
function getFaviconUrl(url) {
return `chrome-extension://${chrome.runtime.id}/_favicon/?pageUrl=${encodeURIComponent(url)}&size=32`;
}
Source: https://groups.google.com/a/chromium.org/g/chromium-extensions/c/qS1rVpQVl8o/m/qmg1M13wBAAJ
I inspected the website-icon in Chrome history page and found this simpler method.
You can get the favicon url by --
favIconURL = "chrome://favicon/size/16#1x/" + tab.url;
Don't forget to add "permissions" and "content_security_policy" to Chrome. (https://stackoverflow.com/a/48304708/9586876)
In the latest version of Chrome, Version 78.0.3904.87 (Official Build) (64-bit)) when tested, adding just img-src chrome://favicon; as content_security_policy will still show 2 warnings:
'content_security_policy': CSP directive 'script-src' must be specified (either explicitly, or implicitly via 'default-src') and must whitelist only secure resources.
And:
'content_security_policy': CSP directive 'object-src' must be specified (either explicitly, or implicitly via 'default-src') and must whitelist only secure resources.
To get rid of them use:
"permissions": ["chrome://favicon/"],
"content_security_policy": "script-src 'self'; object-src 'self'; img-src chrome://favicon;"
Now you can use chrome://favicon/http://example.com without getting any errors or warnings.

Stop the selenium server until File uploaded

I am using a file upload task with Selenium.
The problem here is, to upload file, it is taking 5-10 seconds time. But i have to stop the Selenium server until it uploaded completely.
Here is some example code.
selenium.type("id=Fileuploader","c:\\mypic.jpg");
selenium.click("id=submmit");
It is giving error because the selenium.click statement is executing right after the selenium.type statement without waiting for the file to upload fully.
So, what should I use here to stop the Selenium server (server has to wait for sometime)?
Asynchronous requests are always hard to track. There must be some change on the page when the file is uploaded, so look for it, wait for it.
You can try waitForCondition().
Or some sort of isElementPresent() magic
final int TIMEOUT = 10000; // ten seconds
long targetTime = System.currentTimeInMillis() + TIMEOUT;
while((System.currentTimeInMillis() < targetTime)) {
if (selenium.isElementPresent("xpath=something")) {
break;
}
}
EDIT: If there's no new element, there has to be at least some sort of change. For example, if your asynchronous upload changes a value of some hidden input element, you could test for it using getValue(), or maybe just a smart locator:
isElementPresent("xpath=//input[#type='hidden' and contains(#value,'mypic.jpg')]");
EDIT2: If the element for which we check (in this case, picture preview) is present even before the upload, then it was just not visible and we can test that by isVisible()
If worst, you can always use some Thread.sleep() in the code. But the best way is to see the advanced usage - explicit and implicit waiting
After uploading the file, new element is coming which showing the preview of the uploaded element.
So, i used
selenium.isVisible("xpath of new preview element")
Put it in loop. It will work.
Thank you.

Other ways to check the file size before upload

Is there any other way that I can just check the size of a file before upload? The requirement is if the file exceeded the limit, the form mustn't submit. If it's not, I have to do the ordinary upload using the form and I don't have to exactly upload the file to the server using Flash.
Is there any other way that I can just check the size of a file before upload?
Not in JavaScript, the file size is not in the DOM.
when instantiating SWFUpload, there are two parameters you need to pass: file_size_limit, and file_queue_error_handler:
new SWFUpload({
file_size_limit: "10 MB",
file_queue_error_handler: queueErrorHandler,
[...]
})
and then:
function queueErrorHandler(file, errorCode) {
if (errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
alert("File exceeds the 10MB limit!");
}
}
this checks if the file size is within limits before starting the upload
with the W3C FileAPI (implemented at least by Firefox 3.6) you can.
See this link for details
http://hacks.mozilla.org/2009/12/w3c-fileapi-in-firefox-3-6/
Cheers
Checking the file size through the SWFUpload control is possible. Just put the SWFUpload control outside of the Web form tags. Tell the user click on the SWFUpload button and point to his upload file. Use javascript to determine the file size, then utilize this information as you see fit such as populating a validation function. Then your main form will need to ask the user to point to their upload file again, and it is this field which will do the actual uploading of the file. When the form is submitted, the SWFUpload control will be completely ignored since it's not part of the main form.