Json Working on Localhost but not on server - php

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.

Related

PHPExcel_IOFactory::createWriter and Save taking more than a minute to write a file

Below is my code. I'm getting the data as a string with 2 parts. First part is all about headers for an excel sheet. And the 2nd part is about the actual data. They are separated by a special delimiter.
Again the second part (actual data) is separated with '\n' for each row with each column again divided with delimiter '|'.
Now if i click on download, the excel is being generated after 1 min 20 secs.. Please help me finding the culprit as I'm new to php.
Im using PHPExcel_IOFactory plugin here..
if (!empty($json_decodeArr))
$dataExists = 1;
else
$dataExists = 0;
$service_name = $params['service_name'];
$company_name = $params["company_name"];
$language = $params["language"];
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array(' memoryCacheSize ' => '32MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
if (isset($GLOBALS[$service_name]["TEMPLATE_NAME"]) && $GLOBALS[$service_name]["TEMPLATE_NAME"] != '') {
$template = $GLOBALS[$service_name]["TEMPLATE_NAME"];
$ext = $GLOBALS[$service_name]["TEMPLATE_NAME_EXT"];
$path = $GLOBALS[$service_name]["TEMPLATE_PATH"];
$filepath = $path . $template.$language . "." . $ext;
try {
//load Excel template file
$objPHPExcel = PHPExcel_IOFactory::load($filepath);
} catch(Exception $e) {
die('Error loading file ' . $e -> getMessage());
}
} else {
$template = $GLOBALS["TEMPLATE_BLANK"];
$ext = $GLOBALS[$service_name]["TEMPLATE_BLANK_EXT"];
$path = $GLOBALS["TEMPLATE_BLANKPATH"];
$filepath = $path . $template . "." . $ext;
try {
//load Excel template file
$objPHPExcel = PHPExcel_IOFactory::load($filepath);
} catch(Exception $e) {
die('Error loading file ' . $e -> getMessage());
}
}
$temp_array = array();
//Named Configuration XLS Generation
//Writing Values into the excel sheet
$counter = 0;
$objPHPExcel -> setActiveSheetIndex(1);
$currentSheet = $objPHPExcel -> getActiveSheet();
foreach ($json_decodeArr as $key => $value) {
if ($key == 0) {
$headerNamesArr = explode("|",$GLOBALS[$service_name][$template][0]["HeaderNames"]);
$headerExcelPositionArr = explode("|",$GLOBALS[$service_name][$template][0]["HeaderExcelPosition"]);
$headerDataArr = explode("|",$value);
foreach ($headerNamesArr as $headerName) {
$headerData = getHeaderValue($headerName,$headerDataArr);
$currentSheet -> setCellValue(getHeaderValue($headerName,$headerExcelPositionArr), $headerData);
}
//file_put_contents("testResponse.txt", getHeaderValue('daysleft:',$headerDataArr));
} else {
//$activeWS = "B";
$index = $GLOBALS[$service_name][$template][0]["ROW_START"];
//file_put_contents("testResponse.txt", $GLOBALS[$service_name][$template][0]["COL_START"]);
$rows = explode("\n", $value);
foreach ($rows as $values1) {
$activeWS = $GLOBALS[$service_name][$template][0]["COL_START"];
$rowData = explode("|", $values1);
//file_put_contents("testResponse.txt",$rowData);
foreach ($rowData as $vals) {
$WSName = $activeWS . $index;
$currentSheet -> setCellValue($WSName, $vals);
$activeWS++;
}
$index++;
}
$counter++;
}
}
//$objPHPExcel->removeSheetByIndex($rowStart);
$objPHPExcel -> setActiveSheetIndex(0);
// Redirect output to a client.s web browser (Excel5)
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=" . $filename . ".xlsx");
header("Cache-Control: max-age=0");
// If you"re serving to IE 9, then the following may be needed
header("Cache-Control: max-age=1");
// If you"re serving to IE over SSL, then the following may be needed
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// always modified
header("Cache-Control: cache, must-revalidate");
// HTTP/1.1
header("Pragma: public");
// HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
unset($objPHPExcel);
ob_start();
$objWriter -> save("php://output");
ob_flush();
exit ;

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

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

PHP change variable into jpeg file

I have the following code to get the album cover of an mp3 using getid3, the problem is though, how do I copy this image and put it into a specified directory?
<?php
require_once('getid3/getid3.php');
$file = "path/to/mp3/file.mp3";
$getID3 = new getID3;
$getID3->option_tag_id3v2 = true;
$getID3->option_tags_images = true;
$getID3->analyze($file);
if (isset($getID3->info['id3v2']['APIC'][0]['data'])) {
$cover = $getID3->info['id3v2']['APIC'][0]['data'];
} elseif (isset($getID3->info['id3v2']['PIC'][0]['data'])) {
$cover = $getID3->info['id3v2']['PIC'][0]['data'];
} else {
$cover = "no_cover";
}
if (isset($getID3->info['id3v2']['APIC'][0]['image_mime'])) {
$mimetype = $getID3->info['id3v2']['APIC'][0]['image_mime'];
} else {
$mimetype = 'image/jpeg';
}
if (!is_null($cover)) {
// Send file
header("Content-Type: " . $mimetype);
if (isset($getID3->info['id3v2']['APIC'][0]['image_bytes'])) {
header("Content-Length: " . $getID3->info['id3v2']['APIC'][0]['image_bytes']);
}
echo ($cover);
?>
Is this possible, if yes how? Thanks for any help :)
have you tried:
file_put_contents('<filename>', $getID3->info['id3v2']['APIC'][0]['image_bytes']);

How to zip a folder and download it using php?

I have folder named "data". This "data" folder contains a file "filecontent.txt" and another folder named "Files". The "Files" folder contains a "info.txt" file.
So it is a folder inside folder structure.
I have to zip this folder "data"(using php) along with the file and folder inside it, and download the zipped file.
I have tried the examples available at http://www.php.net/manual/en/zip.examples.php
These examples did not work. My PHP version is 5.2.10
Please help.
I have written this code.
<?php
$zip = new ZipArchive;
if ($zip->open('check/test2.zip',ZIPARCHIVE::CREATE) === TRUE) {
if($zip->addEmptyDir('newDirectory')) {
echo 'Created a new directory';
} else {
echo 'Could not create directory';
}
$zipfilename="test2.zip";
$zipname="check/test2.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=check/test1.zip'); //header('Content-Length: ' . filesize( $zipfilename));
readfile($zipname); //$zip->close(); } else { echo failed';
}
?>
file downloaded but could not unzip
You need to recursively add files in the directory. Something like this (untested):
function createZipFromDir($dir, $zip_file) {
$zip = new ZipArchive;
if (true !== $zip->open($zip_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
return false;
}
zipDir($dir, $zip);
return $zip;
}
function zipDir($dir, $zip, $relative_path = DIRECTORY_SEPARATOR) {
$dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (file === '.' || $file === '..') {
continue;
}
if (is_file($dir . $file)) {
$zip->addFile($dir . $file, $file);
} elseif (is_dir($dir . $file)) {
zipDir($dir . $file, $zip, $relative_path . $file);
}
}
}
closedir($handle);
}
Then call $zip = createZipFromDir('/tmp/dir', 'files.zip');
For even more win I'd recommend reading up on the SPL DirectoryIterator here
========= The only solution for me ! ! !==========
Puts all subfolders and sub-files with their structure:
<?php
$the_folder = 'path/foldername';
$zip_file_name = 'archived_name.zip';
$download_file= true;
//$delete_file_after_download= true; doesnt work!!
class FlxZipArchive extends ZipArchive {
/** Add a Dir with Files and Subdirs to the archive;;;;; #param string $location Real Location;;;; #param string $name Name in Archive;;; #author Nicolas Heimann;;;; #access private **/
public function addDir($location, $name) {
$this->addEmptyDir($name);
$this->addDirDo($location, $name);
} // EO addDir;
/** Add Files & Dirs to archive;;;; #param string $location Real Location; #param string $name Name in Archive;;;;;; #author Nicolas Heimann
* #access private **/
private function addDirDo($location, $name) {
$name .= '/';
$location .= '/';
// Read all Files in Dir
$dir = opendir ($location);
while ($file = readdir($dir))
{
if ($file == '.' || $file == '..') continue;
// Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
$do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
$this->$do($location . $file, $name . $file);
}
} // EO addDirDo();
}
$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if($res === TRUE)
{
$za->addDir($the_folder, basename($the_folder));
$za->close();
}
else { echo 'Could not create a zip archive';}
if ($download_file)
{
ob_get_clean();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($zip_file_name) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zip_file_name));
readfile($zip_file_name);
//deletes file when its done...
//if ($delete_file_after_download)
//{ unlink($zip_file_name); }
}
?>
I had to do the same thing a few days ago and here is what I did.
1) Retrieve File/Folder structure and fill an array of items. Each item is either a file or a folder, if it's a folder, retrieve its content as items the same way.
2) Parse that array and generate the zip file.
Put my code below, you will of course have to adapt it depending on how your application was made.
// Get files
$items['items'] = $this->getFilesStructureinFolder($folderId);
$archiveName = $baseDir . 'temp_' . time(). '.zip';
if (!extension_loaded('zip')) {
dl('zip.so');
}
//all files added now
$zip = new ZipArchive();
$zip->open($archiveName, ZipArchive::OVERWRITE);
$this->fillZipRecursive($zip, $items);
$zip->close();
//outputs file
if (!file_exists($archiveName)) {
error_log('File doesn\'t exist.');
echo 'Folder is empty';
return;
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($archiveName) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($archiveName));
readfile($archiveName);
//deletes file when its done...
unlink($archiveName);
Methods used to fill & parse:
/**
*
* Gets all the files recursively within a folder and keeps the structure.
*
* #param int $folderId The id of the folder from which we start the search
* #return array $tree The data files/folders data structure within the given folder id
*/
public function getFilesStructureinFolder($folderId) {
$result = array();
$query = $this->db->query('SELECT * FROM xx WHERE deleted = 0 AND status = 1 AND parent_folder_id = ? ORDER BY name ASC', $folderId);
$folders = $query->result();
foreach($folders as $folder) {
$folderItem = array();
$folderItem['type'] = 'folder';
$folderItem['obj'] = $folder;
$folderItem['items'] = $this->getFilesStructureinFolder($folder->id);
$result[] = $folderItem;
}
$query = $this->db->query('SELECT * FROM xx WHERE deleted = 0 AND xx = ? AND status = 1 ORDER BY name ASC', $folderId);
$files = $query->result();
foreach ($files as $file) {
$fileItem = array();
$fileItem['type'] = 'file';
$fileItem['obj'] = $file;
$result[] = $fileItem;
}
return $result;
}
/**
* Fills zip file recursively
*
* #param ZipArchive $zip The zip archive we are filling
* #param Array $items The array representing the file/folder structure
* #param String $zipPath Local path within the zip
*
*/
public function fillZipRecursive($zip, $items, $zipPath = '') {
$baseDir = $this->CI->config->item('xxx');
foreach ($items['items'] as $item) {
//Item is a file
if ($item['type'] == 'file') {
$file = $item['obj'];
$fileName = $baseDir . '/' . $file->fs_folder_id . '/' . $file->file_name;
if (trim($file->file_name) == '' || !file_exists($fileName))
continue;
$zip->addFile($fileName, $zipPath.''.$file->file_name);
}
//Item is a folder
else if ($item['type'] == 'folder') {
$folder = $item['obj'];
$zip->addEmptyDir($zipPath.''.$folder->name);
//Folder probably has items in it!
if (!empty($item['items']))
$this->fillZipRecursive($zip, $item, $zipPath.'/'.$folder->name.'/');
}
}
}
See the linked duplicates. Another often overlooked and particular lazy option would be:
exec("zip -r data.zip data/");
header("Content-Type: application/zip");
readfile("data.zip"); // must be a writeable location though
Use the TbsZip class to create a new zip Archive. TbsZip is simple, it uses no temporary files, no zip EXE, it has no dependency, and has a Download feature that flushes the archive as a download file.
You just have to loop under the folder tree and add all files in the archive, and then flush it.
Code example:
$zip = new clsTbsZip(); // instantiate the class
$zip->CreateNew(); // create a virtual new zip archive
foreach (...) { // your loop to scann the folder tree
...
// add the file in the archive
$zip->FileAdd($FileInnerName, $LocalFilePath, TBSZIP_FILE);
}
// flush the result as an HTTP download
$zip->Flush(TBSZIP_DOWNLOAD, 'my_archive.zip');
Files added in the archive will be compressed sequentially during the Flush() method. So your archive can contain numerous sub-files, this won't increase the PHP memory.

Categories