I am trying to break down a folder path
eg: home/player/jay/profile/pictures:
home
home/players
home/players/jay
home/players/jay/profile
home/players/jay/profile/pictures
i tryed using this but i cant get it to displaying right
$new_folders = explode("/","home/player/jay/profile/pictures");
for ($i = 0; $i < sizeof($new_folders); $i++) {
for ($r = 0; $r < $i + 1; $r++) {
$create_new_path .= $new_folders[$r];
if ($r != $i) {
$create_new_path .= "/";
}
}
//ftp_mkdir($conn_id, "httpdocs/user_images/".$create_new_path);
//ftp_chmod($conn_id, 0777, "httpdocs/user_images/".$create_new_path);
}
$breakdown = array();
$dirs = explode('/', 'home/player/jay/profile/pictures');
$path = '';
foreach($dirs as $dir) {
$path .= ($path !== '' ? '/' : '') . $dir;
$breakdown[] = $path;
}
// result is in $breakdown
Related
i am trying to make an array of files which are part of a .zip file.
In the .zip file are 2 files: image1.jpg and image2.jpg
$zip = new ZipArchive;
if ($zip->open($_POST['extractfile']) === TRUE) {
$unzipped = 0;
$fails = 0;
$total = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$path_info = pathinfo($zip->getNameIndex($i));
$ext = $path_info['extension'];
$total ++;
echo $zip->getNameIndex($i);
The echo outputs only the first file: image1.jpg
How can i make an array of the files which are in the .zip file so that i can use a foreach loop like below:
foreach($extractfiles as $extractfile) {
echo $extractfile;
}
To the second part
<?php
$zip = new ZipArchive;
$extractfiles = [];
if ($zip->open($_POST['extractfile']) === TRUE) {
$unzipped = 0;
$fails = 0;
$total = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$path_info = pathinfo($zip->getNameIndex($i));
$ext = $path_info['extension'];
$total ++;
echo $zip->getNameIndex($i);
$extractfiles[] = $zip->getNameIndex($i);
}
}
foreach($extractfiles as $extractfile) {
echo $extractfile . "<br>" . PHP_EOL;
}
How to make directory within directory by php loop?
Example: http://site_name/a/b/c/d
First create a then b within a then c within b then ....
Problem is here a,b,c,d all the folders created in root directory not one within one.
Here is my code -
<?php
$url = "http://site_name/a/b/c/d";
$details1 = parse_url(dirname($url));
$base_url = $details1['scheme'] . "//" . $details1['host'] . "/";
if ($details1['host'] == 'localhost') {
$path_init = 2;
}else {
$path_init = 1;
}
$paths = explode("/", $details1['path']);
for ($i = $path_init; $i < count($paths); $i++) {
$new_dir = '';
$base_url = $base_url . $paths[$i] . "/";
$new_dir = $base_url;
if (FALSE === ($new_dir = folder_exist($paths[$i]))) {
umask(0777);
mkdir($new_dir . $paths[$i], 0777, TRUE);
}
}
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
?>
please check this code. it will create nested folder if not exit
<?php
$your_path = "Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$array_folder = explode('/', $your_path);
$mkyourfolder = "";
foreach ($array_folder as $folder) {
$mkyourfolder = $mkyourfolder . $folder . "/";
if (!is_dir($mkyourfolder)) {
mkdir($mkyourfolder, 0777);
}
}
hope it will help you
You can actually create nested folders with the mkdir PHP function
mkdir($path, 0777, true); // the true value here = recursively
Dear friends the following answer is tested and used in my script -
<?php
$url = "http://localhost/Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$details = parse_url(dirname($url));
//$base_url = $details['scheme'] . "//" . $details['host'] . "/";
$paths = explode("/", $details['path']);
$full_dir = '';
$init = ($details['host'] == 'localhost') ? '2' : '1';
for ($i = $init; $i < count($paths); $i++) {
$full_dir = $full_dir . $paths[$i] . "/";
if (!is_dir($full_dir)) {
mkdir($full_dir, 0777);
}
}
?>
How do we return the absolute path of largest file in a particular directory?
I've been fishing around and haven't turned up anything concrete?
I'm thinking it has something to do with glob()?
$sz = 0;
$dir = '/tmp'; // will find largest for `/tmp`
if ($handle = opendir($dir)) { // will iterate through $dir
while (false !== ($entry = readdir($handle))) {
if(($curr = filesize($dir . '/' . $entry)) > $sz) { // found larger!
$sz = $curr;
$name = $entry;
}
}
}
echo $dir . '/' . $name; // largest
$dir = 'DIR_NAME';
$max_filesize = 0;
$path= '';
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(realpath($dir),FilesystemIterator::SKIP_DOTS)) as $file){
if ($file->getSize() >= $max_filesize){
$max_filesize = $file->getSize();
$path = $file->getRealPath(); // get absolute path
}
}
echo $path;
function getFileSize($directory) {
$files = array();
foreach (glob($directory. '*.*') as $file) {
$files[] = array('path' => $file, 'size' => filesize($file));
}
return $files;
}
function getMaxFile($files) {
$maxSize = 0;
$maxIndex = -1;
for ($i = 0; $i < count($files); $i++) {
if ($files[$i]['size'] > $maxSize) {
$maxSize = max($maxSize, $files[$i]['size']);
$maxIndex = $i;
}
}
return $maxIndex;
}
usage:
$dir = '/some/path';
$files = getFileSize($dir);
echo '<pre>';
print_r($files);
echo '</pre>';
$maxIndex = getMaxFile($files);
var_dump($files[$maxIndex]);
I have the code below.
It first create a dynamic folder with name like v3_12-02-2012-12873547839. Then it creates a subfolder called "image" and saves some jpeg images in the subfolder. Then it create a csv file and put it in "v3_12-02-2012-12873547839"
Then it creates a zip folder in the project folder with name "v3_12-02-2012-12873547839.zip"
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', $source);
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
if (strpos($flag.$file,$source) !== false) { // this will add only the folder we want to add in zip
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
}
Now the problem is, when I am trying to delete the folder, the folder somehow doesn't seem to delete, though I can recursively delete all its contents. Even though the folder becomes empty at the end, it doesn't get deleted.
Error I am getting:
Warning: rmdir(./v3-02-12-2014-1417512727): Permission denied in C:\xampp\htdocs\projecthas2offer\appwall_dev\frontend\ajax.php on line 265
Instances of ZipArchive and/or RecursiveIteratorIterator still live and might still have their hands on your directory, so free them using unset( $zip, $files );
I am using the following script for listing the files in a particular directory as a hyperlink list.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
echo "<li><a href='$files[$x]'>$files[$x]</a></li>";
}
Please tell us whether the following is possible
1. The file extension should not be displayed
2. I need " " instead of "-" in the file names
If possible how to incorporate it.
Update 2:
Thanks for your kindly help. I followed,
The files names which i have mentioned must not be displayed (like dont display index.php), How do i change the code for this?
<?php
$directory = '';
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", " ", $parts['filename']);
echo "<li>{$name}</li>";
}
?>
Try the following using glob in a loop.
$directory = 'folder/';
foreach (glob($directory . "*.*") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", "", $parts['filename']);
echo "{$name}";
}
Example with your provided code, two lines added pathinfo and a preg_replace.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
$parts = pathinfo($files[$x]);
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li><a href='$files[$x]'>$name</a></li>";
}
Updated:
The following doesn't show the files called index.php, wtf.php, and hide.php
$directory = 'folder/';
$blacklist = array(
'index',
'wtf',
'hide'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}