Bundling javascript with htaccess and php - php

I am currently trying to bundle my javascript so I can receive a higher score in page speed/yslow. But i am running into walls with this approach. I am currently using this TUTORIAL as guidance to bundle the js files. I am calling the js files but in the firefox tool is showing that the file bundle.js does not exists which is true but with the htaccess i am chaning the file from bundle.php to bundle.js. But I am not getting any results. Can someone help me pinpoint the issue or is there a better approach to bundle js files?
HERE is my EXAMPLE. When working properly with the js files it should show 4 input fields for file uploads.
This is how I am calling the js files
<script src='core/bundle.js?js=js/jquery-ui-1.8rc2.custom.min.js,js/globalFunctions.js,js/uploaderPreviewer.js,js/itemForm.js&m=4948599067'>
</script>
.htacces to change file type*
RewriteEngine on
RewriteRule ^bundle.js$ bundle.php [QSA,L]
core/bundle.php
include "JSMin.php";
$path = "../../";
$files = explode(",", $_GET['js']);
$missing = array();
$cache = '';
foreach ($files as $index => $file) {
if (strtolower(substr($file, -2)) != 'js') {
unset($files[$index]);
} else if (file_exists($path.$file)) {
$cache .= $file;
$cache .= filemtime($path.$file);
} else {
$missing[] = $file;
unset($files[$index]);
}
}
$cache = 'cache/'.md5($cache);
if (count($missing)) {
header("Content-type: text/javascript");
header("Pragma: no-cache");
header("Cache-Control: no-cache");
echo "alert('Could not load the following javascript source files:\\n\\n- ".implode("\\n- ", $missing)."\\n\\nJavascript not loaded / running!');";
exit;
}
if (count($files)) {
// create cached version if not present
if (!file_exists($cache)) {
$js = '';
foreach ($files as $file) {
$js .= JSMin::minify(file_get_contents($path.$file));
}
file_put_contents($cache, $js);
}
// calculate last-modified & etag send caching headers
$last_modified_time = filemtime($cache);
$etag = md5_file($cache);
header("Content-type: text/javascript");
header("Pragma: public");
header("Cache-Control: public");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: ".$etag);
if (#strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
readfile($cache);
}

Here's what I've been using successfully for many years (no .htaccess needed):
In html:
<script type = "text/javascript" src = "js/scripts.php?build=12345&load=script1,script2,script3,folder/script4"> </script> <!-- do not specify the .js extension -->
In php (file scripts.php):
<?php
error_reporting(E_ERROR);
// see http://web.archive.org/web/20071211140719/http://www.w3.org/2005/MWI/BPWG/techs/CachingWithPhp
// $lastModifiedDate must be a GMT Unix Timestamp
// You can use gmmktime(...) to get such a timestamp
// getlastmod() also provides this kind of timestamp for the last
// modification date of the PHP file itself
function cacheHeaders($lastModifiedDate) {
if ($lastModifiedDate) {
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModifiedDate) {
if (php_sapi_name()=='CGI') {
Header("Status: 304 Not Modified");
} else {
Header("HTTP/1.0 304 Not Modified");
}
exit;
} else {
$gmtDate = gmdate("D, d M Y H:i:s \G\M\T",$lastModifiedDate);
header('Last-Modified: '.$gmtDate);
}
}
}
// This function uses a static variable to track the most recent
// last modification time
function lastModificationTime($time=0) {
static $last_mod ;
if (!isset($last_mod) || $time > $last_mod) {
$last_mod = $time ;
}
return $last_mod ;
}
lastModificationTime(filemtime(__FILE__));
cacheHeaders(lastModificationTime());
header("Content-type: text/javascript; charset: UTF-8");
ob_start ("ob_gzhandler");
foreach (explode(",", $_GET['load']) as $value) {
if (is_file("$value.js")) {
$real_path = mb_strtolower(realpath("$value.js"));
if (strpos($real_path, mb_strtolower(dirname(__FILE__))) !== false || strpos($real_path, mb_strtolower(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR)) !== false) {
lastModificationTime(filemtime("$value.js"));
include("$value.js");echo "\n";
}
}
}
?>
This compresses, merges and caches the js files

Related

browser wont cache image loaded through php proxy

