How to remove __MACOSX while using ZipArchive - php

After hours of trying to figure out why php "ZipArchive" does not work as expected, due to Mac OS adding a "__MACOSX" folder in the zip compression process.
How would I go about deleting "__MACOSX" folder in a zip archive during the upload process in a form?
Below is what I'm working with:
<?php
public function uploadZip($file)
{
$advert_index;
$zip = new \ZipArchive;
if (true === $zip->open($file['tmp_name'])) {
$source = trim($zip->getNameIndex(0), '/');
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
// Determine output filename (removing the `$source` prefix).
$substring_name = substr($name, strlen($source)+1);
$file = $this->option['uploads_path'] . $this->option['advert_id'] . '/' . $substring_name;
// Store the adverts `index.html` file URL to be returned.
if ('html' === pathinfo($name, PATHINFO_EXTENSION)) {
$advert_index = basename($name);
}
// Create the directories if necessary.
$dir = dirname($file);
if (! is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Read from Zip and write to disk.
$fpr = $zip->getStream($name);
$fpw = fopen($file, 'w');
while ($data = fread($fpr, 1024)) {
fwrite($fpw, $data);
}
fclose($fpr);
fclose($fpw);
}
$zip->close();
return array(
'status' => true,
'message' => array(
'index' => $advert_index,
'type' => 'text/html', // #HACK: Set MIME type manually. #TODO: Read MIME type from file.
),
);
}
return array(
'status' => false,
'message' => 'Upload failed',
);
}
Any help would be much appreciated :)
Note: I Managed to find the file just can't get it to be removed.
// Check to see the __MACOSX
if($zip->getNameIndex($i) === "__MACOSX/") {
error_log($zip->getNameIndex($i) . ' - Error here continue');
$zip->deleteName("__MACOSX/");
continue; // Move on to the next iteration
// $zip->deleteIndex($i);
} else {
$name = $zip->getNameIndex($i);
}

It was actually very simple, instead to trying to delete the folder within the zip-archive just had to skip all indexes aka filename that begin with a certain string while looping through the files.
if(substr($zip->getNameIndex($i), 0, 9) === "__MACOSX/") {
continue;
} else {
$name = $zip->getNameIndex($i);
}

Related

Read and write XLSM file in PHP

