I'm having trouble with a foreach loop from a text file. I have a directory tree, and a list of these directories is in a text file, I want to check the tree against the list, and echo if any directories are missing.
The problem that I'm having is that I can't see an account for a new line, so if the file has 1 line, then it returns that it exists, but if the file has two line it returns the first as missing and the second as existing, even if it's the same entry twice in the file - see code below for clarification
<?php
$logFile = 'LogFile.txt';
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$verificationContents = file($verificationFile);
$fh = fopen($logFile,'a') or die("can't open file");
$new_line = "\r\n";
foreach($verificationContents as $directoryName) {
$subDirectory = $rootDirectory.$directoryName;
echo "$subDirectory <br />";
if (file_exists($subDirectory)) {
echo "$subDirectory Exists <br />";
} else {
echo "$subDirectory Does Not Exist <br />";
$libverificationfailed = 'failed';
fwrite($fh, "$subDirectory Not Found");
fwrite($fh, $new_line);
}
}
?>
So, as an example, the root directory has 2 sub directories, subdir1 and subdir2.
directoryverification.txt
subdir1
subdir2
and the page echos
C:\testdir\subdir1
C:\testdir\subdir1 Does Not Exist
C:\testdir\subdir2
C:\testdir\subdir2 Exists
So if there is a new line after the data in the text file, the code isn't reading it correctly. I'm hoping that this makes sense and that somebody can help.
regards,
Thanks rickdenhaan,
$subDirectory = rtrim($subDirectory);
Just before the if statement sorted it.
Try this
$rootDirectory = 'C:\testdir\\';
$verificationFile = 'verificationfiles/directoryverification.txt';
$file = new \SplFileObject($verificationFile, 'r');
$file->setFlags(\SplFileObject::SKIP_EMPTY);
while ( $dirname = $file->fgets() )
{
$dirname = $rootDirectory . trim($dirname);
if ( !file_exists($dirname) )
{
echo sprintf("direcrory %s does not exist\n", $dirname);
continue;
}
echo sprintf("direcrory %s exists\n", $dirname);
}
Related
I have a file on one application folder of codiginitor and I want to copy that file to another application folder of codignitor in another directory.
I have tried below code but it doesn't seem to be working:
$file = 'http://xxxxxx/jakson_solar/ftp.php';
$newfile = './mobile_image/transfer/';
if ( copy($file, $newfile) ) {
echo "Copy success!"; die;
}else{
echo "Copy failed."; die;
}
is there another way to copy file from one directory to another directory?
copy requires as first parameter an input file and as second parameter an output file
So do it this way
$file = 'path_to/ftp.php';
$newfile = './mobile_image/transfer/ftp.php';
if ( copy($file, $newfile) ) {
echo "Copy success!"; die;
} else {
echo "Copy failed."; die;
}
#dev please find the code below for your needs
// 1 check if your input from the form is not empty
if ((isset($_FILES['file']))){
// 2. files inside the session
$_SESSION['FILES'] = $_FILES;
// 3. your path
$PATH = $_SERVER["DOCUMENT_ROOT"]."/mobile_image/transfer/";
// 4. temporary name -> optional step but recommended
$TEMP_NAME = explode(".",$_FILES["file"]);
// 5. new name of the file
$NAME_NEW = substr(number_format(time() * rand(),0,'',''),0,20) . '.' .end($TEMP_NAME);
$UPLOAD_FILE = $PATH . basename($NAME_NEW);
// 6. check before moving the file that is not empty
if (isset($UPLOAD_FILE)) {
move_uploaded_file($_FILES['file'], $PATH); }
// 7. custom errors
$json = array();
$json['status'] = "OK";
$json['message'] = 'File moved successfully';
echo json_encode($json);
}else{
// 7. custom errors
$json = array();
$json['status'] = "NO FILE";
$json['message'] = 'No files found';
echo json_encode($json);
}
There are a directory full of random folders and inside all those folders is name.txt
Example: abcd/name.txt, 1234/name.txt, xyz/name.txt
<?php $users_input = "Jonathan"; ?>
I want to check if $users_input is equal to the contents of any random folder's name.txt and echo THAT folder's name.
Like (if $users_input is equal to contents of 1234/name.text) {echo folder's name which is 1234}
You can use a RecursiveDirectoryIterator to achieve this, as follows:
$users_input = 'Jonathan';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/target/path'));
foreach ($iterator as $file)
{
if ($file->isDir()) {
continue;
}
$path = $file->getPathname();
$contents = file_get_contents($path);
if (strcmp($contents,$users_input)) {
echo $path.'<br\>';
}
}
You may want to include an additional check on the file name if the folders can contain other files with a different name and or extension.
Here's how the solution will look like based on Barmar's suggestion:
<?php
$users_input = "Jonathan";
$file_arr = glob("*/name.txt");
foreach ($file_arr as $path) {
$content = file_get_contents($path);
if (trim($content) === $users_input) {
echo "dirname: " . dirname($path) . "\n";
}
}
Thanks everyone.
Concluded with
$users_input = "Jonathan";
$directory = glob("*");
foreach ($directory as $path) {
if (is_dir($path)) {
$myfile = fopen($path."/name.txt", "r") or die("Unable to open file!");
if (fread($myfile,filesize($path."/name.txt")) == $users_input) {echo $users_input . " is in " . $path;}
fclose($myfile);
}
}
I'm trying to copy multiple files from one domain on a web server to another using copy() and looping through a list of files, but it's only copying the last file on the list.
Here is the contents of files-list.txt:
/templates/template.php
/admin/admin.css
/admin/codeSnippets.php
/admin/editPage.php
/admin/index.php
/admin/functions.php
/admin/style.php
/admin/editPost.php
/admin/createPage.php
/admin/createPost.php
/admin/configuration.php
This script runs on the website that I'm trying to copy the files to. Here's the script:
$filesList = file_get_contents("http://copyfromhere.com/copythesefiles/files-list.txt");
$filesArray = explode("\n", $filesList);
foreach($filesArray as $file) {
$filename = trim('http://copyfromhere.com/copythesefiles' . $file);
$dest = "destFolder" . $file;
if(!#copy($filename, $dest))
{
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
} else {
echo "$filename copied to $dest from remote!<br/>";
}
}
I get the affirmative message for each and every file individually just as I should, but when I check the directory, only the last file from files-list.txt is there. I've tried changing the order, so I know the problem lies with the script, not any individual file.
The output from the echo statements looks something like this:
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPage.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/editPost.php from remote!
http://copyfromhere.com/copythesefiles/admin/admin.css copied to updates/admin/index.php from remote!
Etc
I've modified your code slightly, and tested it on my local dev server. The following seems to work:
$fileURL = 'http://copyfromhere.com/copythesefiles';
$filesArray = file("$fileURL/files-list.txt", FILE_IGNORE_NEW_LINES);
foreach ($filesArray as $file) {
$fileName = "$fileURL/$file";
$dest = str_replace($fileURL, 'destFolder', $fileName);
if (!copy($fileName, $dest)) {
$errors= error_get_last();
echo "COPY ERROR: ".$errors['type'];
echo "<br />\n".$errors['message'];
}
else {
echo "$fileName copied to $dest from remote!<br/>";
}
}
This uses the same fix that Mark B pointed out, but also consolidated the code a little.
Unless the data you're fetching from that remote site has leading/ in the path/filename, you're not generating proper paths:
$file = 'foo.txt'; // example only
$dest = "destFolder" . $file;
produces destFolderfoo.txt, and you end up littering your script's working directory with a bunch of wonky filenames. Perhaps you wanted
$dest = 'destFolder/' . $file;
^----note this
instead.
I'm trying to retrieve images for WP posts, which are held in a wp-uploads directory, using if (file_exists() but it's not recognising the file path.
For each post, there are up to 8 images available. Each image has the letters a-g at the end of the file name (or nothing), and has str_replace to replace certain characters in the file names.
I need to show each image if it exists, and if not, to return nothing. So if the post is associated with images with b, d and f at the end, it just shows those three.
I've tested without the (file_exists()) and its able to pick up the images with a simple echo for each - but it seems the $img paths aren't being recognised.
Im a bit of a php noob so any help would be appreciated...
$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
$imga = $root.$path."a.jpg";
$imgb = $root.$path."b.jpg";
$imgc = $root.$path."c.jpg";
$imgd = $root.$path."d.jpg";
$imge = $root.$path."e.jpg";
$imgf = $root.$path."f.jpg";
$imgg = $root.$path."g.jpg";
if (file_exists($img)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imga)) { echo "<img src='".$root.$path.".jpg' />"; } else { echo ""; }
if (file_exists($imgb)) { echo "<img src='".$root.$path."b.jpg' />"; } else { echo ""; }
if (file_exists($imgc)) { echo "<img src='".$root.$path."c.jpg' />"; } else { echo ""; }
if (file_exists($imgd)) { echo "<img src='".$root.$path."d.jpg' />"; } else { echo ""; }
if (file_exists($imge)) { echo "<img src='".$root.$path."e.jpg' />"; } else { echo ""; }
if (file_exists($imgf)) { echo "<img src='".$root.$path."f.jpg' />"; } else { echo ""; }
if (file_exists($imgg)) { echo "<img src='".$root.$path."g.jpg' />"; } else { echo ""; }`
You need to rearrange the way you are telling PHP to look up the address,
$root is probably not your absolute file path root (probably meaning absolutely) so instead use the special super variable for this, $_SERVER['DOCUMENT_ROOT'] which is the root of the web accessible filepath, therefore you then have:
$img = $_SERVER['DOCUMENT_ROOT'].$root.path.".jpg"
//while retaining your current / at the start of $root
This is the file structure to check if the file exists, not the file structure to reference in the <img> tag, that appears to be correct in your examples above.
So, your overall correction should look like this:
$root ="/wp-content/uploads/2016/Collection/";
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$img = $root.$path.".jpg";
...
if (file_exists($_SERVER['DOCUMENT_ROOT'].$img)){
....
}
An additional note is that the results of this function are cached so you should call clearstatcache() at the start of this file so that it can make fresh checks for if the images exist. Currently without this even if the image does exist, PHP will be using the cached - past- results which may not be up to date.
You start $root with a /, therefore it's starting from the server's root directory. Remove the first / and retry.
$uid = get_post_meta (get_the_ID(), 'Unique number', true);
$path = str_replace(" ","_",$uid);
$path = str_replace(".","_",$path);
$path = str_replace(":","",$path);
$uploads = wp_upload_dir();
Get base root directory.
$root = $uploads['path'];
$imgDir = $root.$path.".jpg";
if (file_exists($imgDir)){
.......
}
$f="../mts/sites/default/files/test.doc";//in this way i am able to find line count,but i am not getting how i can give folder path for line counting..if i give path as $safe_filename and $target_path.$safe_filename it's coming file content not opening. Please check the code and help me out thanks in advance
<?php
$nid = 1;
$teaser = false;
// Load node
$node = node_load(array('nid' => $nid));
// Prepare its output
if (node_hook($node, 'view')) {
node_invoke($node, 'view', $teaser, false);
}
else {
$node = node_prepare($node, $teaser);
}
// Allow modules to change content before viewing.
node_invoke_nodeapi($node, 'view', $teaser, false);
// Print
print $teaser ? $node->teaser : $node->body;
$target_path = "../mts/sites/default/files/ourfiles/";
//$myfile = basename( $_FILES['uploadedfile']['name']);
$safe_filename = preg_replace(
array("/\s+/", "/[^-\.\w]+/"),
array("_", ""),
trim($_FILES['uploadedfile']['name']));
$target_path = $target_path.$safe_filename;
if(file_exists($target_path))
{
echo "<script language=\"javascript\">";
echo "window.alert ('File already exist');";
echo "//--></script>";
}
elseif(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "<script language=\"javascript\">";
echo "window.alert ('File uploaded succesfully');";
echo "//--></script>";
/*
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
*/
}
$con = mysql_connect("localhost","mts","mts");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create table
mysql_select_db("mts", $con);
$f="../mts/sites/default/files/test.doc";//in this way i am able to find line count,but i am not getting how i can give folder path for line counting
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
echo "This file have ". $numWords . " lines";
mysql_query("INSERT INTO mt_upload (FileName,linecount, FilePath,DateTime)
VALUES ('".$safe_filename."','".$numWords."', '".$target_path.$safe_filename."',NOW())");
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
emphasized text
This is not a very safe way of doing things. If two users submitted files with the same filename, they would overwrite each other. This limits the user to a unique filename, which after a while of running a system becomes a problem. Not to mention that the user would be quite puzzled if he ever got such a message.
A much better solution is to generate your own filename for every file. You could make a long random string, or maybe take the mysql_insert_id() for the inserted record in mt_upload table. Then you would also not need to mess around with regexps, and the whole thing would be much simpler. In the mt_upload table you can keep the old filename if you want to show it to the user or something.
If that's the exact code, then the problem is that you call str_word_count() on $str but don't appear to set $str anywhere.
Function to count lines in all the files residing in a certain directory
function linecount_dir($dir) {
$ig = array('.','..');
$d = dir($dir);
while (false !== ($entry = $d->read())) {
if (!in_array($entry,$ig)) {
$total += linecount($d->path . "/$entry");
}
}
$d->close();
return $total;
}
Function to count lines
define(BLOCK_SIZE,131072);
function linecount($filename) {
$f = fopen($filename,'r');
while (!feof($f)) {
$d = fread($f,BLOCK_SIZE);
$rcount += substr_count($d, "\n");
$ncount += substr_count($d, "\r");
}
fclose($f);
return (($rcount >= $ncount) ? $rcount : $ncount);
}
Applied to your code
$f="../mts/sites/default/files/test.doc";//in this way i am able to find line count,but i am not getting how i can give folder path for line counting
// count words
$numWords = str_word_count($str)/11;
// count lines
$numLines = linecount($f);
echo "This file have ". $numWords . " words";
echo "This file have ". $numLines . " lines";
$f="../mts/sites/default/files/".$safe_filename;