currently using a simple php image proxy to load external images to ensure they don't mess with SSL. The problem is, on my live site they only seem to get stored in the memory cache and not the disk cache, so as soon as you close the tab/browser they get downloaded again.
Here's the code:
session_cache_limiter('public');
if (isset($_GET['url']))
{
header('Cache-control: max-age='.(60*60*24*365));
header('Expires: '.gmdate(DATE_RFC1123,time()+60*60*24*365));
header('Last-Modified: '.gmdate(DATE_RFC1123,filemtime($_GET['url'])));
define("APP_ROOT", dirname(dirname(__FILE__)));
require APP_ROOT . "/includes/bootstrap.php";
$url_check = parse_url($_GET['url']);
if (isset($url_check['scheme']) && ($url_check['scheme'] == 'http' || $url_check['scheme'] == 'https'))
{
$image_raw = core::file_get_contents_curl($_GET['url']);
$new_image = imagecreatefromstring($image_raw);
if ($new_image !== false)
{
$image_info = getimagesizefromstring($image_raw);
$image_type = $image_info['mime'];
if (stripos($image_type, 'image/') !== false)
{
header('Content-Type: '.$image_type);
imagepng($new_image);
imagedestroy($new_image);
}
}
}
else
{
echo 'Not a valid image url!';
}
}

Json Working on Localhost but not on server

I installed a server (VPS) and made sure that JSON plugin is enabled.
Now, I'm using Laravel and one helper file returns the code list of files.
It's working on Localhost, but not working on HTTPS server.
Now, this echo json_encode($enteries) is working on localhost (MAMP) but not working on liver server.
I am using Laravel V5.2
I get responset type: text/html in response on server.
Whereas on localhost, it comes to be application/json
Thank you in advance.
<?php
namespace ImageBrowser;
use ImageBrowserEntry\ImageBrowserEntry;
use Thumbnail\Thumbnail;
class ImageBrowser {
// path to file upload directory
private $contentPath = '';
public function __construct()
{
$this->contentPath = public_path() .\Config::get('global.DIRECTORY_SEPERATOR'). \Config::get('global.image_browser_path');
}
private function canAccess($path) {
return \ImageHelper::startsWith(realpath($path), realpath($this->contentPath));
}
private function ensureAccess($path) {
if (!$this->canAccess($path)) {
header('HTTP/1.0 403 Forbidden');
die();
}
}
private function normalize($path) {
if (!\ImageHelper::endsWith($path, '/')) {
$path .= '/';
}
return $path;
}
public function basePath() {
return $this->normalize($this->contentPath);
//return $this->normalize(realpath(dirname(__FILE__) . $this->contentPath));
}
public function getList($path) {
$this->ensureAccess($path);
header('Content-Type: application/json');
$dir = array_map(function ($scan_entry) use ($path) {
if (\ImageHelper::startsWith($scan_entry, '.')) {
return;
}
$entry = new ImageBrowserEntry();
$fullpath = realpath($path . $scan_entry);
$entry->name = $scan_entry;
$entry->type = is_dir($fullpath) ? 'd' : 'f';
$entry->size = filesize($fullpath);
if ($entry->type == 'f' && preg_match('/\\.(png|gif|jpg|jpeg)$/i', $scan_entry) == 0) {
return;
}
return $entry;
}, scandir($path));
$entries = array();
foreach ($dir as $entry) {
if ($entry) {
$entries[] = $entry;
}
}
echo json_encode($entries);
}
public function setImageHeaders($path, $type=null) {
if (!$type) {
$type = \ImageHelper::getImageType($path);
}
header("Content-type: image/" . $type);
header("Expires: Mon, 1 Jan 2099 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// get the size for content length
$size = filesize($path);
header("Content-Length: $size bytes");
if (ob_get_contents()) ob_end_clean();
//ob_clean();
flush();
}
public function getThumbnail($path) {
$this->ensureAccess($path);
$image = new Thumbnail($path);
$this->setImageHeaders($path, $image->getType());
$image->downscale();
$image->render();
}
public function getImage($path) {
$this->ensureAccess($path);
$this->setImageHeaders($path);
readfile($path);
}
public function destroy($path, $entry) {
$target = $this->normalize($path) . $entry;
$this->ensureAccess($target);
if (is_dir($target)) {
\ImageHelper::rmdir_r($target);
} else {
unlink($target);
}
}
public function create($path, $entry) {
$this->ensureAccess($path);
mkdir($path . $entry);
}
public function saveFile($file, $path) {
$path = $this->normalize($path);
$this->ensureAccess($path);
$name = basename($file['name']);
$target = $path . $name;
move_uploaded_file($file['tmp_name'], $target);
header('Content-Type: application/json');
$result = new ImageBrowserEntry();
$result->size = filesize($target);
$result->name = $name;
echo json_encode($result);
}
}
Found Answer by myself.
The Laravel env. is strange and all I changed was remove native PHP object methods and then it worked.

ob_start including file echoing 1

class function (located php/php_includes/easyCMSv2.php)
public function get_file($file){
ob_start();
include('php/'.$file);
$file = ob_end_clean();
return $file;
}
stylesheet_config.php (located php/css)
<?php
$blue = "#4C66A4";
$red = "#A44C4C";
?>
stylesheet.php (located php/css)
<?php
ob_start ("ob_gzhandler");
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$if_modified_since = preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']);
} else {
$if_modified_since = '';
}
$mtime = filemtime($_SERVER['SCRIPT_FILENAME']);
$gmdate_mod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
if ($if_modified_since == $gmdate_mod) {
header("HTTP/1.0 304 Not Modified");
exit;
}
header("Last-Modified: $gmdate_mod");
header('Content-type: text/css');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (60*60*24*45)) . ' GMT');
include_once('../php_includes/easyCMSv2.php');
require('stylesheet_config.php');
$cms = new Template($connect);
if(isset($_GET['v'])){
$cms->get_file('css/'.$_GET["v"].'.php');
}
?>
$_GET['v'] = 1-23-1
1-23-1.php (located php/css)
div{
color:<?=$blue?>;
background:<?=$red?>;
}
Though everytime I go to the url (either by a link tag or direct url) it returns 1 can anyone explain to me why it keeps returning 1?
ob_end_clean() returns true or false (in your case, true, or 1). It does not return the actual buffer output.
You need to use another method to retrieve the buffer output: ob_get_contents()
public function get_file($file){
ob_start();
include('php/'.$file);
$file = ob_get_contents(); /* *** */
ob_end_clean();
return $file;
}

