I have a little problem with this code I have here. This code searches in a txt file and returnes what it has found.
Now what I want to do is change the file path with a $_GET method
But when I put in a $_GET method inside the "" it just says alot of errors such as "Your path cannot be empty"
What does not work:
$handle = #fopen(."$_GET['filepath']"., "r");
How I want it
$handle = #fopen("I/want/this/$_get/method", "r");
Full code
<?php
function find_value($input) {
// $input is the word being supplied by the user
$handle = #fopen("/users/edwin/list.txt", "r");
if ($handle) {
while (!feof($handle)) {
$entry_array = explode(":",fgets($handle));
if ($entry_array[0] == $input) {
return $entry_array[1];
}
}
fclose($handle);
}
return NULL;
}
?>
Thanks :)
Check the way you're handling your quotes.
$handle = #fopen($_GET['filepath'], "r");
Since it's a variable, it does not have to be encapsulated at all, unlike a string.
Related
I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php
I am trying to read the contents of a file line by line with Laravel.
However, I can't seem to find anything about it anywhere.
Should I use the fopen function or can I do it with the File::get() function?
I've checked the API but there doesn't seem to have a function to read the contents of the file.
You can use simple PHP:
foreach(file('yourfile.txt') as $line) {
// loop with $line for each line of yourfile.txt
}
You can use the following to get the contents:
$content = File::get($filename);
Which will return a Illuminate\Filesystem\FileNotFoundException if it's not found. If you want to fetch something remote you can use:
$content = File::getRemote($url);
Which will return false if not found.
When you have the file you don't need laravel specific methods for handling the data. Now you need to work with the content in php. If you wan't to read the lines you can do it like #kylek described:
foreach($content as $line) {
//use $line
}
You can use
try
{
$contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
die("The file doesn't exist");
}
you can do something like this:
$file = '/home/albert/myfile.txt';//the path of your file
$conn = Storage::disk('my_disk');//configured in the file filesystems.php
$stream = $conn->readStream($file);
while (($line = fgets($stream, 4096)) !== false) {
//$line is the string var of your line from your file
}
You can use
file_get_contents(base_path('app/Http/Controllers/ProductController.php'), true);
$tmpName = $request->file('csv_file');
$csvAsArray = array_map('str_getcsv', file($tmpName));
I have a form from which I save the given input into a textfile,
but I have trouble reading from the saved file:
while(!feof($fileNotizen)) {
$rawLine = fgets($fileNotizen);
if($rawLine==false) {
echo "An error occured while reading the file";
}
$rawLine seems to be always false, even though I use this function before, to fill the textfile:
function addToTable($notizFile) {
fwrite($notizFile, $_POST["vorname"]." ".$_POST["nachname"]."#");
$date = date(DATE_RFC850);
fwrite($notizFile, $date."#");
fwrite($notizFile, $_POST["notiz"].PHP_EOL);
}
And after I submit the form and get the error message, if I check the textfile, everything is there, so the function works correctly.
If it is of value, I open the file with this command:
$fileNotizen = fopen("notizen.txt", "a+");
Could the problem be that the pointer is already at the end of the file and thus returns false?
$fileNotizen = fopen("notizen.txt", "a+");
a+ opens for read/write but places file pointer AT THE END. So you must fseek() to the beginning first or look into fopen() flags and choose more wisely based on your needs.
Use fseek($fileNotizen, 0, SEEK_SET); to rewind the file.
To read/get content of the file try this function:
function read_file($file_name) {
if (is_readable($file_name)) {
$handle = fopen($file_name, "r");
while (!feof($handle)) {
$content .= fgets($handle);
}
return !empty($content) ? $content : "Empty file..";
} else {
return "This file is not readable.";
}
}
and if you want to see content of the file displayed on separate lines then use <pre></pre> tag like this:
echo "<pre>" . read_file("notizen.txt") . "</pre>";
and if you want to write/add content to the file then try this function:
function write_file($file_name, $content) {
if (file_exists($file_name) && is_writable($file_name)) {
$handle = fopen($file_name, "a");
fwrite($handle, $content . "\n");
fclose($handle);
}
}
and you can use it like this:
$content = "{$_POST["vorname"]} {$_POST["nachname"]}#" . date(DATE_RFC850) . "#{$_POST["notiz"]}";
write_file("notizen.txt", $content);
I'm new to learning php and in one of my first programs I wanted to make a basic php website with login capabilities with and array of the user and passwd.
my idea is to store the username as a list parameter and have the passwd as the contents, like this:
arr = array(username => passwd, user => passwd);
now my problem is that I don't know how I can read from the file (data.txt) so I can add it into the array.
data.txt sample:
username passwd
anotherUSer passwd
I've opened the file with fopen and stored it in $data.
You can use the file() function.
foreach(file("data.txt") as $line) {
// do stuff here
}
Modify this PHP example (taken from the official PHP site... always check first!):
$handle = #fopen("/path/to/yourfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
to:
$lines = array();
$handle = #fopen("/path/to/yourfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
lines[] = $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
// add code to loop through $lines array and do the math...
Be aware that you should not store login details in a textfile that in addition is not encrypted, this approach has severe security issues.
I know you are new from PHP, but the best approach is to store it in a DB and crypting the passwords with an algorithm such as MD5 or SHA1,
You shouldn't store sensitive information as plaintext, but to answer your question,
$txt_file = file_get_contents('data.txt'); //Get the file
$rows = explode("\n", $txt_file); //Split the file by each line
foreach ($rows as $row) {
$users = explode(" ", $row); //Split the line by a space, which is the seperator between username and password
$username = $users[0];
$password = $users[1];
}
Take a look at this thread.
This works for extremely large files as well:
$handle = #fopen("data.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = stream_get_line($handle, 1000000, "\n");
//Do Stuff Here.
}
fclose($handle);
}
Use file() or file_get_contents() to create either an array or a string.
process the file contents as needed
// Put everything in the file in an array
$aArray = file('file.txt', FILE_IGNORE_NEW_LINES);
// Iterate throug the array
foreach ($aArray as $sLine) {
// split username an password
$aData = explode(" ", $sLine);
// Do something with the username and password
$sName = $aData[0];
$sPass = $aData[1];
}
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.