I am new to PHP and I am currently working on File Handling. I have a text file of which I am attempting to open for reading/appending using a skeleton script. The file is outputting and showing it is successfully opening, but only when I add a include function into the code. I have my code below, can someone look at it and tell me if I am doing it right because it feels right to me at the minute and it does output but i'm not 100% positive.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
include($location);
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} else {
echo 'File not found';
}
change your code to read and output file to below:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
//include($location); remove include
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
echo $file_content; //<----echo here to display content
fclose($file);
} else {
echo 'File not found';
}
Another option is to use file_get_contents().
It will also read the text file but it will read the text files full contents to a string.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location)){
$file_content = file_get_contents($file);
Echo $file_content;
$file_content .= " And some more"; //append string to end of string
Echo $file_content; // echo with appended string.
File_put_contetnts($file, $file_content); // save the original text plus the appended.
} else {
echo 'File not found';
}
Related
Hi I am trying to get this external text file to print inside my php document. The code looks fine to me however when I echo it does not output anything and I am not sure why this is. Can anybody help me out as I am new to this.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
$fp = fopen($location, 'r');
if ($fp) {
$readin = fread($fp);
fclose($fp);
} else {
echo 'Can\'t open input.txt';
}
Not sure what you're trying to 'echo' but have you checked if the file exists in the first place?
Your code could be written as:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location) && $data = file_get_content($location)){
echo $data;
} else {
echo 'File not found';
}
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} esle {
echo 'File not found';
}
See here for more: http://php.net/manual/en/function.file-get-contents.php, http://php.net/manual/en/function.filesize.php
A (simple) question.
I have a TXT file search script in PHP.
$search = $_GET["search"];
$logfile = $_GET['logfile'];
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
fclose($file);
Now what I want to do is delete all the text it finds in the TXT file.
I tried doing a str_replace but it didn't work.
Thanks for helping!
I think this will do the magic:
$file->ftruncate($file->ftell());
You need to gather the lines which doesn't contain the search term and you need to save the text in an array.
When you're done with the listing, you need to open the file in write mode (which will empty the file) and then write the text you gathered in the file.
Here's the code:
<?php
$search = isset($_GET["search"]) ? $_GET["search"] : '';
$logfile = isset($_GET['logfile']) ? $_GET['logfile'] : '';
$text_without_term_arr = array();
if(!empty($logfile) && !empty($search)){
// Read from file
$file = fopen($logfile, "r");
echo ' <head>
<title>Searching: ' . $search . '</title>
</head>';
while(($line = fgets($file))!== false){
if(stristr($line, $search)){
// Case insensitive search
echo '<font face="Arial">' . $line . '</font><hr/>';
} else {
// Search term not found in these lines
array_push($text_without_term_arr, $line);
}
}
fclose($file);
// Empty the file and write the text again without the search term
if(!empty($text_without_term_arr)){
$new_file = fopen($logfile, "w");
$content = implode("\n", $text_without_term_arr);
fwrite($new_file, $content);
fclose($new_file);
}
}
?>
You need another file handle to write the result out to:
$tempname=tmpname('/tmp','result');
$outfile=fopen($tempname,'w');
Next, use str_ireplace to remove the found text in each line:
$newline=str_ireplace($search, '', $line);
Then write the new line out to the out file:
fputs($outfile,$newline); // May need to send PHP_EOL too
Close the file off:
fclose($outfile);
And then rename the new file to the old filename:
rename($tempname,$logfile);
I'm working on what seems to be a simple php reading and writing to a txt file. I'm able to read the file but not write. I've tried variations of the following but to no avail. I'm trying to read the txt file that will have a 0 or a 1 in it and switch it. But for some reason I can only read. How can I make this code write to the file? Note I do have write permissions to the txt file.
Thx
Rich
<?php
$status = readfile("0.txt");
echo $status;
$file_handle = fopen("../light_switches/0.txt", "w");
if($status = 1){
$file_contents = "0";
fwrite($file_handle, $file_contents);
}
else if($status = 0){
$file_contents = "1";
fwrite($file_handle, $file_contents);
}
fclose($file_handle);
?>
readfile returns the number of bytes read from the file, but not the file content.
You could use file_get_contents to get the file content, and use file_put_contents to write:
$path = "../light_switches/0.txt";
file_put_contents($path, file_get_contents($path) === '0' ? '1' : '0');
Use file_put_contents(). It is the same as calling fopen(), fwrite(), and fclose(). Use the flag FILE_APPEND
file_put_contents($filepath, $content, FILE_APPEND);
PHP Documentation
EDIT
I have reworked this code. If all you are doing is trying to switch the 0 and 1 of the txt file, this code is working. Simply just replace the file path with yours.
<?php
$file_path = '0.txt';
if (!file_exists($file_path)) {
echo 'File does not exist';
exit;
}
$currentContent = file_get_contents($file_path);
echo $currentContent;
if ($currentContent == '0') {
$newContent = '1';
}
elseif ($currentContent == '1') {
$newContent = '0';
}
else {
//Start the file fresh if it found extra lines for example
$newContent = '0';
}
file_put_contents($file_path, $newContent);
?>
First goal: Create an index.html file and create a link to download the generated file
The issue here is when i click to generate new file the downloaded file is always the same and isnt updated
the variable $content has insite an entire html page with <headers><aside> and <sections>
I have the following code
if( empty( $error )){
echo "<h3>File generated</h3>";
$my_file = 'index.html';
if (file_exists($my_file)) {
if(unlink($my_file)){
};
$new_file = 'index.html';
$handle = fopen($new_file, 'w') or die('Cannot open file: '.$new_file);
$data = $content;
fwrite($handle, $data);
fclose($handle);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
} else {
$new_file = 'index.html';
$handle = fopen($new_file, 'w') or die('Cannot open file: '.$new_file);
$data = $content;
fwrite($handle, $data);
fclose($handle);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
}
hi i think it's will be work if variable $content will be contain correct data and you have permission to read, update, create file. in code I use file_put_contents function for minimize your code
if( empty( $error )){
echo "<h3>File generated</h3>";
$my_file = 'index.html';
file_put_contents($my_file, $content);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
}
UPDATE:
Are you sure that you have correctly generated content and the $content always contains different value?
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);