Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I've searched around google for a way to fopen and read a file with an unknown/random name in a specific folder with a specific extension (it will be the only file in that folder, but it gets updated every hour with a new name), but couldn't find anything. Previously the file had the same name every time unfortunately now it changes...
previously i had to only define it this way:
$file = "/var/uploads/quarter.csv";
$handle = #fopen($file, "r");
but with a random name it doesn't work anymore.
so, I've tried:
function the_file($dir = '/var/uploads/') {
$files = glob($dir . '/*.csv');
$file = $files;
}
$handle = #fopen($file, "r");
script continues...
but it doesn't work. Any help would be appreciated, thanks.
The $file variable doesn't exist outside the function scope and hence you won't be able to use it outside the function. Also, glob() returns an array -- if there is only one file, you can just get the first element of the array and return it, like so:
function the_file($dir = '/var/uploads/') {
$files = glob($dir . '/*.csv');
return $files[0]; // return the first filename
}
Now to store it in a variable, you can do:
$file = the_file(); // or specify a directory
# code ...
A possible solution can be:
If there is only one file in the directory, you can do a scandir to get the contents of the folder. (see PHP ref.)
$dir = 'your_folder_name';
$files1 = scandir($dir);
The content of the $files will be:
Array
(
[0] => .
[1] => ..
[2] => yourfile.csv
)
So you can get the full name of the file with:
$filename = $files1[2];
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I would like to show a list of all subdirectories in the directory on the UI Interface using php .The directories will show up as a button and the user can select which directory.
Here is my code so far
$path = /path;
$dir = glob($path.'/*/,GLOB_ONLYDIR);
Please how do I go about this? Any hint will be appreciated.
Use foreach to loop through the results of glob function. Example:
$path = '/';
$dirs = glob($path.'*', GLOB_ONLYDIR);
foreach($dirs as $dir) {
echo ''.$dir.'<br>';
}
You can start by looping the array and printing each directory:
foreach ($dir as $item) {
echo $item;
}
Depending on how you want to add that to your UI, you can dress that up with a button code:
echo "<button>$item</button>";
Then you could add some javascript to add an action to whatever should happen when the user clicks that button.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a problem while trying to open a file and display its contents using php
My file called hello.txt
Here is my PHP code
<?php
$filename = 'hello.txt';
$filePath = 'c:\\Users\\bheng\\Desktop\\'.$filename;
if(file_exists($filePath)) {
echo "File Found.";
$handle = fopen($filePath, "rb");
$fileContents = fread($handle, filesize($filePath));
fclose($handle);
if(!empty($fileContents)) {
echo "<pre>".$fileContents."</pre>";
}
}
else {
echo "File Not Found.";
}
?>
I got this from
http://php.net/manual/en/function.fread.php
I keep getting error:
fread(): Length parameter must be greater than 0
Can someone help me please?
Although there are good answers here about using file_get_contents() instead, I'll try to explain wht this is not actually working, and how to make it work without changing the method.
filesize() function uses cache. You probably executed this code while still having the file empty.
Use the clearstatcache function each time the file change, or before testing its size :
clearstatcache();
$fileContents = fread($handle, filesize($filePath));
Also obviously make sure that your file is not empty ! Test it :
clearstatcache();
if(file_exists($filePath) && filesize($filePath)) {
// code
}
It needn't be that hard, and it certainly doesn't require you to read a file in binary mode:
if (file_exists($filePath))//call realpath on $filePath BTW
{
echo '<pre>', file_get_contents($filePath), '</pre>';
}
All in all, you really don't want to be doing this kind of stuff too much, though
If you need to read the entire file's content, there is a shortcut function
http://php.net/manual/en/function.file-get-contents.php
So you don't need to bother creating a file handler and closing it afterwards.
$fileContents = file_get_contents($filePath);
using file_get_contents method of php
echo file_get_contents("text.txt");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using a script to back up files from ftp. code is below.
include "recurseZip.php";
//Source file or directory to be compressed.
$src='source/images/black.png';
//Destination folder where we create Zip file.
$dst='backup';
$z=new recurseZip();
echo $z->compress($src,$dst);
Now I want to get values to $src from source/files.txt which contains a list of file names.
My .txt file:
index.php.bk-2013-12-02
index.php.bk-2013-12-07
index.php.bk-2013-12-10
index.php.bk-2013-12-20
index.php.bk-2013-12-26
function.php.bk-2013-12-20
function.php.bk-2013-12-23
contact.php.bk-2013-12-23
contact.php.bk-2013-12-30
my source/files.txt contains 10 file names those need to be assigned as values to the variable $src I am using this script http://ramui.com/articles/php-zip-files-and-directory.html
how can I do that.?
any help will be very much appreciated.
Thanks.
Okay, you want to get the file name from each line of the .txt file.
<?php
$myFile = "files.txt";
$lines = file($myFile);
foreach($lines as $line){
$file = basename($line);
echo $file;
}
?>
Answer to your old question variant
You can use the basename() function. The manual says, "given a string containing the path to a file or directory, this function will return the trailing name component".
Now, you said "I want to get file name to $src from source/files.txt", so assuming from this, you are looking to get the file name i.e. black.png. This could be achieved using the basename() function as mentioned before.
<?php
$src='source/images/black.png';
$file = basename($src);
echo $file;
?>
Output
black.png
http://ideone.com/p2b4sr
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I got a problem with my code. It's returning false. I have searched and tried some similar questions here but none of them helped. anyway, im using cPanel here. and i'm sure that the file really exists and so with the folder names. Hope you can help me with this. thanks in advance.
<?php
$filename = 'event-01.jpg';
if ( file_exists( $_SERVER{'/home2/user/public_html'} . "/MyProject/events/event-01.jpg")) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
i have also tried
$filename = 'event-01';
if (!file_exists('http://mysite.com/MyProject/events/event-01.jpg')) {
echo "The file $filename doesn't exist";
}
Problem
To put it bluntly; this...
file_exists( $_SERVER{'/home2/user/public_html'} . "/MyProject/events/event-01.jpg")
is not php.
Solution
Check a file exists
Assuming that the file path is actually:
/home2/user/public_html/MyProject/events/event-01.jpg
Then you should just be using that in file_exists:
file_exists("/home2/user/public_html/MyProject/events/event-01.jpg")
Server root
I assume that what you actually meant to do was:
file_exists($_SERVER['DOCUMENT_ROOT']."/MyProject/events/event-01.jpg")
You might also like to try to var_dump($_SERVER) to see all of the information that it stores.
References
file_exists: http://php.net/file_exists
$_SERVER: http://php.net/manual/en/reserved.variables.server.php
In PHP, $_SERVER is a superglobal containing various server related information and unrelated to what you're trying to achieve.
Simply try this instead:
if (file_exists("/home2/user/public_html/MyProject/events/event-01.jpg")) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to run 600 XML files through a script I've made that extracts specific pieces of information and saves each one in JSON format. All 600 XML files are inside a folder ready to be run through the PHP file, I'm now looking for a fast way to do it.
Essentially this is the process the PHP file goes through:
PHP reads single XML file via URL -> locally saves important info in variables -> saves important info into JSON file
Is there a way I can somehow run all 600 XML files through my PHP file?
Thanks
Open the directory containing the XML files and then process them, here are some of the most common way todo that.
opendir()
<?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);
}
}
?>
You can also use glob()
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Inside the foreach loop of whichever you choose you can use file_get_contents() or fread() then you can do your conversion to json.
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Hope it helps
Just go ahead and try! You'll probably run into a timeout error. If you do, try configuring the max timeout settings. http://php.net/manual/en/function.set-time-limit.php
Joel,
Sounds to me like what you need to is to use readdir
http://php.net/manual/en/function.readdir.php
This will allow you to get a list of files in a directory to iterate over.
$dir = opendir('/path/to/files');
while($file = readdir($dir)) {
if ($file !== '.' && $file !== '..' && !is_dir($file)) {
$parthParts = pathinfo($file);
if ($pathParts['extension'] === 'xml') {
runscripton($file);
}
}
}
closedir($dir);
First, write a function that gets an XML file name, and after processing, returns the results in php array or JSON (Based on how you need your code to be).
To write this function, you need to parse XML (http://php.net/manual/en/book.xml.php).
To work with JSON in PHP: http://php.net/manual/en/book.json.php
Then, write your main code. Your main code should enumerate all XML files in the folder, and then call your function for each file, and gather/generate JSON using information returned by the function.
You might need readdir to gather all of XML files in the folder. (http://php.net/manual/en/book.xml.php)
Don't forget to increase time limit as long as there are lots of XML files and the process might take long so a timeout error would occur. (http://php.net/manual/en/function.set-time-limit.php)