Cannot use SplFileObject with directories - php

I used splfileobject to open the file in PHP. File is in the same directory below code is work fine. If file is another directory and is shows error like Cannot use SplFileObject with directories
$file = new SplFileObject("files/".$file_name);
$row = 1;
while (!$file->eof()) {
$data[$row] = $file->fgetcsv();
$row++;
}

If you just want to skip directories, then is_dir() will allow you to check the type and skip it...
if ( is_dir("files/".$file_name ) == false ) {
$file = new SplFileObject("files/".$file_name);
$row = 1;
while (!$file->eof()) {
$data[$row] = $file->fgetcsv();
$row++;
}
}

Related

PHP File count inside a folder

I'm using bootstrap tables and rows to count how much files are in a folder, but the destination is pointing to a different server the code below does not work.
As i'm using localhost (xampp) trying to do this don't know if its possible.
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/'; <!--\\189.207.00.122\folder1\folder2\folder3\test-->
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
Here is a handy little function you might want to try out. Just pass the path to the Directory as the first argument to it and you'd get your result.
NOTE: This Function is RECURSIVE, which means: it will traverse all sub-directories... to disable this behaviour, simply comment out or delete the following lines towards the end of the Funciton:
<?php
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
THE CODE:
<?php
$folder = dirname(__FILE__).'/uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS IN THE SAME DIRECTORY AS index.php
// (/htdocs/php/pages)
// OR
$folder = dirname(__FILE__).'/../uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS ONE DIRECTORY ABOVE
// THE CURRENT DIRECTORY (/htdocs/php)
// THIS IS MOST LIKELY RIGHT
// OR
$folder = dirname(__FILE__).'/../../uploads';// ASSUMES YOUR uploads DIRECTORY
// IS TWO DIRECTORIES ABOVE
// THE CURRENT DIRECTORY (/htdocs)
// MAKE SURE THE FOLDER IN QUESTION HAS THE RIGHT PERMISSIONS
// OR RATHER CHANGE PERMISSIONS ON THE FOLDER TO BE ABLE TO WORK WITH IT
chmod($folder, 0777);
var_dump(getFilesInFolder($folder));
// IF YOU PASS false AS THE THE 2ND ARGUMENT TO THIS FUNCTION
// YOU'D GET AN ARRAY OF ALL FILES IN THE $path2Folder DIRECTORY
// AS WELL AS IN SUB-DIRECTORIES WITHIN IT...
function getFilesInFolder($path2Folder, $countOnly=true){
$files_in_dir = scandir($path2Folder);
$returnable = array();
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $path2Folder . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && !preg_match("#^\..*#", $temp_file_or_dir)){
$arrRX = array('#\.{2,4}$#', '#\.#');
$arrReplace = array("", "_");
$returnVal = preg_replace($arrRX, $arrReplace, $val);
$returnable[$returnVal] = $temp_file_or_dir;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return ($countOnly) ? count($returnable) : $returnable;
}
Use $_SERVER['DOCUMENT_ROOT'] to get your root directory.
$dir = $_SERVER['DOCUMENT_ROOT'].'/uploads/';

Warning with, fopen, feof and fgetcsv

