Php gunzip and get name - php

Good morning!
I unzipped the archive using php, but after that I need to get the name of the files and perform another action, but I can not figure out how to do it.
Is it possible to do this with php? If so, tell me how and, if possible, an example, even a light one.
Thanks
$filelist = glob("/emp/*.gz");
$filedirtxt = glob("/emp/*.txt");
foreach ($filelist as $key => $value) {
$filename = pathinfo($value);
$gzname = $filename['basename'];
$gunzip = shell_exec("gunzip "."/emp/".$gzname);
foreach ($filedirtxt as $keytxt => $valuetxt) {
$filename_txt = pathinfo($valuetxt);
$name_txt = $filename_txt['basename'];
echo $name_txt."\n";
}
}

Related

listObject equivelent in Azure using php sdk

I am new to Azure and i'm trying to list all objects within a blob with an extension of .json
I can do this easily in AWS and it works perfectly. I've been trying to find an equivalent command in Azure.
Here is what i've tried. It only returns the first .json file.
I need to list all the .json files in all folders ( I know they are not really folders but hopefully people understand what i'm trying to do )
$containerName = 'calls';
$result = $blobClient->listBlobs($containerName, $listBlobsOptions);
foreach ($results as $result) {
$keyname = $result['keyname'];
echo "\n Key name is ".$keyname; // I can see the keyname
if (strpos($keyname, 'meta-data.json') !== false) {
$id = $result['id'];
echo "\n" . $count;
$blobUrl = $keyname; // I get the blob url returned but its only ever the first level
$metadata = file_get_contents($blobUrl); // tried to get the file.. no success , another issue to address later
echo $metadata;
}
}
Any help would be greatly appreciated.
You can use the below code to list blobs in a folder by using azure php SDK:
// List blobs.
$key = 'keyname';
$blobListOptions = new ListBlobsOptions();
$blobListOptions->setPrefix($key);
$blobList = $blobRestProxy->listBlobs($blobContainer, $blobListOptions);
foreach($blobList->getBlobPrefixes() as $key => $blob) {
echo "BlobPrefix ".$key.": \t".$blob->getName()."\n";
}
foreach($blobList->getBlobs() as $key => $blob) {
echo "Blob ".$key.": \t".$blob->getName()."\t(".$blob->getUrl().")\n";
}
Thanks to Microsoft for providing more information on Azure PHP SDKs in GitHub here.

PHP 5.3.x - How do I turn the server path into its domain name, and a clickable URL?

I'm a newbie...sorry...I'll admit that I've cobbled this script together from several sources, but I'm trying to learn. :-) Thanks for any help offered!!
$directory = new \RecursiveDirectoryIterator(__DIR__, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
if ($current->getFilename() === '.') {
return FALSE;
}
if ($current->isDir()) {
return $current->getFilename() !== 'css';
}
else {
// Only consume files of interest.
return strpos($current->getFilename(), 'story.html') === 0;
}
});
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
$files[] = $info->getPathname();
}
?>
Then down in my HTML is where I run into problems, in the 2nd echo statement...
<?php
echo '<ul>';
foreach ($files as $item){
echo '<li>http://<domain.com/directory/subdirectory/story.html></li>';
echo '</ul>';
};
?>
The purpose of my script is to "crawl" a directory looking for a specific file name in sub-directories. Then, when it finds this file, to create a human-readable, clickable URL from the server path. Up to now, my HTML gets one of these two server paths as my list item:
http://thedomain.com/var/www/vhosts/thedomain.com/httpdocs/directory/subdirectory/story.html
or
file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html
...depending on where I'm running my .php page.
I feel like I need to "strip away" part of these paths... to get down to /subdirectory/story.html ... If I could do that, then I think I can add the rest into my echo statements. Everything I've found for stripping strings has been from the trailing end of the path, not the leading end. (dirname($item)) takes away the filename, and (basename($item)) takes away the subdirectory and the filename ... the bits I want!!
Try this function
function strip($url){
$info = parse_url($url);
$slash = (explode('/',$info['path']));
$sub = $slash[count($slash)-2];
$file = basename($url)==$sub ? "" : basename($url);
return "/".$sub."/".$file;
}
calling it by
echo strip('file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html');
will result in
/subdirectory/story.html

