I don't have much experience with caching using .htaccess. I found some snippets and that worked for static resources (like imgs, js, css etc), but in my project I have to include a CDN that has a different expiration time.
How can I increase my CDN cache time without it affecting my PageSpeed at Google insights.
I have attached the image as well:
what you need to do is to import all the .js files dynamically into our website.
To do on PHP use the file_get_contents() function.
The first thing to do is to locate the external script:
<script type="text/javascript" src="https://ssl.google-analytics.com/ga.js">
</script>
The next step is to create a .php file. Let’s call it externaljs.php. Insert the following code in it:
<?php
$files = array(
'ga.js' => 'https://ssl.google-analytics.com/ga.js',
'bsa.js' => 'https://s3.buysellads.com/ac/bsa.js',
'pro.js' => 'https://s3.buysellads.com/ac/pro.js'
);
if(isset($files[$_GET['file']])) {
if ($files[$_GET['file']] == 'ga.js'){
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + ((60 * 60) * 48)));
// 2 days for GA
} else {
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); //
Default set to 1 hour
}
echo file_get_contents($files[$_GET['file']]);
}
?>
Lines 3 to 7: An array containing the accepted files is created. This is super important since otherwise any file could be embedded into your site, leading to potential security problems.
Lines 9 to 14: Since we need to adjust the expiring time for every script, we need a conditional statement to do so.
Line 16: If the script passed out as a GET parameter is found in our array, we can now
safely display it.
You’ll need to adjust the code and enter the URLs of your external scripts. Once done, just upload it onto your server. If you’re using WordPress, it’s a good idea to put the file in your theme folder.
Then, simply replace the external .js call and replace it by a call to your externaljs.php file, as shown below:
<script type="text/javascript" src="externaljs.php?file=ga.js"></script>
And you’re done. You can now dynamically import external .js file on your server and therefore, set the right expire header for each script
You seem to be pulling in js for analytics and ads stuff. You should be using the amp-analytics and amp-ad tags and not trying to pull in the js.
Related
Can anyone please help me to understand the syntax error based on the attached screenshot below?
My script is supposed to access a given JSON and return the specific value, but somehow it's returning this error.
Edit 1
I tested my script with a dummy JSON and the script didn't return any error, so I suspect my original JSON might be giving problem. Here's my JSON.
{
"og_object": {
"id": "1192199560899293",
"description": "Hi everyone I have an important announcement to make. So ever since Penny started school, I've been having mixed feelings. \u00a0Besides having a bit of space to myself to breathe and rest my brain/legs, I'm actually a bit bittersweet cos my little baby, who used to sleep at weird hours and gobble puree",
"title": "Fighter and Penny's new sibling",
"type": "article",
"updated_time": "2017-04-12T01:17:57+0000"
},
"share": {
"comment_count": 0,
"share_count": 109
},
"id": "http://fourfeetnine.com/2017/03/05/fighter-and-pennys-new-sibling/"
}
Edit 2
Here's my script that I run that produces the error.
var objects = require('./output.txt');
console.log(objects);
output.txt is the file that contains the JSON that I pasted in Edit 1
var objects = require('./output.txt');
The require() function belongs to the module loading system. Despite the name, it can actually load several types of files and directories and not only Node modules. As per the high-level algorithm in pseudocode shown in docs:
require(X)
If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
[...]
LOAD_AS_FILE(X)
If X is a file, load X as JavaScript text. STOP
If X.js is a file, load X.js as JavaScript text. STOP
If X.json is a file, parse X.json to a JavaScript Object. STOP
If X.node is a file, load X.node as binary addon. STOP
Since you get SyntaxError, output.txt does not contain valid JavaScript code.
If you really want to load JSON, you need to enforce subrule #3 by renaming the file to output.json.
Thanks to #Jordan suggestion. The fault is indeed due to wrong file extension. After changing the file extension from .txt to .json, then the syntax error disappeared.
I would just like a simple browser automation that increments one number in a URL and downloads the information from that place. For example, if the address looks like this:
www.test.com/something/part1_0.jpg
How could I increment the '1' and download the file from each successive web page?
Thanks
P.S. I'm using OS X 10.9
Here's a ruby solution using open-uri:
require 'open-uri'
(1..100).each do |num|
File.open("part#{num}_0.jpg", 'wb') do |f|
f.write open("www.test.com/something/part#{num}_0.jpg").read
end
end
This snippet A) creates a range of numbers; B) iterates over the range of numbers; C) opens an image file in binary mode and interpolates the current number into the file name; and D) reads the image from the URL and writes it.
But the easiest way would probably be to use curl from your command line:
curl -O www.test.com/something/part[1-100]_0.jpg
Depending on the number of webpages that you need to access, modify the numbers in brackets accordingly.
I'm trying to access a page from another domain, I can get all other html from php, but the files like images and audio files have relatives paths making them to be looked inside the local server whereas they're on the other server.
I've allowed cross-domain access though PHP from the other page.
header('Access-Control-Allow-Origin: *');
Then I use AJAX load to load that pages' content.
$('#local_div').load('page_to_load_on_side_B #div_on_that_page');
Now, the path looks like this:
../../user/6/535e55ed00978.jpg
But I want it to be full like.
http//:www.siteB.com/user/6/535e55ed00978.jpg
Correction: I have full access to both sites so I need to get the absolute paths from the site where these files are originating.
For this problem would use one of the following:
Server Side Approach
I would create a parameter in server B named for example abspath. When this param is set to 1 the script would start an output buffer ob_start() then before submiting would get ob contents with ob_get_clean() and finally using regular expressions make a replace of all urls for http//:www.siteB.com/. So, the script on server A would look like follows:
<?php
$abspath=(isset($_REQUEST["abspath"])?$_REQUEST["abspath"]:0);
if($abspath==1) ob_start();
// Do page processing (your actual code here)
if($abspath==1)
{
$html=ob_get_clean();
$html=preg_replace("\.\.\/\.\.\/", "http://siteb.com/");
echo $html;
}
?>
So in client side (site A) your ajax call would be:
$('#local_div').load('page_to_load_on_side_B?abspath=1#div_on_that_page');
So when abspath param is set to 1 site B script would replace relative path (note I guessed all paths as ../..) to absolute path. This approach can be improved a lot.
Client Side Approach
This replace would be done in JavaScript locally avoiding changing Server B scripts, . The replacements in Javascript would be the same. If all relative paths starts with ../.. the regex is very simple, so in site A replace $('#local_div').load('page_to_load_on_side_B #div_on_that_page'); for the following (note that I asume all relatives urls starts with ../..):
$.get('page_to_load_on_side_B #div_on_that_page', function(data) {
data=data.replace(/\.\.\/\.\.\//, 'http://siteb.com/');
$('#local_div').html(data);
});
That will do the replacement before setting html to DIV so images will be loaded from absolute URL.
Ensure full CORS access to site B.
The second approach is clean than the first so I guess would use Javascript to do the replacements, both are the same only changes where the replace is done.
There is a PHP function that can make absolute path from relative one.
realpath()
If you mean URL path, simply replace all occurences of "../" and add domain in front.
Try this one:
function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach($from as $depth => $dir) {
// find first non-matching dir
if($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}
Also you can find below solution:
In general, there are 2 solutions to this problem:
1) Use $_SERVER["DOCUMENT_ROOT"] – We can use this variable to make all our includes relative to the server root directory, instead of the current working directory(script’s directory). Then we would use something like this for all our includes:
include($_SERVER["DOCUMENT_ROOT"] . "/dir/script_name.php");
2) Use dirname(FILE) – The FILE constant contains the full path and filename of the script that it is used in. The function dirname() removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:
include(dirname(__FILE__) . "/dir/script_name.php");
You may also use basename() together with dirname() to find the included scripts name and not just the name of the currently executing script, like this:
script_name = basename(__FILE__);
I personally prefer the second method over the first one, as it gives me more freedom and a better way to create a modular web application.
Note: Remember that there is a difference between using a backslash “\” and a forward (normal) slash “/” under Unix based systems. If you are testing your application on a windows machine and you use these interchangeably, it will work fine. But once you try to move your script to a Unix server it will cause some problems. Backslashes (“\”) are also used in PHP as in Unix, to indicate that the character that follows is a special character. Therefore, be careful not to use these in your path names.
I am not sure this is even possible with just using Movable Type tags but, how do I display random number with in certain range?
For example I have 10 images named 1~10 and every time I rebuild I want to display a random image from that range.
I use MT5.
Thank you in advance!
You can try my version of the MTCollate plugin with random filter. Original documentation is here: http://www.nonplus.net/software/mt/MTCollate.htm - difference is that it adds a sort="~" or "random" filter, but you'll probably be fine using the MTShuffleList block.
I think if you want to show one image and images count is ten, maybe you can show this cord.
<MTSetVarBlock name="imageID"><MTDate format="%S"></MTSetVarBlock>
<MTSetVarBlock name="imageID"><mt:GetVar name="imageID" op="div" value="6" sprintf="%d"></MTSetVarBlock>
<MTSetVar name="imageID" op="++">
src="/images/hoge<mt:GetVar name='imageID'>.jpg"
You can actually do this with PHP if you're so inclined. Movable Type supports the ability to publish to PHP and you can just put the content you want to be randomized inside of a PHP block. All you need to do is change the published archive file type to "php" in the blog settings. Here is the MTML sample:
<?php
$images = array();
<mt:Asset id="1">
$images[] = '<mt:AssetURL/>';
</mt:Asset>
<mt:Asset id="2">
$images[] = '<mt:AssetURL/>';
</mt:Asset>
<mt:Asset id="3">
$images[] = '<mt:AssetURL/>';
</mt:Asset>
$selected_asset = array_rand($images);
?>
Just repeat the Asset tag for each of the specific assets you want. That will generate ten operations to push each image asset's URL into the array. Alternatively, if you want to expose the last ten, you'd just to <mt:Assets lastn="10">
I'm trying to move my kml styles to an external document for use with OpenLayers. The styles work when they are included directly in the kml file.
At first I thought I could use straight kml for this with the styleUrl tag:
<styleUrl>http://localhost/map.kml#myIcon</styleUrl>
However, when I try to do that, the map.kml file never gets requested, and the markers don't show up. I've verified that the styleUrl url works.
I'm loading my kml using:
new OpenLayers.Layer.GML('Name', 'kml_path', {
format: OpenLayers.Format.KML,
formatOptions: {
extractStyles: true,
extractAttributes: true
},
projection: map.displayProjection
});
There are some tantalizing options called 'styles' and 'styleBaseUrl' in the OpenLayers.Format.KML API, but I cannot find any documentation about what they are for or how to use them. Does anyone have any experience with these?
One way could be, have a separate SLD external file with styles and apply it to your GML layer.
Take a look at the SLD OpenLayers code example at http://openlayers.org/dev/examples/sld.html and just replace the example layers with your layer and replace the styles in the sld-tasmania.xml file. This way, you would not need the option extractStyles in the formatOptions.
In formatOptions, try adding maxDepth:10 or some such integer. Here is the api definition.
maxDepth:{Integer} Maximum depth for recursive loading external KML URLs Defaults to 0: do no external fetching
With it defaulting to 0, I would suspect that it downloads 0 external kml files.
I really don't have any experience on KML, so I'm sorry if this is totally off. I just read the code for KML layers, especially the style portions. From your styleUrl tag it looks as the styleBaseUrl should be http://localhost/map.kml, based on the code in KML.js:
parseStyleMaps():
this.styles[(options.styleBaseUrl || "") + "#" + id] =
this.styles[(options.styleBaseUrl || "") + styleUrl];
parseStyles():
var styleName = (options.styleBaseUrl || "") + "#" + style.id;
The styles parameter seems to be initialized and rewritten each time the code reads the data, so that won't do any good I think.