I'm in trouble, I am failing to understand why this error is happening.
So when I only run this code,
function getClientProject($cliente)
{
$file = fopen("Projetos.csv","r");
$ArrayCount = 0;
$bool = false;
while(! feof($file))
{
$data = fgetcsv($file);
if($data[0] != '')
{
if(substr_compare($data[0],$cliente, 0, 3) == 0)
{
if($ArrayCount > 0)
{
$total = count($OpenProject);
for($i=0;$i<$total;$i++)
{
if($OpenProject[$i] == $data[0])
$bool = true;
}
if($bool == false)
{
$OpenProject[$ArrayCount] = $data[0];
$ArrayCount++;
}
}else
{
$OpenProject[$ArrayCount] = $data[0];
$ArrayCount++;
}
}
}
}
fclose($file);
return $OpenProject;
}
It works and returns the Array. But when I call the function this way,
include_once 'CRM files/TSread.php';
$arrayC = getClientProject('SLA');
var_dump($arrayC);
No longer works and me these errors,
What am I doing wrong?
path, the file i'm using is "Projeto.php":
and my CRM files folder:
You are opening the file using a relative path. You assume that Projetos.csv is always in the same directory as the TSread.php file. Although, when including it, you seem to be in a higher directory (outside of the CRM files directory), therefor PHP can no longer find your CSV file, since it's trying to open it relative to the upper directory now.
You could pass the full path to your getClientProject method to avoid this. So, you would get something like:
$arrayC = getClientProject('SLA', __DIR__ . '/CRM files/Projectos.csv');
Obviously, you will need to change your function a little to work with this new constructor, so it should like something like this:
function getClientProject($cliente, $csv) {
$file = fopen($csv, "r");
// Followed by the rest of your function

Return file directories in an array

I`m trying to create a function that reads a directory and returns all file's working directories in an array, but it is not working. I don`t know why the code doesn`t work, can you help me?
$postsDirectory = "../posts/";
function listFiles() {
$results = array();
$handler = opendir($postsDirectory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[] = getcwd($file);
}
}
closedir($handler);
return $results;
}
getcwd() returns the working directory for the script that is being executed. It doesn't take any parameters, and it has nothing to do with other files on the file system (nor does the idea of a "working directory" make sense for an arbitrary file). I assume that what you actually want is a list of all directories within a given directory.
I would use a RecursiveDirectoryIterator for this:
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($postsDirectory),
FilesystemIterator::SKIP_DOTS
);
$results = array();
while($it->valid()) {
if($it->isDir()) {
$results[] = $it->getSubPath();
}
$it->next();
}

Create a temp file with a specific extension using php

How do I create a temporary file with a specified extension in php.
I came across tempnam() but using it the extension can't be specified.
Easiest way i have found is to create tempfile and then just rename it. For example:
$tmpfname = tempnam(sys_get_temp_dir(), "Pre_");
rename($tmpfname, $tmpfname .= '.pdf');
my way is using tempnam
$file = tempnam(sys_get_temp_dir(), 'prefix');
file_put_contents($file.'.extension', $data);
{
//use your file
}
unlink($file);//to delete an empty file that tempnam creates
unlink($file.'.extension');//to delete your file
This might simulate mkstemp() (see http://linux.die.net/man/3/mkstemp) a bit, achieving what you want to do:
function mkstemp( $template ) {
$attempts = 238328; // 62 x 62 x 62
$letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$length = strlen($letters) - 1;
if( mb_strlen($template) < 6 || !strstr($template, 'XXXXXX') )
return FALSE;
for( $count = 0; $count < $attempts; ++$count) {
$random = "";
for($p = 0; $p < 6; $p++) {
$random .= $letters[mt_rand(0, $length)];
}
$randomFile = str_replace("XXXXXX", $random, $template);
if( !($fd = #fopen($randomFile, "x+")) )
continue;
return $fd;
}
return FALSE;
}
So you could do:
if( ($f = mkstemp("test-XXXXXX.txt")) ) {
fwrite($f, "test\n");
fclose($f);
}
Let's say tempnam() gives you a file of "filename". You move it to "filename.ext". At any point, tempnam() can give you "filename" again. If you check for "filename.ext", reject the filename given by tempnam(), and call it again, you still end up with the possibility that between one step and another, a file will get created with the same name. (This is discussed in the user comments on the documentation page for tempnam(): https://www.php.net/manual/en/function.tempnam.php.)
However, if you just leave the file created by tempnam() alone (not deleting "filename" until you delete "filename.ext") and work with that filename + the extension, then there is no chance that tempnam() will use that filename again (as far as I can see). Yes, it is messy to have "filename" and "filename.ext" for every single file. On the other hand, it solves the problem.
public static function makeTempFileInFolder($prefix, $suffix, $folder="")
{
if (strlen($folder)==0) $folder = sys_get_temp_dir();
do {
$file = $folder."/".$prefix.rand(1,99999).time().$suffix;
} while (file_exists($file));
return $file;
}
The same as tempnam() except the additional parameter:
function tempnamp($dir, $prefix, $postfix) {
$maxAttempts = 1000;
// Trim trailing slashes from $dir.
$dir = rtrim($dir, DIRECTORY_SEPARATOR);
// If we don't have permission to create a directory, fail, otherwise we will
// be stuck in an endless loop.
if (!is_dir($dir) || !is_writable($dir)) return false;
// Make sure characters in prefix and postfix are safe.
if (strpbrk($prefix, '\\/:*?"<>|') !== false) return false;
if (strpbrk($postfix, '\\/:*?"<>|') !== false) return false;
// Attempt to create a random file until it works.
$attempts = 0;
do
{
$path = $dir.DIRECTORY_SEPARATOR.$prefix.mt_rand(100000, mt_getrandmax()).$postfix;
$fp = #fopen($path, 'x+');
} while (!$fp && $attempts++ < $maxAttempts);
if ($fp) fclose($fp);
return $path;
}
That 'p' at the end of the name stands for 'postfix'.
I prefer this solution:
$uid = uniqid('', true);
$path = sys_get_temp_dir() . "some_prefix_$uid.myextension";
Note: I do not put the prefix in uniqid because, IMHO, it's not its duty
Maybe using
move_uploaded_file($tmp_name, "$uploads_dir/$name.myextension");
See http://php.net/manual/en/function.move-uploaded-file.php#example-2209
Rename does it, find the extension with pathinfo and then replace with the extension you want.
$tmpfname = tempnam(sys_get_temp_dir(), 'FOO');
$newname = str_replace(pathinfo($tmpfname, PATHINFO_EXTENSION),'pdf',$tmpfname);
rename($tmpfname, $newname);
//do what you want with $newname
unlink($newname);

Scan files in a directory and sub-directory and store their path in array using php

I want not scan all the files in a directory and its sub-directory. And get their path in an array. Like path to the file in the directory in array will be just
path -> text.txt
while the path to a file in sub-directory will be
somedirectory/text.txt
I am able to scan single directory, but it returns all the files and sub-directories without any ways to differentiate.
if ($handle = opendir('fonts/')) {
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry<br/>";
}
closedir($handle);
}
What is the best way to get all the files in the directory and sub-directory with its path?
Using the DirectoryIterator from SPL is probably the best way to do it:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach ($it as $file) echo $file."\n";
$file is an SPLFileInfo-object. Its __toString() method will give you the filename, but there are several other methods that are useful as well!
For more information see: http://www.php.net/manual/en/class.recursivedirectoryiterator.php
Use is_file() and is_dir():
function getDirContents($dir)
{
$handle = opendir($dir);
if ( !$handle ) return array();
$contents = array();
while ( $entry = readdir($handle) )
{
if ( $entry=='.' || $entry=='..' ) continue;
$entry = $dir.DIRECTORY_SEPARATOR.$entry;
if ( is_file($entry) )
{
$contents[] = $entry;
}
else if ( is_dir($entry) )
{
$contents = array_merge($contents, getDirContents($entry));
}
}
closedir($handle);
return $contents;
}

Categories