I want to read and write XLSM type file using PHP. I tried using PHPSpreadsheet for this but it doesn't support XLSM extension.
One possible solution could be to use EasyXLS (https://www.easyxls.com/manual/basics/import-from-xlsx-file-format.html)
// Create an instance of the class that imports XLSM files
$workbook = new COM("EasyXLS.ExcelDocument");
// Import XLSM file
$workbook->easy_LoadXLSXFile("C:\\Samples\\Excel to import.xlsm");
// Get the table of the second worksheet
$xlsSecondTable = $workbook->easy_getSheet("Second tab")->easy_getExcelTable();
// Add more data to the second sheet
$xlsSecondTable->easy_getCell_2("A1")->setValue("Data added by Tutorial37");
for ($column=0; $column<5; $column++)
{
$xlsSecondTable->easy_getCell(1, $column)->setValue("Data " . ($column + 1));
}
// Generate the XLSM file
$workbook->easy_WriteXLSXFile("C:\Samples\Excel with macro.xlsm");
But I was unable to find any Library for this.
Does anyone have any possible solution for this or some other way for this?
function excel($excelfile, $sheet = false){//from stores.blade.php
$tempfile = resource_path("uploads/excel.xlsm");//it just needs a place to store the XML file temporarily, this function only works in Laravel, replace with a filename
if($sheet){//load XML file
//$XML = file_get_contents($tempfile);
$XML = simplexml_load_file($excelfile);
$XML = json_decode(json_encode((array)$XML), TRUE);
$excelfile = pathinfo($sheet)['basename'];
if($excelfile == "workbook.xml"){
$RET = [];
foreach($XML["sheets"]["sheet"] as $data){
$RET[ $data["#attributes"]["sheetId"] ] = $data["#attributes"]["name"];
}
return [
'Filename' => $excelfile,
'SheetName' => "sys_workbook",
'SheetData' => $RET,
];
} else if($excelfile == "sharedStrings.xml"){
foreach($XML["si"] as $index => $value){
if(isset($value["t"])){
$value = $value["t"];
} else {
foreach($value["r"] as $index2 => $value2){
if(is_array($value2["t"])){
$value2["t"] = $value2["t"][0];
}
$value["r"][$index2] = $value2["t"];
}
$value = implode("", $value["r"]);
}
if(is_array($value)){
$value = $value[0];
}
$XML["si"][$index] = $value;
}
return [
'Filename' => $excelfile,
'SheetName' => "sys_strings",
'SheetData' => $XML["si"],
];
} else if(isset($XML["sheetPr"])){
return [
'Filename' => $excelfile,
'SheetName' => $XML["sheetPr"]["#attributes"]["codeName"],
'SheetData' => $XML["sheetData"]["row"],
];
}
return false;
} else {//load ZIPped XLSM file
$files = [];
$zip = new ZipArchive;
if ($zip->open($excelfile) === TRUE) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
if(startswith($filename, "xl/worksheets/") || $filename == "xl/workbook.xml" || $filename = "xl/sharedStrings.xml"){
copy("zip://" . $excelfile . "#" . $filename, $tempfile);
$XML = excel($tempfile, $filename);
if($XML !== false){
$files[ $XML["SheetName"] ] = $XML["SheetData"];
}
}
}
#unlink($tempfile);
$zip->close();
}
var_dump($files);
die();
}
}
I started work on this, I got this far. The problem is, I don't know how the shared strings (sys_strings) are referenced, and you'd need an equation evaluator to handle the functions. I HOPE, the sheets are in order, so Sheet1 becomes the first array value in sys_workbook.
For anyone still looking for a solution to this problem, the following XLSX reader can parse XLSM without a problem. Also saves the headache in interpreting Excel timestamps and data formats. Tried and tested.
I did not test the Writer though, yet!
https://github.com/shuchkin/simplexlsx

Uploading files in Fine-Uploader, fail to combine/merge chunks after successful upload