PHP Get all files but not in subdirectories

Im using this code:
$path = realpath('');
$i = 0;
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object){
and it gets all sub directories in the main directory, when I only want it to get in the current directory
How would I go about doing that?
You could make use of glob() instead.
<?php
chdir('yourcurrentdirectory');
foreach(glob("*.*") as $file)
{
echo $files."<br>";
}

Arrays from multiple upload form, Upload images then insert to database (PHP, MySQL)

Language: PHP / MySQL
I am going out of my mind, I really have to ask now... I have a multiple file upload form:
<input type="file" name="fileupload[]" multiple>
With the help of some Javascript, on each change made to this input, it appends a list of filenames, + a formatted string (grabbed from the filename) inside another input, so onchange we have a layout as shown below (assuming that we just added some images):
Almost similar to: http://jsfiddle.net/pxfunc/WWNnV/4/
// An HTML representation of such layout would be... (assuming that we added 3 images)
<input type="file" name="fileupload[]" multiple>
image-name-1.jpg <input type="text" value="Image Name 1" name="keyword[]">
justsome_file.png <input type="text" value="Justsome File" name="keyword[]">
some_Img-031.gif <input type="text" value="Some Img 031" name="keyword[]">
<input type="submit" value="Upload">
I have it this way because aside from uploading the files, I would also like to add them to my database, with a default title based on its filename (and the option to set/change this title for each image as I upload it). There is no problem with my form.
PROBLEM: My dilemma lies inside the PHP page where the form data/action is submitted.
I can only manage to either:
Upload correct images, but get same title for all
Insert correct titles, but get same image for all
Here is my PHP action page: (Currently uploading correct images, but having same title for all)
<?php
// CONNECT TO DATABASE...
// INCLUDE UPLOAD CLASS LIBRARY
include (dirname(__FILE__).'/lib/class.upload.php');
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
// create an array here to hold file names
$uploaded = array();
foreach ($files as $file)
{
$generate_name = rand(100,99999);
$generate_name_extra = rand(200,9999);
$filenamex = "COVER_PHOTO_".$generate_name.$generate_name_extra."_".time();
$filenamex_thumb = $filenamex."_thumb";
$handle = new upload($file);
if ($handle->uploaded) {
$this_upload = array();
///// 1 ////////////////////////////////////////////////////////////////////
$handle->file_new_name_body = $filenamex_thumb;
$handle->file_force_extension = true;
$handle->image_resize = true;
$handle->image_x = '300';
$handle->image_ratio_y = true;
$handle->jpeg_quality = '100';
// ABSOLUTE PATH BELOW
$handle->process($absoRoot.'covers/thumbs/');
////////////////////////////////////////////////////////////////////////////
if ($handle->processed) {
// store the image filename
$this_upload['image'] = $handle->file_dst_name; // Destination file name
$this_upload['body'] = $handle->file_dst_name_body; // Destination file name body
$this_upload['extension'] = $handle->file_dst_name_ext; // Destination file extension
$category_id = $_POST['cat'];
$hiddenvalues = explode ("|",$_POST["cat"]);
$category = $hiddenvalues[0];
$category_name = $hiddenvalues[1];
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id) VALUES ("", "'.$this_upload['image'].'", "'.$imagename.'", "'.$category_name.'", "'.$category.'")';
mysql_query($sql);
}
$handle->clean();
header("Location: ./upload.php");
$message = "";
} else {
echo ' file not uploaded to the wanted location';
echo ' Error: ' . $handle->error . '';
}
} ?>
(I use the Upload Class by Colin Verot to handle image uploads, and their FAQ tutorial to handle MULTIPLE image uploads on this page, under: What about multiple uploads?)
This would work perfect if I were just uploading images, however I added the functionality of adding each image data to my database. & This is where it gets confusing.
I'm sure the key is placing the SQL query inside the right foreach, or perhaps making another one, but I've tried that & it only gives me 1 good result for either the image upload or the title, never for both.
I need to upload the image to the site, then store its data (including image path) to my database.
Please look into my code and enlighten me how to solve this problem? A snippet clue would really be great for now as I am already very confused after having tried all I could think of. Thank you so much!
You aren't saving your $imagename variable to the $files array, you're just resetting it each time.
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
Should be something like:
$files[$i][$k] = array($v, $_POST['keyword'][$i]);
...
foreach ($files as $data) {
list($file, $imagename) = $data;
...
}
I do think one of your problems is your foreach:
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
So you are going through each of the fields assigning their value to the right file which fits this structure policy:
_FILES => array(
'name' => array(0 => 'file.txt'),
'size' => array(0 => 235)
)
Which is correct for multifiles but then you do:
$imagename = $_POST['keyword'][$i];
Which does not look right. You are overwriting the var each time with the last looked at which means you will only ever get one input vlaue.
When you're gathering the file information you're overwriting $imagename on every loop so it will be assigned to the last one. Try attaching it to the $files variable (hopefully this doesn't mess with the upload class you're using).
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$files[$i]['imagename'] = $_POST['keyword'][$i];
}
Then update your $sql string to reference that
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id)
VALUES ("", "'.$this_upload['image'].'", "'.$file['imagename'].'",
"'.$category_name.'", "'.$category.'")';

