Selecting a file from a directory randomly and then display it - php

I have a directory which contains several text files. What I'm trying to do is to randomly select one of the files and then display it. Here's what i got so far, but i still haven't managed to get it working. Any idea's? Thanks.
<?php
function random_pic($dir = 'wp-content\files')
{
$files = opendir($dir . '/*.txt');
$file = array_rand($files);
return $files[$file];
}
while(!feof($file)) {
echo fgets($file) . "<br />";
}
fclose($file);
?>

scandir will put all elements in the directory into an array. Then use array_rand to choose a random element from the array.
$dir = "/path/to/pictures/";
$dirarray = scandir( $dir );
unset($dirarray [0]);
unset($dirarray [1]);
$content = file_get_contents( $dir . $dirarray[array_rand($dirarray )] );
echo $content;
The unset commands are to remove . and .. from the array.
This would for example result in echoing picturename.jpg.

You have wrong slash in your directory.
$dir = 'wp-content\files'
should be
$dir = 'wp-content/files'
It should be forward slash not back slash. Also check permission of the directory that you are accessing.

Try this:-
Use glob function to get all files in a directory, and then take a random element from that array and return it. Then read the file and echo its content.
function get_random_file($dir = 'folder_name')
{
$files = glob($dir . '/*.txt');
$file = array_rand($files);
return $files[$file];
}
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

use function name with parameters in while loop condition and check function returning a file name or not. Check the following link for detail http://php.net/manual/en/function.readdir.php

Related

fopen and fwrite inside for loop

for($i=0;$i<$directoriesCount;$i++)
{
$fileName=$Config['path']['basePath']."language/".$directories[$i]."/"."commontest.conf";
$file = fopen($fileName,"a");
$data = "testcontent";
fwrite($file,"\n");
fwrite($file,$data);
fclose($file);
}
the $directories variable will have array values:
en_lang
fr_lang
it_lang, etc.,
in the every directory we should find the commongtest.conf file to write the content.
In my test file its writes only the first values of array for ex 1. en_lang folder file only get fwrite other files not affected.
You have an extra double quote here:
."/".commontest.conf"
should be:
."/.commontest.conf"
A foreach statement might work better here for you:
foreach($directories as $directory){
$fileName=$Config['path']['basePath']."language/".$directory."/.commontest.conf";
$file = fopen($fileName,"a");
$data = "testcontent"."\n";
fwrite($file,$data);
fclose($file);
}
This code is working for me.
I think using file_put_contents would be even better.
foreach($directories as $directory){
$fileName=$Config['path']['basePath']."language/".$directory."/.commontest.conf";
$data = "testcontent"."\n";
file_put_contents($fileName,$data);
}

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

Getting Error on fopen in PHP

I'm writing a simple text editor for a template, and I've gotten the opening, displaying, and editing part handled. Every time I try to save it though, it keeps giving me an error on the fopen() function.
I'm getting the files with this:
$dir = "./uploads/post-templates";
$files = scandir($dir);
while($files[0] == "." || $files[0] == "..") {
array_shift($files);
}
Then a simple loop handles displaying filenames in a select menu:
<?php foreach($files as $f) { echo "<option name='file' value=" . $f . " class='file'>" . $f . "</option>";}; ?>
Lastly it is all appended into the textarea using a short jQuery function. Alas, when it comes to executing the script to save the file, I get an error every single time. I've tried using relatives, absolutes, and http for the directory, and the filename and path are echoing properly each time.
///different file!!!!
$f = $_POST['file'];
$c = $_POST['content'];
$dir = "./uploads/post-templates/";
$file = $dir . $f;
echo $file;
$fo = fopen($file, "w") or die("opening error");
fwrite($fo, $c) or die("writing error");
fclose($f);
NOTE: For testing purposes only.
I wrote a test script and it was successful.
With the values that you have Mike, try using my script below with your present incoming values.
Plus this line gave me an error from your original code: fclose($f);
Error: when using fclose($f);
Warning: fclose() expects parameter 1 to be resource, string given in...
It should read as fclose($fo);
TEST CODE:
<?php
$f = "thefile.txt";
$c = "the content";
$dir = "./test/";
$file = $dir . "/" . $f;
echo $file; // echos the file name at this point
$fo = fopen($file, "w") or die("opening error");
fwrite($fo, $c) or die("writing error");
fclose($fo);
// shows the contents of the written file on screen
$contents = file_get_contents($file);
echo $contents;
?>

Parsing and Writing Files in PHP

I'm attempting to open a directory full of text files, and then read each file line-by-line, writing the information in each line to a new file. Within each text file in the directory I'm trying to iterate, the information is formed like:
JunkInfo/UserName_ID_Date_Location.Type
So I want to open every one of those text files and write a line to my new file in the form of:
UserName,ID,Date,Location,Type
Here's the code I've come up with so far:
<?php
$my_file = 'info.txt';
$writeFile = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$files = scandir('/../DirectoryToScan');
foreach($files as $file)
{
$handle = #fopen($file, "r");
if ($handle)
{
while (($buffer = fgets($handle, 4096)) !== false)
{
$data = explode("_", $buffer);
$username = explode("/", $data[0])[1];
$location = explode(".", $data[3])[0];
$type = explode(".", $data[3])[1];
$stringToWrite = $username . "," . $data[1] . "," . $data[2] . "," . $location . "," . $type;
fwrite($writeFile, $stringToWrite);
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
}
fclose($writeFile);
?>
So my problem is, this doesn't seem to work. I just never get anything happening -- the output file is never written and I'm not sure why.
There is one potential issue with the scandir() line:
$files = scandir('/../DirectoryToScan');
The path begins with a /, which means that it is looking in the root of the server. So, the directory it's trying to read is /DirectoryToScan. To fix it, you can just remove the leading /. Of course, this could be a sample path for this example and may not actually apply to reality, or maybe you really do have a directory in the root of your system named that - in these cases, feel free to ignore this bit =P.
The next thing is when you're using fopen() on the files you're iterating through. scandir() returns the name of the file, not the full path. You'll need to concat the directory name and the file each time:
$dir = '../DirectoryToScan/';
$files = scandir($dir);
foreach($files as $file) {
$handle = #fopen($dir . $file, "r");
I'm currently running an older version of PHP, so directly-accessing array indexes from return-functions, such as with explode("/", $data[0])[1], doesn't work for me (it was added in PHP 5.4).
Other than that, the rest of your code looks like it should work fine (minus any potential logic/data errors that I may have overlooked).

Define array of file locations, parse and replace. Where's my error?

I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.

Categories