Read a file with php on php hosting - php

I am trying to read a file (ex: pdf file) on php hosting.
My code:
$myarray = array();
$path = "/home/mywebsite.com/httpdocs";
$open = opendir($path);
while ($x = readdir($open)) {
if ($file != "." && $file != "..") {
$myarray[] = $file;
}
}
sort($myarray);
closedir($open);
echo json_encode($myarray);
This code is running but if I change the value of $path : "/home/mywebsite.com/mydirectory/" instead of "/home/mywebsite.com/httpdocs", this code does not run.
I want to store my documents in my directory. Any suggestions?

Related

PHP: Fastest way to get huge number of directories including subdirectories into db

How to get all directories including subdirectories separately and save in database in PHP? I am using MySQL and PHP 5.4 and nginx.
Right now I have the following function which uses readdir and does what I want just fine.
protected function getSubDirsRecursively($dir)
{
$result = array();
$dir = rtrim($dir, '\\/');
if (is_dir($dir)) {
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
$currentPath = $dir . DIRECTORY_SEPARATOR . $file;
if ($file !== '.' && $file !== '..' && is_dir($currentPath)) {
$result[] = $currentPath;
$result = array_merge($result, $this->getSubDirsRecursively($currentPath));
}
}
closedir($dh);
}
return $result;
}
However, the problem is when user has huge number of directories (e.g. 1m) and PHP execution time limit which he cannot change due to shared hosting.
Is it possible to do this with ajax requests and collect directories in portions?

PHP & HTML: Download file link not working

The following code lists all the files contained in a certain folder in my local machine, as you can see I'm echoing the file path inside the tag using the href attribute correctly.
So the problem is that when I click on the tag, it doesn't take me to the file download unless I copy the link and paste it to another tab of the browser, why is this happening? How can I fix it?
<h5>Attached Files</h5>
<?php
$date = $dateCreated->format('d-m-Y');
$thepath = public_path().'/uploads/binnacle/'.$date.'/'.$activity->activity_id;
$handle = opendir($thepath);
$x = 1;
while(($file = readdir($handle))!= FALSE) {
if($file != "." && $file != ".." && $file != "thumbs" && $file != "thumbs.db") {
echo $x.".- "."<a href='$thepath/$file' target='_blank'>$file</a><br>";
$x++;
}
}
closedir($handle);
?>
NOTE: This happens with all file types including images, excel files, text documents, etc.
SOLUTION BY #WereWolf - The Alpha:
<?php
$date = $dateCreated->format('d-m-Y');
$thepath = "/uploads/binnacle/".$date."/".$activity->activity_id;
$handle = opendir(public_path().$thepath);
$x = 1;
while(($file = readdir($handle))!= FALSE) {
if($file != "." && $file != ".." && $file != "thumbs" && $file != "thumbs.db")
{
echo $x.'.- '.''.$file.'<br>';
$x++;
}
}
closedir($handle);
?>
Make some changes:
// Remove the public_path()
$thepath = 'uploads/binnacle/'.$date.'/'.$activity->activity_id;
Then in the link:
"<a href='" . asset($thepath/$file) . "' target='_blank'>$file</a><br>";
Note: Laravel has a File component, You may use that, check it in the source.

Read and delete a text file in php

I am making a simple php script which just read a text file from server and delete it after showing on web.Script works well but it reads another file and delete another. It should delete the same file it reads. Any help please. Here is my code:
<?php
$mystr = '';
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$info = pathinfo($entry);
if ($info["extension"] == "txt") {
$mystr = $entry;
}
}
}
closedir($handle);
}
if (empty($mystr)) {
}else{
$contents = file_get_contents($mystr);
echo $contents;
unlink($mystr);
}
?>
Update
I dont know the file name, So in a loop I get the file name. I want to read any .txt file in the folder. This I read file one by one and at the same time delete it.
Your script is just this :
foreach(glob('/path/to/dir/*.txt') as $file)
{
readfile($file);
unlink($file);
}
See readfile() and glob() manual pages.

php readdir and is_dir

I am testing out the functions of directory handling. I have a fold/directory that contains the following:
0 File folder
false File folder
my_pictures File folder
MVI_3094 mov file
img01 jpeg image
etc...
I wrote the following code to traverse the directory and print out specific resutls
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($entry))
{
echo "Directory:$entry<br />";
}
}
My only problem is that the second "if" statement does not output the results of
echo "Directory:$entry<br />";
even though the entry is a directory. I have checked the entry manually with the "var_dump" function and it returns true as a directory.
Any suggestions would help
Try this and check. Just a try...
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
elseif(is_dir("files/".$entry))
{
echo "Directory:$entry<br />";
}
}
$entry is relative... is_dir expects an absolute path.
Try:
if(is_dir("files/".$entry))
readdir() is just returning the filenames. Your code is therefore looking for the files in the current directory rather than the subdirectory.
This will just probe the basename of whatever directory entry:
is_dir($entry)
The opendir() result list will be relative to the directory you gave for reading. So you need to use:
is_dir("files/$entry")
Your problem is that in elseif(is_dir($entry)) {, entry is equal to some string like "file.txt" or "somedirectory", which isn't a path pointing to a file at all. It needs to be "files/file.txt".
Try this:
$dir = "files/";
$handle = opendir($dir);
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($dir.$entry))
{
echo "Directory:$entry<br />";
}
}
Try using the DirectoryIterator:
$iterator = new \DirectoryIterator(realpath('files/'));
foreach($iterator as $file){
if($file->isDot())
continue;
if($file->isDir())
printf('Directory: %s <br/>', $file->getRealPath());
}

Display contents of multiple text files

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 />";
}

Categories