So I've been trying to get Chunked uploading working for a project I've been working on, I'm pretty new to things, in fact for all intensive purposes you can consider me a complete noob who is teaching himself, I'm using the Manual Upload Template from the website, and the Traditional Server Side Example files to gain an understanding of how the code works and trying to piece them together into a fully functional example for me to build from. I've been able to get most things working.
I've managed to get it uploading regular files into the files folder successfully if I upload a file without chunking it goes into my files directory, however if I use chunking it works to chunk up the file and upload it into a folder in my Chunks directory, but i cant seem to figure out how to get it to put the chunks back together and place it in the Files directory
My Firefox console gives me this response and stops after finishing uploading a file in chunks regardless of if I have my chunking success endpoint included in my code or not which makes me think it's got something to do with my chunking success endpoint not being set up correctly or something along those lines.
[Fine Uploader 5.11.8] All chunks have been uploaded for 0 - finalizing....fine-uploader.js:162:21
[Fine Uploader 5.11.8] Received response status 200 with body: {"success":true,"uuid":"79e7db33-9609-49cd-bcb1-2606bea6abd7","uploadName":null}fine-uploader.js:162:21
[Fine Uploader 5.11.8] Finalize successful for 0
I've spent about 2 days researching this with no avail, I don't seem to be getting errors, but as I said I'm pretty much a Noob when it comes to understanding this on my own. Any help is Greatly Appreciated.
Here Is my Uploader Code Body
<body>
<!-- Fine Uploader DOM Element
====================================================================== -->
<div id="fine-uploader-manual-trigger"></div>
<!-- Your code to create an instance of Fine Uploader and bind to the DOM/template
====================================================================== -->
<script>
var manualUploader = new qq.FineUploader({
debug: true,
element: document.getElementById('fine-uploader-manual-trigger'),
template: 'qq-template-manual-trigger',
request: {
endpoint: 'endpoint.php'
},
chunking: {
enabled: true
},
success: {
endpoint: "endpoint.php?done"
},
resume: {
enabled: true
},
thumbnails: {
placeholders: {
waitingPath: 'images/waiting-generic.png',
notAvailablePath: 'images/not_available-generic.png'
}
},
autoUpload: false,
showMessage: function(message) { //show message if any error occur during upload process
alert(message);
}
});
qq(document.getElementById("trigger-upload")).attach("click", function() {
manualUploader.uploadStoredFiles();
});
</script>
</body>
</html>
Here Is my Endpoint.php File
require_once "handler.php";
$uploader = new UploadHandler();
// Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
$uploader->allowedExtensions = array(); // all files types allowed by default
// Specify max file size in bytes.
$uploader->sizeLimit = null;
// Specify the input name set in the javascript.
$uploader->inputName = "qqfile"; // matches Fine Uploader's default inputName value by default
// If you want to use the chunking/resume feature, specify the folder to temporarily save parts.
$uploader->chunksFolder = "chunks";
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
header("Content-Type: text/plain");
// Assumes you have a chunking.success.endpoint set to point here with a query parameter of "done".
// For example: /myserver/handlers/endpoint.php?done
if (isset($_GET["done"])) {
$result = $uploader->combineChunks("files");
}
// Handles upload requests
else {
// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
$result = $uploader->handleUpload("files");
// To return a name used for uploaded file you can use the following line.
$result["uploadName"] = $uploader->getUploadName();
}
echo json_encode($result);
}
// for delete file requests
else if ($method == "DELETE") {
$result = $uploader->handleDelete("files");
echo json_encode($result);
}
else {
header("HTTP/1.0 405 Method Not Allowed");
}
?>
Here is my handler.php file, I'm just using the default traditional server side example.
class UploadHandler {
public $allowedExtensions = array();
public $sizeLimit = null;
public $inputName = 'qqfile';
public $chunksFolder = 'chunks';
public $chunksCleanupProbability = 0.001; // Once in 1000 requests on avg
public $chunksExpireIn = 604800; // One week
protected $uploadName;
/**
* Get the original filename
*/
public function getName(){
if (isset($_REQUEST['qqfilename']))
return $_REQUEST['qqfilename'];
if (isset($_FILES[$this->inputName]))
return $_FILES[$this->inputName]['name'];
}
public function getInitialFiles() {
$initialFiles = array();
for ($i = 0; $i < 5000; $i++) {
array_push($initialFiles, array("name" => "name" + $i, uuid => "uuid" + $i, thumbnailUrl => ""));
}
return $initialFiles;
}
/**
* Get the name of the uploaded file
*/
public function getUploadName(){
return $this->uploadName;
}
public function combineChunks($uploadDirectory, $name = null) {
$uuid = $_POST['qquuid'];
if ($name === null){
$name = $this->getName();
}
$targetFolder = $this->chunksFolder.DIRECTORY_SEPARATOR.$uuid;
$totalParts = isset($_REQUEST['qqtotalparts']) ? (int)$_REQUEST['qqtotalparts'] : 1;
$targetPath = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
$this->uploadName = $name;
if (!file_exists($targetPath)){
mkdir(dirname($targetPath), 0777, true);
}
$target = fopen($targetPath, 'wb');
for ($i=0; $i<$totalParts; $i++){
$chunk = fopen($targetFolder.DIRECTORY_SEPARATOR.$i, "rb");
stream_copy_to_stream($chunk, $target);
fclose($chunk);
}
// Success
fclose($target);
for ($i=0; $i<$totalParts; $i++){
unlink($targetFolder.DIRECTORY_SEPARATOR.$i);
}
rmdir($targetFolder);
if (!is_null($this->sizeLimit) && filesize($targetPath) > $this->sizeLimit) {
unlink($targetPath);
http_response_code(413);
return array("success" => false, "uuid" => $uuid, "preventRetry" => true);
}
return array("success" => true, "uuid" => $uuid);
}
/**
* Process the upload.
* #param string $uploadDirectory Target directory.
* #param string $name Overwrites the name of the file.
*/
public function handleUpload($uploadDirectory, $name = null){
if (is_writable($this->chunksFolder) &&
1 == mt_rand(1, 1/$this->chunksCleanupProbability)){
// Run garbage collection
$this->cleanupChunks();
}
// Check that the max upload size specified in class configuration does not
// exceed size allowed by server config
if ($this->toBytes(ini_get('post_max_size')) < $this->sizeLimit ||
$this->toBytes(ini_get('upload_max_filesize')) < $this->sizeLimit){
$neededRequestSize = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
return array('error'=>"Server error. Increase post_max_size and upload_max_filesize to ".$neededRequestSize);
}
if ($this->isInaccessible($uploadDirectory)){
return array('error' => "Server error. Uploads directory isn't writable");
}
$type = $_SERVER['CONTENT_TYPE'];
if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
$type = $_SERVER['HTTP_CONTENT_TYPE'];
}
if(!isset($type)) {
return array('error' => "No files were uploaded.");
} else if (strpos(strtolower($type), 'multipart/') !== 0){
return array('error' => "Server error. Not a multipart request. Please set forceMultipart to default value (true).");
}
// Get size and name
$file = $_FILES[$this->inputName];
$size = $file['size'];
if (isset($_REQUEST['qqtotalfilesize'])) {
$size = $_REQUEST['qqtotalfilesize'];
}
if ($name === null){
$name = $this->getName();
}
// check file error
if($file['error']) {
return array('error' => 'Upload Error #'.$file['error']);
}
// Validate name
if ($name === null || $name === ''){
return array('error' => 'File name empty.');
}
// Validate file size
if ($size == 0){
return array('error' => 'File is empty.');
}
if (!is_null($this->sizeLimit) && $size > $this->sizeLimit) {
return array('error' => 'File is too large.', 'preventRetry' => true);
}
// Validate file extension
$pathinfo = pathinfo($name);
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
if($this->allowedExtensions && !in_array(strtolower($ext), array_map("strtolower", $this->allowedExtensions))){
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
}
// Save a chunk
$totalParts = isset($_REQUEST['qqtotalparts']) ? (int)$_REQUEST['qqtotalparts'] : 1;
$uuid = $_REQUEST['qquuid'];
if ($totalParts > 1){
# chunked upload
$chunksFolder = $this->chunksFolder;
$partIndex = (int)$_REQUEST['qqpartindex'];
if (!is_writable($chunksFolder) && !is_executable($uploadDirectory)){
return array('error' => "Server error. Chunks directory isn't writable or executable.");
}
$targetFolder = $this->chunksFolder.DIRECTORY_SEPARATOR.$uuid;
if (!file_exists($targetFolder)){
mkdir($targetFolder, 0777, true);
}
$target = $targetFolder.'/'.$partIndex;
$success = move_uploaded_file($_FILES[$this->inputName]['tmp_name'], $target);
return array("success" => true, "uuid" => $uuid);
}
else {
# non-chunked upload
$target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
if ($target){
$this->uploadName = basename($target);
if (!is_dir(dirname($target))){
mkdir(dirname($target), 0777, true);
}
if (move_uploaded_file($file['tmp_name'], $target)){
return array('success'=> true, "uuid" => $uuid);
}
}
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
/**
* Process a delete.
* #param string $uploadDirectory Target directory.
* #params string $name Overwrites the name of the file.
*
*/
public function handleDelete($uploadDirectory, $name=null)
{
if ($this->isInaccessible($uploadDirectory)) {
return array('error' => "Server error. Uploads directory isn't writable" . ((!$this->isWindows()) ? " or executable." : "."));
}
$targetFolder = $uploadDirectory;
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$tokens = explode('/', $url);
$uuid = $tokens[sizeof($tokens)-1];
$target = join(DIRECTORY_SEPARATOR, array($targetFolder, $uuid));
if (is_dir($target)){
$this->removeDir($target);
return array("success" => true, "uuid" => $uuid);
} else {
return array("success" => false,
"error" => "File not found! Unable to delete.".$url,
"path" => $uuid
);
}
}
/**
* Returns a path to use with this upload. Check that the name does not exist,
* and appends a suffix otherwise.
* #param string $uploadDirectory Target directory
* #param string $filename The name of the file to use.
*/
protected function getUniqueTargetPath($uploadDirectory, $filename)
{
// Allow only one process at the time to get a unique file name, otherwise
// if multiple people would upload a file with the same name at the same time
// only the latest would be saved.
if (function_exists('sem_acquire')){
$lock = sem_get(ftok(__FILE__, 'u'));
sem_acquire($lock);
}
$pathinfo = pathinfo($filename);
$base = $pathinfo['filename'];
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
$ext = $ext == '' ? $ext : '.' . $ext;
$unique = $base;
$suffix = 0;
// Get unique file name for the file, by appending random suffix.
while (file_exists($uploadDirectory . DIRECTORY_SEPARATOR . $unique . $ext)){
$suffix += rand(1, 999);
$unique = $base.'-'.$suffix;
}
$result = $uploadDirectory . DIRECTORY_SEPARATOR . $unique . $ext;
// Create an empty target file
if (!touch($result)){
// Failed
$result = false;
}
if (function_exists('sem_acquire')){
sem_release($lock);
}
return $result;
}
/**
* Deletes all file parts in the chunks folder for files uploaded
* more than chunksExpireIn seconds ago
*/
protected function cleanupChunks(){
foreach (scandir($this->chunksFolder) as $item){
if ($item == "." || $item == "..")
continue;
$path = $this->chunksFolder.DIRECTORY_SEPARATOR.$item;
if (!is_dir($path))
continue;
if (time() - filemtime($path) > $this->chunksExpireIn){
$this->removeDir($path);
}
}
}
/**
* Removes a directory and all files contained inside
* #param string $dir
*/
protected function removeDir($dir){
foreach (scandir($dir) as $item){
if ($item == "." || $item == "..")
continue;
if (is_dir($item)){
$this->removeDir($item);
} else {
unlink(join(DIRECTORY_SEPARATOR, array($dir, $item)));
}
}
rmdir($dir);
}
/**
* Converts a given size with units to bytes.
* #param string $str
*/
protected function toBytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/**
* Determines whether a directory can be accessed.
*
* is_executable() is not reliable on Windows prior PHP 5.0.0
* (http://www.php.net/manual/en/function.is-executable.php)
* The following tests if the current OS is Windows and if so, merely
* checks if the folder is writable;
* otherwise, it checks additionally for executable status (like before).
*
* #param string $directory The target directory to test access
*/
protected function isInaccessible($directory) {
$isWin = $this->isWindows();
$folderInaccessible = ($isWin) ? !is_writable($directory) : ( !is_writable($directory) && !is_executable($directory) );
return $folderInaccessible;
}
/**
* Determines is the OS is Windows or not
*
* #return boolean
*/
protected function isWindows() {
$isWin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
return $isWin;
}
}
Thanks for the help in making sure my code was correct, Kicked myself in the face for this one! As I was thinking for the longest time a incorrectly setup Apache Environment has been the root of all my problems.
I did not have .htaccess setup which seemed to fix all of my problems.
Here are the steps I followed to resolve my problem.
First Step
Open apache.conf file as
sudo vim /etc/apache2/apache2.conf
Second Step
remove comment sign (#) if you find it before this line ( line number 187 approx.)
AccessFileName .htaccess
Third Step
Then find the line where there is
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
replace "None" with "All"
AllowOverride All
Step Four
Activate ModRewrite:
sudo a2enmod rewrite
sudo service apache2 restart
Everything should be Good from here.

Getting Videos from server directory to display in container on page using PHP

I have been trying to modify some PHP to allow my page to get to a directory and its sub-directories to get video files to display dynamically on my page, I'm using the scripts as follows
$imagetypes = array("video/ogv", "video/webm", "video/mp4");
$dir = "../uploadedVideo/*/";
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getVideo: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
This the top of my page before the HTML
This the div I'm looking to display static images or thumbnail, which when clicked on will be viewed in the page
<div class="vidSelect">
<?php
// fetch image details
$video = getImages("video");
// display on page
foreach($video as $vid) {
echo "<div class=\"vidContainer\" src=\"{$vid['file']}\"
{$vid['size'][3]}></div>\n";
} ?>
</div>
I haven't as yet sorted the video player, as I'm just looking to get the videos to show up first but have run out of ideas and skills to get any further.
It looks as if something is being seen as 3 div containers are being created although there are five sub directories within one main directory I want to access, Any help would be most gratefully received
So I see your Type is wrong from the comments. Also the Source is not correct.
function getImages($dir) {
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if (substr($dir, -1) != "/") $dir. = "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getVideo: Failed opening directory $dir for reading");
while (false !== ($entry = $d - > read())) {
// skip hidden files
if ($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file - bi $f`);
foreach($imagetypes as $valid_type) {
if (preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' = > "$dir$entry",
'size' = > getimagesize("$fulldir$entry"));
break;
}
}
}
$d - > close();
return $retval;
}
Then in your HTML:
< div class = "vidSelect" >
<? php
// fetch image details
$video = getImages("video");
// display on page
foreach($video as $vid) {
echo "<div class='vidContainer' src='{$vid['file']}' type='{$vid['size']['mime']}'></div>\n";
} ?>
< /div>

how to unzip txt.gz file and store into database using php

My zip file name is Product_Catalog.txt.gz. this zip file contain one txt file.
how can i extract and store into my database
i have already done in zip file unzip and store into my database. but i can't understand .gz format. so please advise
my zip file code is here
if (realpath($destinationname."/".$filename)){
if ($zip = zip_open(realpath($directory."/".$filename)))
{
while (($zip_entry = zip_read($zip))){
$zipfilename=zip_entry_name($zip_entry );
$zipfilename."<br>";
$tmpfname = tempnam("/tmp", "");
$handle = fopen($tmpfname, "w+");
while($data = zip_entry_read($zip_entry,50000000000)){
fwrite($handle,$data);
}// end while $data
fseek($handle,0);
if ($separatetables);
$table=strtok($zipfilename,"-");
$sql="CREATE TABLE IF NOT EXISTS `$table` LIKE `cjfeeds`";
mysql_query($sql);
how can i convert this code into txt.gz
gzip, which is generally used for single files, is not the same file format as ZIP. Although the same compression algorithm (DEFLATE) is used in both formats, the headers are entirely different, so PHP's Zip functions will not recognize your file.
Instead, you can use the compress.zlib:// wrapper to open gzip-compressed files. You can then use the normal stream functions to read the file.
$handle = fopen("compress.zlib://$filename", 'r');
However, there are some limitations; for example, opening a gzipped file in read-write mode is not possible, and seeking may be slow. If necessary, you can work around these by making a temporary uncompressed copy:
copy("compress.zlib://$filename", $tmpfname);
You don't extract.
if ($rrpath){
if ($zip = gzopen($rrpath, "rb"))
{
$filenamen = $_SESSION['files_list'][$i];
$zipfilename = str_replace('.gz', '', $_SESSION['files_list'][$i]);
$tmpfname = tempnam("/home/demoosiz/tmp", "");
$handle = fopen($tmpfname, "w+");
ini_set("max_execution_time",3000000000000);
while($data = gzread($zip, 4096)){
fwrite($handle,$data);
}// end while $data
fseek($handle,0);
if ($separatetables);
$table=strtok($zipfilename,"-");
// $sqly = "TRUNCATE TABLE `cjfeeds`";
//mysql_query($sqly);
// I'm not too sure if this is windows specific
$tmpfile=addslashes($tmpfname);
//if the script times out uncomment the next line
ini_set("max_execution_time",3000000000000);
$sql22 ="LOAD DATA LOCAL INFILE '$tmpfile' REPLACE INTO TABLE `cjfeeds` FIELDS TERMINATED BY '$fieldseparator' IGNORE 1 LINES;";
You can use this code. This code is very helpful for you.
You keep calling it a zip file. It's not a zip file (.zip). It's a gzip file (.gz). Different format.
You can use gzdecode() to decompress a gzip file.
You can interact with .gz files through the functions of the zlib module.
Responding to your comment:
You won't need to do the while($zip_entry = zip_read($zip)) since gz files don't hold multiple files within them. A .gz file is just a single file that has been compressed. Unfortunately, this also means that there is no equivalent to zip_entry_name either, since there is only one file.
If you're trying to read a tarball - an archive of files which have been concatenated together and gzipped to form a .tar.gz file - then Zlib isn't for you, since it's not designed to handle that. You'll want something like PharData instead:
$phar = new PharData($filename);
foreach ($phar as $phar_stream) {
$file_data = file_get_contents($phar_stream);
// process $file_data how you like
}
If these are just single-file gz files, then you can read the files with the gz versions of the usual filesystem functions.
You can use gzread to process chunks of the file the way you're currently doing with zip_entry_read, or you can read all lines into an array with gzfile. There is a readgzfile function which grabs the whole file, but unfortunately it seems like it just dumps the output directly to the client, rather than do a file. You could use output buffering to capture that output, but it seems like too much of a hassle considering your other options.
Try this....
if(isset($_FILES['zipfile']))
{
$filename = $_FILES['zipfile']['name'];
$source = $_FILES['zipfile']['tmp_name'];
$type = $_FILES['zipfile']['type'];
/*$name = explode('.zip', $filename); # $name[0] returns the name of the file. $name[1] returns the extension (zip)
; */ # Where the file will be saved. I.E. 'extracted/myFile-02151985/'
$target = PHYSICAL_PATH."upload/";
// Ensures that the correct file type was chosen.
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type)
{
if($mime_type == $type)
{
$okay = true;
break;
}
}
$okay = strtolower($name[1]) == 'zip' ? true : false;
if(!$okay)
{
$msg="Please choose a zip file, dummy!";
}
$saved_file_location = $target.$filename;
if(move_uploaded_file($source, $target . $filename))
{
global $target;
global $unique_folder;
$zip = new ZipArchive();
$x = $zip->open($saved_file_location);
if ($x === true)
{
$folder=$zip->extractTo($target);
for ( $i=0; $i < $zip->numFiles; $i++ )
{
echo $entry = $zip->getNameIndex($i);
$filename=explode('/',$entry);
print_r($filename);
if($filename[1] != '')
{
$filename_folder=$filename[0];
$filename = $filename[1]; //
$name = explode('.zip', $filename_folder); # $name[0] returns the name of the file. $name[1] returns the extension (zip)
//echo 'sfkdf'.$name[0];
$target = PHYSICAL_PATH."upload/";
$sql = "select `id` from `tracks` order by `id` desc";
$list = mysql_query($sql);
$list_num = mysql_num_rows($list);
if($list_num > 0)
{
$res = mysql_fetch_array($list);
$new_id=$res['id'];
} else {
$new_id=1;
}
$check_for_jpg = strpos($filename, '.mp3');
if ($check_for_jpg === false ){
echo 'Check file format.';
$source=$target . $name[0].'/'.$filename;
unlink($source);
} else {
$srch = array(' ','--','"','!','#','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','/','*','+','~','`','=');
$rep = array('_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_');
$name_song[$i]= str_replace($srch,$rep,$filename);
$title_name=explode('.',$filename);
$new_id=$new_id+1;
$new_filename=$new_id.'-'.$name_song[$i];
mysql_query("insert into `tracks` set track='".addslashes(stripslashes($new_filename))."',title='".addslashes(stripslashes($title_name[0]))."',tape_id='".$id_last."',addDate=NOW(),status=1 ");
$source=$target . $name[0].'/'.$filename; $target_move=$target.$new_filename;
if(rename($source,$target_move)) { unlink($source); } else { echo 'not';}
echo 'folder zip';
echo '<li>' . $new_filename . '</li>';
}
rmdir($target . $name[0]);
}
else { echo $target = PHYSICAL_PATH."upload/";
$sql = "select `id` from `test_table` order by `id` desc";
$list = mysql_query($sql);
$list_num = mysql_num_rows($list);
if($list_num > 0) {
//and, instead of using "while":
$res = mysql_fetch_array($list); // will return the highest "id" number
echo $new_id=$res['id'];
} else {
$new_id=1;
}
$check_for_jpg = strpos($entry, '.mp3');
if ($check_for_jpg === false ){
echo 'Check file format.';
$source=$target .$entry;
unlink($source);
} else {
$srch = array(' ','--','"','!','#','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','/','*','+','~','`','=');
$rep = array('_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_','_');
$name_song[$i]= str_replace($srch,$rep,$entry);
$title_name=explode('.',$entry);
$new_id=$new_id+1;
$new_filename=$new_id.'-'.$name_song[$i];
mysql_query("insert into `tracks` set track='".addslashes(stripslashes($new_filename))."',title='".addslashes(stripslashes($title_name[0]))."',tape_id='".$id_last."',status=1 ");
$source=$target .$entry; $target_move=$target.$new_filename;
if(rename($source,$target_move)) { unlink($source); } else { echo 'not';}
echo 'only zip';
echo '<li>' . $new_filename . '</li>';
}
}
}
$zip->close();
unlink($saved_file_location); #deletes the zip file. We no longer need it.
} else {
die("There was a problem. Please try again!");
}
} else {
$msg="There was a problem";
}
}

