ob_start including file echoing 1 - php

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;
}

Related

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.

resume and section support in php

sorry if this is not a new question but i'm really stuck in this problem. I'm using script below for downloading a large file like a movie, I can not let user to access direct link of the file, also I need to let user download the file in a resume and section support manner. Using this code I just have resume support, not section. I'm using Yii framework.
Please Help me on this by any solution and suggestion.
public static function downloadFile($fileLocation, $saveName = null, $maxSpeed = 100, $doStream = false){
$start = 0;
$end = -1;
$section = false;
$extension = CFileHelper::getExtension($fileLocation);
$fileName = is_null($saveName) ? basename($fileLocation) : $saveName . '.' . $extension;
/* #var $contentType string mime type for the file, if is null, it will be octet-stream */
$contentType = CFileHelper::getMimeType($fileLocation);
$contentType = is_null($contentType) ? 'application/octet-stream' : $contentType;
if(isset($_SERVER['HTTP_RANGE']))
{
$range2 = substr($_SERVER['HTTP_RANGE'], strlen('bytes='));
$range = explode('-', $range2);
if($range[0] > 0)
$start = intval($range[0]);
if($range[1] > 0)
$end = intval($range[1]);
$section = true;
}
ob_end_clean();
$old_status = ignore_user_abort(true);
set_time_limit(0);
$size = filesize($fileLocation);
if($start > ($size -1)) $start = 0;
$fp = fopen($fileLocation, 'rb');
if($start) fseek($fp, $start);
if($end < $start) $end = $size -1;
header('Content-Type: '.$contentType);
$contentDisposition = 'attachment';
if($doStream == true){
$array_listen = array('mp3','m3u','m4a','mid','ogg','ra','ram','wm',
'wav','wma','aac','3gp','avi','mov','mp4','mpeg','mpg','swf','wmv','divx','asf');
if(in_array($extension,$array_listen)){
$contentDisposition = 'inline';
}
}
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
$fileName= preg_replace('/\./', '%2e', $fileName, substr_count($fileName, '.') - 1);
header("Content-Disposition: $contentDisposition; filename=\"$fileName\"");
} else {
header("Content-Disposition: $contentDisposition; filename=\"$fileName\"");
}
header('Content-Disposition: ' . $contentDisposition . '; filename="' . $fileName . '"');
header('Last-Modified: ' . date('D, d M Y H:i:s \G\M\T', filemtime($fileLocation)));
if($section)
{
header("HTTP/1.0 206 Partial Content");
header("Status: 206 Partial Content");
header('Accept-Ranges: bytes');
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: " . ($end - $start + 1));
}else
header('Content-Length: '.$size);
$size = $end - $start + 1;
while(!(connection_aborted() || connection_status() == 1) && !feof($fp))
{
print(fread($fp,1024*$maxSpeed));
flush();
ob_flush();
sleep(1);
}
fclose($fp);
ignore_user_abort($old_status);
set_time_limit(ini_get('max_execution_time'));
}
If you are using apache and able to install mods to it, you can use mod_xsendfile module. It supports partial downloads, cashing and other cool things.
Simple demo: Send Files Faster & Better with PHP & X-Sendfile

Elgg Profile Image

I am developing a plugin in elgg which has a some images for profile icon.
in that plugin there are various sized file for a single image for eg
train.jpg = Height : 100px || Width : 100px
train_25px.jpg = Height : 25px || Width : 25px
Like above i have cropped images. there are about 25 images + 25 cropped images
i want to define one image per user and call the image at any time without recreating the same image in another location
for eg :
Original Location : sitepath/mod/plugin_name/graphic/profile_icon1/master.jpg
User Image Location : site_temp_path/year/month/user_guid/master.jpg
My php function is
global $CONFIG;
function identicon_init() {
extend_view('profile/editicon', 'identicon/editicon');
register_action('identicon/preference', false, $CONFIG->pluginspath . 'identicon/actions/preference.php');
register_plugin_hook('entity:icon:url', 'user', 'identicon_usericon_hook', 900);
}
function identicon_usericon_hook($hook, $entity_type, $returnvalue, $params) {
if (($hook == 'entity:icon:url') && ($params['entity'] instanceof ElggUser)) {
$ent = $params['entity'];
if ($ent->preferIdenticon || !$returnvalue) {
return identicon_url($ent, $params['size']);
}
} else {
return $returnvalue;
}
}
function identicon_url($ent, $size) {
global $CONFIG;
return $CONFIG->wwwroot . 'mod/fp_auto_profile_image/img.php?entity=' . $ent->getGUID() . '&size=' . $size;
}
register_elgg_event_handler('init','system','identicon_init');
use elgg_get_data_path() instead of $CONFIG->wwwroot
then create icon.php and return path to icon.php in identicon_usericon_hook along with required with and size
then in icon.php have this code
$news_guid = get_input('guid');
$contents = readfile(filepath);
$size = strtolower(get_input('size'));
if (!in_array($size, array('large', 'medium', 'small', 'tiny', 'master', 'topbar')))
$size = "large";
header("Content-type: image/jpeg");
header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+10 days")), true);
header("Pragma: public");
header("Cache-Control: public");
header("Content-Length: " . strlen($contents));
header("ETag: \"$etag\"");
echo $contents;

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

Bundling javascript with htaccess and 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

Categories