I'm currently trying to merge several .csv files with the following code:
<?php $csvdir = get_template_directory() . '/exports';
$csvcontent = '';
if (is_dir($csvdir)) {
if ($handle = opendir($csvdir)) {
while (($file = readdir($handle)) !== false) {
if (substr($file, -4) === ".csv") {
$csvcontent .= file_get_contents($csvdir . $file);
}
}
closedir($handle);
}
}
$result = fopen('app/merge.csv', 'w');
fwrite($result, $csvcontent);
fclose($result); ?>
It's outputting a blank csv file at the moment with no errors. Is there anything obvious wrong with the code?
The template to generate this is in the same directory as the exports folder.
As I have mentioned in the comment, you are missing / after the exports directory name. Hence, the file name is going wrong while reading contents from it.
Also, check the directory is a valid one by echo $csvdir and echo is_dir($csvdir) before the processing starts.
Here is the working demo: https://repl.it/#fiveelements/MergeCSVContents
And here is your modified code:
<?php $csvdir = './exports/';
$csvcontent = '';
if (is_dir($csvdir)) {
if ($handle = opendir($csvdir)) {
while (($file = readdir($handle)) !== false) {
if (substr($file, -4) === ".csv") {
$csvcontent .= file_get_contents($csvdir . $file);
}
}
closedir($handle);
}
}
echo $csvcontent;
$result = fopen('exports/merge.csv', 'w');
fwrite($result, $csvcontent);
fclose($result); ?>
Related
I am trying to open a sub folder when user clicked on main directory url link. It does not either show any errors or content.
Here is my php code to open main folder which is working fine.
$loc = 'C:/Apache24/htdocs/www.test.in/stRec';
if (is_dir($loc)){
if ($dh = opendir($loc)){
while (($file = readdir($dh)) !== false){
echo''.$file.'';
}
}
}
Code to open sub directory which shows no content.
if(isset($_GET['dir'])) {
$dir = $_GET['dir'];
$loc = 'C:/Apache24/htdocs/www.test.in/stRec'.$dir;
if (is_dir($loc)){
if ($dh = opendir($loc)){
while (($file = readdir($dh)) !== false){
echo $file;
}
}
}
}
C:/Apache24/htdocs/www.test.in/stRec'.$dir
path separator on windows is "\"
edit:
To get more details:
<?php
if (!isset($_GET['dir'])) {
die('dir not set');
}
$dir = $_GET['dir'];
$loc = 'C:\whatever\path' . $dir;
if (!is_dir($loc)) {
die('not a dir');
}
if ($handle = opendir($loc)) {
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
closedir($handle);
}
For the below code I have multiple directories and files. I can display one filename per directory(Which is good with the "BREAK").
<?php
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
break;
//---- if ($i>=5) { break; }
}
closedir($dh);
}
}
?>
With
if ($i>=5) { break; } I can still display 5 filenames but it reads only one directory.
I want to display at least 5 file names from all directories, how can I do it?
Use the scandir function.
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
or
If you are using unix you could also do a system call and run the following command.
ls /$dir | head -5
$dir is the directory and -5 is the number filenames in the directory.
Since you said that you have multiple directory's, I rewrote your code a bit:
(Here I first loop through all directory's with array_map() then I get all files from each directory with glob(). After this I just limit the files per directory with array_slice() and at the end I simply print all file names)
<?php
$directorys = ["images/", "xy/"];
$limit = 3;
//get all files
$files = array_map(function($v){
return glob("$v*.*");
}, $directorys);
//limit files per directory
$files = array_map(function($v)use($limit){
return array_slice($v, 0, $limit);
}, $files);
foreach($files as $directory) {
echo "<b>Directory</b><br>";
foreach($directory as $file)
echo "$file<br>";
echo "<br><br>";
}
?>
You don't have to break it, you can just skip it. And in doing so, you have to use continue instead.
$dir = "/images/";
$i=0;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
}
closedir($dh);
}
}
Here is also another scenario. Because you mentioned that you have many directories but you only show one main directory, I am guessing that the directories you've mentioned were inside the /images/ directory.
$dir = "images/";
$i=1;
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
$j=1;
if (is_dir($file)) {
if ($internalDir = opendir($file)) {
while (($internalFile = readdir($internalDir)) !== false) {
echo $file."->filename: ".$internalFile."<br>";
if ($j>=5)
continue;
$j++;
}
closedir(opendir($file));
}
} else {
echo "filename:" . $file . "<br>";
if ($i>=5)
continue;
$i++;
}
}
closedir($dh);
}
}
Read more about continue here: http://php.net/manual/en/control-structures.continue.php
I want to create a system which will include any .php file from a folder, similar to wordpress\plugins folder. Preferably drag and drop.
Any ideas how to do it?
Question is not clear...
read the folder files
scroll through the files found
if PHP - include it
<?php
function scandir2($dir)
{
$out = array();
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if ($file == '.' or $file == '..') continue;
if (!is_dir($dir . '/'. $file))
{
$out[] = $dir . '/' . $file;
}
}
closedir($dh);
}
}
sort($out);
return $out;
}
$i=scandir2(".");
foreach($i as $name)
{
if(strstr($name ,'.php'))
include($name);
}
?>
this code scan directory and include php files ...
Here is the code to do that:
foreach (glob("/path/*.php") as $filename) {
include $file;
}
The glob() function returns an array of all .php files on the specified path.
Here is how I would do it...
<?php
$dirPath = '/path/to/files';
if ($handle = opendir($dirPath)) {
/* loop over files in directory */
while (false !== ($entry = readdir($handle))) {
/* find extension */
$ext = substr($entry,-3);
$ext = strtolower($ext);
/* include file if extension is PHP */
if ($ext === 'php') {
include_once($dirPath .'/'. $entry);
} //if
} //if
closedir($handle);
} //if
Note that there is several security concerns and possibly performance concerns.
Sequel to my question here: Addslashes displays as forward slashes in php ,
I want to strip slashes from the filenames of files i have on my server. the slashes were added during file upload (magic_quotes).
Please how can i go about this? thanks
Here you go:
<?php
$path = '/path/to/files/dir/';
$file_types = 'txt,doc,pdf';
foreach (glob($path.'*.{'.$file_types.'}', GLOB_BRACE) as $filename){
if(rename($filename , stripslashes($filename))){
echo 'Renamed file from '.$filename.' to '.stripslashes($filename).'<br />';
} else{
echo 'Failed to rename file from '.$filename.' to '.stripslashes($filename).'<br />';
}
}
?>
Change path to files and the comma separated list of file types.
Update with asker's code on the comments:
$dir='cv';
if(is_dir($dir)){
if ($dh = opendir($dir)) {
while (false !== ($file = readdir($dh))) {
if ($file != "." && $file != "..") {
$file2 = $dir."/".$file; $newfile=$dir."/".stripslashes(urldecode($file));
if(rename($file2, $newfile)){
echo "renamed from $file2 to $newfile <br>";
} else{
echo "error renaming from $file2 to $newfile <br>";
}
}
}
closedir($dh);
}
}
http://php.net/function.stripslashes
I have a number of text files held in directory
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A couple of things:
Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
Use opendir(), readdir() and closedir() for reading directory contents; and
Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}