codeigniter get directory info in view

I'm essentially having difficulty pass dynamic variables to a view.
I have php functions as the following:
public function scandir_recursive($directory, $filter=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}elseif(is_readable($directory))
{
// initialize directory tree variable
$directory_tree = array();
// we open the directory
$directory_list = opendir($directory);
// and scan through the items inside
while (FALSE !== ($file = readdir($directory_list)))
{
// if the filepointer is not the current directory
// or the parent directory
if($file != '.' && $file != '..')
{
// we build the new path to scan
$path = $directory.'/'.$file;
// if the path is readable
if(is_readable($path))
{
// we split the new path by directories
$subdirectories = explode('/',$path);
// if the new path is a directory
if(is_dir($path))
{
// add the directory details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'kind' => 'directory',
// we scan the new path by calling this function
'content' => scandir_recursive($path, $filter));
// if the new path is a file
}elseif(is_file($path))
{
// get the file extension by taking everything after the last dot
$extension = end(explode('.',end($subdirectories)));
// if there is no filter set or the filter is set and matches
if($filter === FALSE || $filter == $extension)
{
// add the file details to the file list
$directory_tree[] = array(
'path' => $path,
'name' => end($subdirectories),
'extension' => $extension,
'size' => filesize($path),
'kind' => 'file');
}
}
}
}
}
// close the directory
closedir($directory_list);
// return file list
return $directory_tree;
// if the path is not readable ...
}else{
// ... we return false
return FALSE;
}
}
</code>
I need to make such a function operable in the sense I can echo the data retrieved from the directories recursively and pass this data to the view.
In the controller do the following:
$data['directory_tree'] = scandir_recursive($directory);
$this->load->view('my_view', $data);
In the view you can access the variable like this:
echo $directory_tree['path'];

Categories