PHP: Get list of all filenames contained within my images directory [duplicate]

This question already has answers here:
How to read a list of files from a folder using PHP? [closed]
(9 answers)
Closed 7 years ago.
I have been trying to figure out a way to list all files contained within a directory. I'm not quite good enough with php to solve it on my own so hopefully someone here can help me out.
I need a simple php script that will load all filenames contained within my images directory into an array. Any help would be greatly appreciated, thanks!
Try glob
Something like:
foreach(glob('./images/*.*') as $filename){
echo $filename;
}
scandir() - List files and directories inside the specified path
$images = scandir("images", 1);
print_r($images);
Produces:
Array
(
[0] => apples.jpg
[1] => oranges.png
[2] => grapes.gif
[3] => ..
[4] => .
)
Either scandir() as suggested elsewhere or
glob() — Find pathnames matching a pattern
Example
$images = glob("./images/*.gif");
print_r($images);
/* outputs
Array (
[0] => 'an-image.gif'
[1] => 'another-image.gif'
)
*/
Or, to walk over the files in directory directly instead of getting an array, use
DirectoryIterator — provides a simple interface for viewing the contents of filesystem directories
Example
foreach (new DirectoryIterator('.') as $item) {
echo $item, PHP_EOL;
}
To go into subdirectories as well, use RecursiveDirectoryIterator:
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('.'),
RecursiveIteratorIterator::SELF_FIRST
);
foreach($items as $item) {
echo $item, PHP_EOL;
}
To list just the filenames (w\out directories), remove RecursiveIteratorIterator::SELF_FIRST
You can also use the Standard PHP Library's DirectoryIterator class, specifically the getFilename method:
$dir = new DirectoryIterator("/path/to/images");
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
This will gives you all the files in links.
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/your_folder/";
$files = scandir($path);
$count=1;
foreach ($files as $filename)
{
if($filename=="." || $filename==".." || $filename=="download.php" || $filename=="index.php")
{
//this will not display specified files
}
else
{
echo "<label >".$count.". </label>";
echo "".$filename."
";
$count++;
}
}
?>
Maybe this function can be useful in the future. You can manipulate the function if you need to echo things or want to do other stuff.
$wavs = array();
$wavs = getAllFiles('folder_name',$wavs,'wav');
$allTypesOfFiles = array();
$wavs = getAllFiles('folder_name',$allTypesOfFiles);
//explanation of arguments from the getAllFiles() function
//$dir -> folder/directory you want to get all the files from.
//$allFiles -> to store all the files in and return in the and.
//$extension -> use this argument if you want to find specific files only, else keept empty to find all type of files.
function getAllFiles($dir,$allFiles,$extension = null){
$files = scandir($dir);
foreach($files as $file){
if(is_dir($dir.'/'.$file)) {
$allFiles = getAllFiles($dir.'/'.$file,$allFiles,$extension);
}else{
if(empty($extension) || $extension == pathinfo($dir.'/'.$file)['extension']){
array_push($allFiles,$dir.'/'.$file);
}
}
}
return $allFiles;
}

Categories