Flash doesnt recognize the file type to get AS3 PHP

Im programming in as3 flash and php a button where you can download a file .zip file.
This gets the path from a php (proxy), but it cant recognize the file type and also fails to run the COMPLETE event. The idea of ​​this is to hide where the zip file is located.
I dont understand where the problem is.
The as3 code:
package {
imports...
public class Main extends MovieClip{
var download_button:MovieClip;
var req:URLRequest;
var file:FileReference;
var proxy:String = "http://www.domain.com/audio/proxy.php?url=";
var filename:String = "file.zip";
var status:TextField = new TextField();
public function Main() {
download_btn.addEventListener(MouseEvent.CLICK, promptDownload);
status.text = "Bienvenido";
addChild(status);
}
private function promptDownload(e:MouseEvent):void {
req = new URLRequest(proxy + filename);
file = new FileReference();
file.addEventListener(Event.COMPLETE, completeHandler);
file.addEventListener(Event.CANCEL, cancelHandler);
file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
file.download(req, "file.zip");
}
private function cancelHandler(event:Event):void {
trace("User canceled the download");
status.text = "Cancelado";
}
private function completeHandler(event:Event):void {
trace("Download complete");
status.text = "Completado";
}
private function ioErrorHandler(event:IOErrorEvent):void {
trace("ioError occurred");
status.text = "Error";
}
}
}
and the php code:
$filename = "http://www.domain.com/audio/files" . $_GET['url'];
$archivo = "file.zip";
$len = filesize($filename);
$outname = $archivo;
header("Content-type: application/zip");
// Optional but the error is the same
//header("Expires: -1");
//header("Last-Modified: " . gmdate('D, d M Y H:i:s') . " GMT");
//header("Content-Transfer-Encoding: binary");
//header("Cache-Control: no-store, no-cache, must-revalidate");
//header("Cache-Control: post-check=0, pre-check=0");
//header("Pragma: no-cache");
//header("Content-Length:".$len);
//header("Content-Disposition: attachment; filename=".$outname);
readfile($filename);
thank you very much
The actionscript work perfectly on my localhost, I download the zip file. You should check the PHP, you don't need to use http url to read file on the same server.
$filename = "http://www.domain.com/audio/files" . $_GET['url'];
This line is really a security hole, a hacker can get all your file, you need to escape this variable and check if the filename is legit.

How to use etags in a PHP file?

How do you implemented etags inside a PHP file? What do I upload to the server and what do I insert into my PHP file?
Create / edit your .htaccess file and add the following:
FileETag MTime Size
Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:
<?php
$file = 'myfile.php';
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
if (#strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
?>
Version that corresponding to https://datatracker.ietf.org/doc/html/rfc7232#section-2.3 (an etag value must be quoted):
<?php
$file = __DIR__ . '/myfile.js';
$etag = '"' . filemtime($file) . '"';
// Use it if the file is changed more often than one time per second:
// $etag = '"' . md5_file($file) . '"';
header('Etag: ' . $etag);
$ifNoneMatch = array_map('trim', explode(',', trim($_SERVER['HTTP_IF_NONE_MATCH'])));
if (in_array($etag, $ifNoneMatch, true) || count($ifNoneMatch) == 1 && in_array('*', $ifNoneMatch, true)) {
header('HTTP/1.1 304 Not Modified');
exit;
}
print file_get_contents($file);

Categories