So far after looking of multiple examples of how to unzip a file i'm a little confused on what i'm missing for this to work now.
Im using WordPress and AdvancedCustomFields to designate what kind of file i'm going to be uploading. I need to unzip this file and figure out the internal files to use one as a source.
} else if(get_sub_field('media_type') == 'Zip'){
/* Get Path Name */
$file = get_sub_field('file');
$pieces = explode("/", $file);
$lastZip = end($pieces);
array_pop($pieces ); //removes last
$path = implode("/", $pieces);
$path = $path."/";
/* Get Name of File and concat .png */
$last = explode(".", $lastZip);
$last = $last[0].".png";
/* Append new filename to proper pathing */
$pathFile = $path.$last;
$zip = new ZipArchive;
$zip->open($lastZip, ZipArchive::CREATE);
print_r($zip);
if ($zip === TRUE) {
$zip->extractTo($path);
$zip->close();
echo 'File extracted to: $path';
} else {
echo "does not work!";
}
?><span><img src="<?php echo $pathFile; ?>" /></span>
<?php
}
My outcome of print_r($zip) is:
ZipArchive Object (
[status] => 0
[statusSys] => 0
[numFiles] => 0
[filename] => /var/www/vhosts/domain.com/httpdocs/example.zip
[comment] =>
)
Related
Code to download all certificates:
<?php
require_once('../../config.php');
global $DB,$CFG;
$certlist = $_POST['select_cert'];
print_r($certlist);
$files = array('niBMkaooT.jpg');
$zip = new ZipArchive();
$zip_name = time().".zip";
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
$path = $file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
?>
if($certificate!=''){
echo "<input type='checkbox' class='checkboxcert' name='select_cert[]' value='$certificate'>";
}
echo "</td>";
echo "<td>";
Also below i am getting $certificate and when i am downloading individual certificates this is working fine . But when selecting multiple document i am not able to download all
$certificate = get_certificate($userid,$c_id);
Please find the array which i have printed (print_r($certlist))
Array ( [0] => https://google.com/lms/plufile.php/69402/mod_certificate/issue/484123/Abu 2021_Abu, Neglecting, and Exploitation.pdf [1] =>
Please advise what changes are required?`
The certificate PDF isn't always saved, so the file might not always be available
I'd suggest creating and saving the PDF in your own code
Have a look at how the PDF is saved in the view code
https://github.com/mdjnelson/moodle-mod_certificate/blob/master/view.php
if ($certificate->savecert == 1) {
certificate_save_pdf($filecontents, $certrecord->id, $filename, $context->id);
}
Then work backwards from there to see how the variables are created
eg. $USER is the current user
$certrecord = certificate_get_issue($course, $USER, $certificate, $cm);
So you will need to replace that with the required $user in your code
$certrecord = certificate_get_issue($course, $user, $certificate, $cm);
I have zip files with only one file inside it, but it has new name every time. I need to extract file and save it with specific file name, not extracted one.
$zip = new ZipArchive;
$res = $zip->open($tmp_name);
if ($res === TRUE) {
$path = _PATH."/files/";
$zip->extractTo($path);
$zip->close();
echo 'Unzip!';
}
Abowe code works, but I need to have specific filename. For example anyfile located under zip (eg. pricelist025.xml should be named temp.xml
Rename your specific file before you extract it.
$zip = new ZipArchive;
$res = $zip->open($tmp_name);
if ($res === TRUE) {
$zip->renameName('pricelist025.xml','temp.xml');
$path = _PATH."/files/";
$zip->extractTo($path);
$zip->close();
echo 'Unzip!';
} else {
echo 'failed, code:' . $res;
}
I hope this works.
UPDATE 1
There is two options if you want to change the file names.
1. change the file names before extracting -This way zip files will be modified
2. change the file names after extracting -Zip files will remain as they were before
Changing file names before extracting
We have to define a pattern for filenames. Here, Files will be in this patter : myfile0.xml, myfile1.html, adn so on..
Note: extension will be preserved.
$zip = new ZipArchive;
$res = $zip->open('hello.zip');
$newfilename = 'myfile';
for($i=0;$i<$zip->count();$i++)
{
$extension = pathinfo($zip->getNameIndex($i))['extension'];
$zip->renameName($zip->getNameIndex($i), $newfilename.$i.'.'.$extension);
}
Chaning file names after extracting
File names will in the same pattern as above.
$directory = 'hello/'; //your extracted directory
$newfilename = 'myfile';
foreach (glob($directory."*.*") as $index=>$filename) {
$basename = pathinfo($filename)['basename'];
if(!preg_match('/myfile\d\./', $basename)) {
$extension = pathinfo($filename)['extension'];
rename($filename,$newfilename.$index.'.'.$extension);
}
}
What we are here scanning the all the files from the extracted directory for which doesn't have a filename in the patter myfile[num]. and then we are changing it's name.
UPDATE 2
I just noticed you have updated your question.
As you have just one file and you want to extract it every time with different name. You should rename it every time you extract.
$zip = new ZipArchive;
$newfilename = "myfile".rand(1,999); //you can define any safe pattern here that suites you
if($zip->open('help.zip')===TRUE)
{
$path = '/your/path/to/directory';
$filename = $zip->getNameIndex(0);
if($zip->extractTo($path))
{
echo "Extracted";
}else{
echo "Extraction Failed";
exit();
}
$extension = pathinfo($filename)['extension'];
rename($path."/$filename",$path."/$newfilename".'.'.$extension);
echo "Extracted with different name successfully!";
} else {
echo "Failed";
}
I'm trying to get the svg files from a folder.
Tried the following ways but none of them seems to work:
<?php
$directory = get_bloginfo('template_directory').'/images/myImages/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while ($it->valid()) { //Check the file exist
if (!$it->isDot()) { //if not parent ".." or current "."
if (strpos($it->key(), '.php') !== false
|| strpos($it->key(), '.css') !== false
|| strpos($it->key(), '.js') !== false
) {
echo $it->key() . '<br>';
}
}
}
?>
And:
global $wp_filesystem;
$path = get_bloginfo('template_directory').'/images/myImages/';
$filelist = $wp_filesystem->dirlist( $path );
echo $filelist;
And:
$path = get_bloginfo('template_directory').'/images/myImages/';
$images = scandir( $path, 'svg', $depth = 0);
echo $images;
And:
$dir = get_bloginfo('template_directory').'/images/myImages/';
$files = scandir($dir);
print_r($files);
And:
$directory = get_bloginfo('template_directory')."/images/myImages/";
$images = glob($directory . "*.svg");
echo '<pre>';
print_r($images);
echo '</pre>';
echo $directory.'abnamro.svg">';
foreach($images as $image)
{
echo $image;
}
I'm kinda lost. I might think that there is something else wrong.
Also checked the privileges for the user but all is okay.
I run Wordpress on a local machine with MAMP.
Any thoughts?
Try the function below, I have notated for clarity. Some highlights are:
You can skip dots on outset in the directory iterator
You can trigger a fatal error if path doesn't exist (which is the issue in this case, you are using a domain-root path instead of the server root path [ABSPATH])
You can choose the extension type to filter files
function getPathsByKind($path,$ext,$err_type = false)
{
# Assign the error type, default is fatal error
if($err_type === false)
$err_type = E_USER_ERROR;
# Check if the path is valid
if(!is_dir($path)) {
# Throw fatal error if folder doesn't exist
trigger_error('Folder does not exist. No file paths can be returned.',$err_type);
# Return false incase user error is just notice...
return false;
}
# Set a storage array
$file = array();
# Get path list of files
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::SKIP_DOTS)
);
# Loop and assign paths
foreach($it as $filename => $val) {
if(strtolower(pathinfo($filename,PATHINFO_EXTENSION)) == strtolower($ext)) {
$file[] = $filename;
}
}
# Return the path list
return $file;
}
To use:
# Assign directory path
$directory = str_replace('//','/',ABSPATH.'/'.get_bloginfo('template_directory').'/images/myImages/');
# Get files
$files = getPathsByKind($directory,'svg');
# Check there are files
if(!empty($files)) {
print_r($files);
}
If the path doesn't exist, it will now tell you by way of system error that the path doesn't exist. If it doesn't throw a fatal error and comes up empty, then you actually do have some strange issue going on.
If all goes well, you should get something like:
Array
(
[0] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img1.svg
[1] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img2.svg
[2] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img3.svg
[3] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img4.svg
)
If path invalid, will throw:
Fatal error: Folder does not exist. No file paths can be returned. in /data/19/2/133/150/3412/user/12321/htdocs/domain/index.php on line 123
I have some videos,images and text files in "uploads/video/" dir.
Here i am getting all the files using scandir but I want only videos from that folder.
Sample code :
$video_dir = 'uploads/video/';
$video_array = scandir($video_dir);
unset($video_array[0]);
unset($video_array[1]);
echo "<pre>";
print_r($video_array);
echo "</pre>";
Getting Result :
Array ( [2] => ADD.mp4 [3] => COO_Notes.txt [4] => Carefree.mp3 [5] => Circus Tent.mp3 [6] => Phen.mp4 [7] => REM.mp4 [8] => images (9).jpg [9] => images.jpg [10] => test.php )
I need only video files. Remove the text,mp3,jpg,etc files:
Array ( [2] => ADD.mp4 [6] => Phen.mp4 [7] => REM.mp4)
Thanks for your updates.
You can use glob():
<?php
foreach (glob("*.mp4") as $filename) {
echo "$filename - Size: " . filesize($filename) . "\n";
}
# or:
$video_array = glob("*.mp4");
?>
In order to get multiple formats, simply put the extensions in curly braces and add the parameter GLOB_BRACE:
$video_array = glob('uploads/video/{*.mp4,*.flv,*.mov}', GLOB_BRACE);
See it on PHP.net here.
I believe the function pathinfo should help you out.
http://php.net/manual/en/function.pathinfo.php
<?php
$videos = array();
$video_ext = array('mp4', 'mpeg');
foreach ($video_array as $path) {
if (in_array(pathinfo($path, PATHINFO_EXTENSION), $video_ext)) {
//less general, but will work if you know videos always end in mp4
//if (pathinfo($path, PATHINFO_EXTENSION) == "mp4") {
$videos[] = $path;
}
}
You may check file type with mime_content_type: http://php.net/manual/en/function.mime-content-type.php.
Assume this will be something like:
$videos = array();
$dir = 'uploads';
$files = scandir($dir);
foreach($files as $file) {
$filepath = $dir . '/' . $file;
if(is_file($filepath)) {
$contentType = mime_content_type($filepath);
if(stripos($contentType, 'video') !== false) {
$videos[] = $file;
}
}
}
Also this may be not very fast and perhaps will not detect all possible (strange) video files (as it uses magic.mime). But this may work without array of file extensions and also will look at file itself rather than filename.
I am working on a pretty large PHP class that does a lot of stuff with Image Optimization from the Command line, you basically pass the program an Image path or a Folder path that has multiple images inside of it. It then runs the files through up to 5 other command line programs that optimize images.
Below is part of a loop that gathers the images paths, if the path is a Folder instead of an image path, it will iterate over all the images in the folder and add them to the image array.
So far I have everything working for single images and images in 1 folder. I would like to modify this section below so it could recursively go deeper then 1 folder to get the image paths.
Could someone possibly show me how I could modify this below to accomplish this?
// Get files
if (is_dir($path))
{
echo 'the path is a directory, grab images in this directory';
$handle = opendir($path);
// FIXME : need to run recursively
while(FALSE !== ($file = readdir($handle)))
{
if(is_dir($path.self::DS.$file))
{
continue;
}
if( ! self::is_image($path.self::DS.$file))
{
continue;
}
$files[] = $path.self::DS.$file;
}
closedir($handle);
}else{
echo 'the path is an Image and NOT a directory';
if(self::is_image($path))
{
echo 'assign image Paths to our image array to process = '. $path. '<br><br>';
$files[] = $path;
}
}
if (!count($files))
{
throw new NoImageFoundException("Image not found : $path");
}
UPDATE
#Chris's answer got me looking at the Docs and I found an example that I modified to this that seems to work
public static function find_recursive_images($path) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $path) {
if ($path->isDir()) {
//skip directories
continue;
} else {
$files[] = $path->__toString();
}
}
return $files;
}
...
$files = self::find_recursive_images($path);
echo '<pre>';
print_r($files);
echo '</pre>';
exit();
The output is JUST the filenames and there path like this which is my ultimate goal, so far this works perfect but as always if there is a better way I am all for improving
(
[0] => E:\Server\_ImageOptimize\img\testfiles\css3-generator.png
[1] => E:\Server\_ImageOptimize\img\testfiles\css3-please.png
[2] => E:\Server\_ImageOptimize\img\testfiles\css3-tools-10.png
[3] => E:\Server\_ImageOptimize\img\testfiles\fb.jpg
[4] => E:\Server\_ImageOptimize\img\testfiles\mysql.gif
[5] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-generator.png
[6] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-please.png
[7] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-tools-10.png
[8] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\fb.jpg
[9] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\mysql.gif
[10] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\support-browsers.png
[11] => E:\Server\_ImageOptimize\img\testfiles\support-browsers.png
)
While andreas' answer probably works, you can also let PHP 5's RecursiveDirectoryIterator do that work for you and use a more OOP approach.
Here's a simple example:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
while ($it->valid())
{
if ($it->isDot())
continue;
$file = $it->current();
if (self::is_image($file->pathName))
{
$files[] = $file->pathName;
}
$it->next();
}
Edit:
Alternatively, you could try this (copied from Zend_Translate_Adapter):
$it = new RecursiveIteratorIterator(
new RecursiveRegexIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::KEY_AS_PATHNAME),
'/^(?!.*(\.svn|\.cvs)).*$/', RecursiveRegexIterator::MATCH
),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $dir => $info)
{
var_dump($dir);
}
Cheers
Chris
Create a recursive function to read a directory, then read further if a directory is found during the loop.
Something along the line of:
function r_readdir($path) {
static $files = array();
if(!is_dir($path)) {
echo 'the path is an Image and NOT a directory';
if(self::is_image($path))
{
echo 'assign image Paths to our image array to process = '. $path. '<br><br>';
$files[] = $path;
}
} else {
while(FALSE !== ($file = readdir($handle)))
{
if(is_dir($path.self::DS.$file))
{
r_readdir($path.self::DS.$file);
}
if( ! self::is_image($path.self::DS.$file))
{
continue;
}
}
closedir($handle);
}
return $files;
}