How to fix PHP Warning: file_get_contents? - php

I'm getting following warning:
Warning: file_get_contents(C:\xampp\htdocs\test/wp-content/themes/test\images) [function.file-get-contents]: failed to open stream: Permission denied in ..\plugins\theme-check\main.php on line 29
The line 29 of main.php reads as:
$other[$filename] = file_get_contents( $filename );
Here is code related to $files:
$files = listdir( $theme );
$files = array_merge( listdir( $parent ), $files );
if ( $files ) {
foreach( $files as $key => $filename ) {
if ( substr( $filename, -4 ) == '.php' ) {
$php[$filename] = php_strip_whitespace( $filename );
}
else if ( substr( $filename, -4 ) == '.css' ) {
$css[$filename] = file_get_contents( $filename );
}
else {
$other[$filename] = file_get_contents( $filename );
}
}
// run the checks
$failed = !run_themechecks($php, $css, $other);
As far I have understood, its the permission error. As the file can't seem to access that folder. I'm using XAMPP on Windows 7. I dont know how can i change the folder permissions on windows.
PS. Please notice the folder path in the warning, it has \ and also /.
I don't want to turn off the Warning etc., instead want to fix the warning.

Marc B hit it on the head. You need to add a test to check if the filename is a directory with php function is_dir($filename)
if ( $files ) {
foreach( $files as $key => $filename ) {
if ( substr( $filename, -4 ) == '.php' ) {
$php[$filename] = php_strip_whitespace( $filename );
}
else if ( substr( $filename, -4 ) == '.css' ) {
$css[$filename] = file_get_contents( $filename );
}
else {
if(!is_dir($filename)) $other[$filename] = file_get_contents( $filename );
}
}
Edit
If you are doing something like a directory view online. You could go further and include the directories in a seperate array and sort them and list them out first. and then list the files. I have created something like this for a dynamic gallery.

Try using this PHP function to replace the windows path: getcwd().
You will need to concatenate the file names.

Related

How do i update a CSV file with data from external CSV file link using PHP?

I need help with my PHP code.
We have an e-commerce site made with wordpress and woocommerce.
The site needs to import products from another site's CSV-file through a datafeed.
The datafeed setup requires a PHP-file in the website's file system
and a Cron Job that executes the PHP-file.
The PHP-file takes the data from
5dkmiglm.csv (cdn.sandberg.world)
and appends it to
pricelist_206876.csv (in our system)
These two CSV files differ in number of columns.
5dkmiglm.csv has these columns that should be imported to our pricelist:
Partno
Name
Weight
Width
Height
SE:retailPriceIncVat
sv:CategoryName
The PHP-code looks like this:
`<?php
$current = file_get_contents("https://cdn.sandberg.world/feeds/5dkmiglm.csv");
$pricefile = "/pricelist_206876.csv";
file_put_contents($pricefile,$current);
?>`
I placed the PHP-file in the same folder as the pricelist that needs to be updated
but nothing happens. pricelist_206876 is not updated as it should be.
The Cron Job is not in the wp-admin panel, but in the control panel (DirectAdmin) of our web host Inleed.
The Cron Job command looks like this:
/usr/bin/php -q /dev/null "/home/goffero/domains/goffero.com/datafeedcode.php"
I tried modifying the PHP code in various ways with no result.
realpath() didn't work.
I changed the write/read/execute system permissions for the files but that didn't solve the problem.
I have a project in Magento and the import of the products is done the same way you want.
We take a csv with 10 or more columns but we export only qty and SKU in this case.
Here is what we have done:
<?php
// downloaded file path
$filesRoot = BP . '/pub/path/to/your/folder/';
// If folder doesn't exist, create it
if ( ! file_exists( $filesRoot ) ) {
mkdir( $filesRoot, 0777, true );
}
// their file
$fileIn = $filesRoot . '5dkmiglm.csv';
// your file
$fileOut = $filesRoot . 'pricelist_206876.csv';
$url = 'https://cdn.sandberg.world/feeds/5dkmiglm.csv';
// Download their csv in your environment
if ( ! file_put_contents( $fileIn, file_get_contents( $url ) ) ) {
die( 'error download file' );
}
$countLine = 0;
$fileInOpn = fopen( $fileIn, 'r' );
$fileOutOpn = fopen( $fileOut, 'w' );
while ( ( $line = fgetcsv( $fileInOpn ) ) !== false ) {
// position of each column
if ( $countLine == 0 ) {
$keyQty = array_search( 'qty', $line );
$keySku = array_search( 'sku', $line );
}
$newLineRev = array();
foreach ( $line as $key => $el ) {
if ( $key == $keyQty || $key == $keySku ) {
$newLineRev[ $keyQty ] = $line[ $keyQty ];
$newLineRev[ $keySku ] = $line[ $keySku ];
continue;
}
}
// Write in your file
fputcsv( $fileOutOpn, $newLineRev );
$countLine++;
}
fclose( $fileInOpn );
fclose( $fileOutOpn );

How do I edit multiple .txt files with different names in a folder?

I have a folder that contains several .txt files called :
A500_1.txt
A500_2.txt
A700_1.txt
A700_2.txt
A900_1.txt
...
In each of the .txt files there is :
PRXC1_|TB|CCAAO9-RC|9353970324463|24.99
PRXC1_|TB|CFEXK4-RC|9353970294766|84.99
PRXC1_|TB|CFEXK4-RC|9353970294773|84.99
...
I'd like you to :
if the filename starts with A500_ replace "TB" with "MD"
if the filename starts with A700_ replace "TB" by "JB"
if the filename senter code heretarts with A900_ replace "TB" with "LD"
I wrote this function but it just creates me an empty A500_2.TXT file at the root of the project and displays :
Warning: file_get_contents(A500_2.TXT): failed to open stream:
Where's my error?
<?php
function processFile( $path ) {
$dir = './test/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
$filename = basename( $file );
if ( ! in_array($file,array(".","..")))
{
//read the entire string
$str = file_get_contents( $file );
// var_dump($str);
// replace something in the file string
if ( strpos( $filename, 'A500_' ) === 0 ) {
$str = str_replace( 'TB', 'MD', $str );
} else if ( strpos( $filename, 'A700_' ) === 0 ) {
$str = str_replace( 'TB', 'JB', $str );
} else if ( strpos( $filename, 'A900_' ) === 0 ) {
$str = str_replace( 'TB', 'LD', $str );
} else {
// Return false if we don't know what to do with this file
return false;
}
//write the entire string
$writeResult = file_put_contents( $file, $str );
//return true after a file is written successfully, or false on failure
return $writeResult >= 0;
}
}
}
if(processFile( './test/' )) echo "good!";
?>
Both the file_get_contents warning and the blank file being created are down to the same problem - scandir returns just the filename, not a relative path to the currently running script.
I'd guess that you're expecting it to return relative paths, which is why you're calling basename at the top of your loop. As it is, your $file and $filename arguments are going to always be set to the same thing.
The quickest solution will be to prepend $file with the scanned directory name before processing anything else:
$file = $dir . $file;
This should fix both the read and write calls.

Exploring a file structure using php using scandir()

I am new to php and trying to learn how to navigate a local file structure in for the format:
-Folder
-SubFolder
-SubSubFolder
-SubSubFolder
-SubFolder
-SubSubFolder
...
From another stackoverflow question I have been able to use this code using scandir():
<?php
$scan = scandir('Folder');
foreach($scan as $file)
{
if (!is_dir($file))
{
$str = "Folder/".$file;
echo $str;
}
}
?>
This allows me to generate a list of strings of all the 'SubFolder' in my folder directory.
What I am trying to do is list all the 'SubSubFolder' in each 'SubFolder', so that I can create a string of the 'SubSubFolder' name in combination with its 'SubFolder' parent and add it to an array.
<?php
$scan = scandir('Folder');
foreach($scan as $file)
{
if (!is_dir($file))
{
$str = "Folder/".$file;
//echo $str;
$scan2 = scandir($str);
foreach($scan2 as $file){
if (!is_dir($file))
{
echo "Folder/SubFolder/".$file;
}
}
}
}
?>
This however isn't working, and I wasn't sure if it was because I cannot do consecutive scandir() or if I cannot use $file again.
There is probably a better solution, but hopefully the following will be of some help.
<?php
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces -$file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
//To list folders names only and not the files within comment out the following line.
echo "$spaces $file<br />.";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
getDirectory( "folder" );
// Get the current directory
?>

problem with folder handling with php

Friends,
I have a problem............
Help me please........
Am getting the image url from my client, i want to store those images in my local folder.
if those images are in less, i will save them manually
But they are greater than 5000 images.........
Please give some code to down load all the images with PHP
you could try file_get_contents for this. just loop over the array of files and use file_get_contents('url'); to retrieve the files into a string and then file_put_contents('new file name'); to write the files again.
You may download file using file_get_contents() PHP function, and then write it on your local computer, for example, with fwrite() function.
The only opened question is, where to get list of files supposed to be downloaded - you did not specify it in your question.
Code draft:
$filesList = // obtain URLs list somehow
$targetDir = // specify target dir
foreach ($filesList: $fileUrl) {
$urlParts = explode("/", $fileUrl);
$name = $urlParts[count($urlParts - 1)];
$contents = file_get_contents($fileUrl);
$handle = fopen($targetDir.$filename, 'a');
fwrite($handle, $contents);
fclose($handle);
}
I'm not sure that this is what you want. Given a folder's (where PHP has the authority to get the folder's contents) URL and a URL you want to write to, this will copy all of the files:
function copyFilesLocally( $source, $target_folder, $index = 5000 )
{
copyFiles( glob( $source ), $target_folder, $index );
}
function copyFiles( array $files, $target_folder, $index )
{
if( count( $files ) > $index )
{
foreach( $files as $file )
{
copy( $file, $target_folder . filename( $file ) );
}
}
}
If you're looking to a remote server, try this:
function copyRemoteFiles( $directory, $target_folder, $exclutionFunction, $index = 5000)
{
$dom = new DOMDocument();
$dom->loadHTML( file_get_contents( $directory ) );
// This is a list of all links which is what is served up by Apache
// when listing a directory without an index.
$list = $dom->getElementsByTagName( "a" );
$images = array();
foreach( $list as $item )
{
$curr = $item->attributes->getNamedItem( "href" )->nodeValue;
if( $exclutionFunction( $curr ) )
$images[] = "$directory/$curr";
}
copyFiles( $images, $target_folder, $index );
}
function exclude_non_dots( $curr )
{
return strpos( $curr, "." ) != FALSE;
}
copyRemoteFiles( "http://example.com", "/var/www/images", "exclude_non_dots" );

PHP delete the contents of a directory

How do I do that? Is there any method provided by kohana 3?
To delete a directory and all this content, you'll have to write some recursive deletion function -- or use one that already exists.
You can find some examples in the user's notes on the documentation page of rmdir ; for instance, here's the one proposed by bcairns in august 2009 (quoting) :
<?php
// ensure $dir ends with a slash
function delTree($dir) {
$files = glob( $dir . '*', GLOB_MARK );
foreach( $files as $file ){
if( substr( $file, -1 ) == '/' )
delTree( $file );
else
unlink( $file );
}
rmdir( $dir );
}
?>
I suggest this way, simple and direct.
$files = glob('your/folder/' . '*', GLOB_MARK);
foreach($files as $file)
{
if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
have you tried unlink in the directory ?
chdir("file");
foreach (glob("N*") as $filename )
{
unlink($filename);
}
This deletes filenames starting from N
I'm not sure about Kohana 3, but I'd use a DirectoryIterator() and unlink() in conjunction.
The solution of Pascal does not work on all OS. Therefor I have created another solution. The code is part of a static class library and is static.
It deletes all files and directories in a given parent directory.
The function is recursive for the subdirectories and has an option not to delete the parent directory ($keepFirst).
If the parent directory does not exist or is not a directory 'null' is returned. In case of a successful deletion 'true' is returned.
/**
* Deletes all files in the given directory, also the subdirectories.
* #param string $dir Name of the directory
* #param boolean $keepFirst [Optional] indicator for first directory.
* #return null | true
*/
public static function deltree( $dir, $keepFirst = false ) {
// First check if it is a directory.
if (! is_dir( $dir ) ) {
return null;
}
if ($handle = opendir( $dir ) ) {
while (false !== ( $fileName = readdir($handle) ) ) {
// Skips the hidden directory files.
if ($fileName == "." || $fileName == "..") {
continue;
}
$dpFile = sprintf( "%s/%s", $dir, $fileName );
if (is_dir( $dpFile ) ) {
self::deltree( $dpFile );
} else {
unlink( $dpFile );
}
} // while
// Directory removal, optional not the parent directory.
if (! $keepFirst ) {
rmdir( $dir );
}
} // if
return true;
} // deltree

Categories