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);
?>
Related
I have two scripts: one of them writes the value of a variable to a file. In another script, I try to read it. It is written without problems, but it is not readable.
Here I write to a file:
$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file, $peer_id);
fclose($file);
Here I read the file:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
// Result is TRUE
}
if(is_readable ($file)){
// Result is FALSE
}
// an empty variables, because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);
The code runs on "sprinthost" hosting, if that makes a difference. There are suspicions that this is because of that hosting.
file_get_contents in short runs the fopen, fread, and fclose. You don't use a pointer with it. You should just use:
$peer_id = file_get_contents($fileLocation);
That is the same for is_readable:
if(is_readable($fileLocation)){
// Result is FALSE
}
So full code should be something like:
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
$peer_id = file_get_contents($fileLocation);
} else {
echo 'Error message about file being inaccessible here';
}
The file_get_contents has an inverse function for writing; https://www.php.net/manual/en/function.file-put-contents.php. Use that with the append constant and you should have the same functionality your first code block had:
file_put_contents($fileLocation, $peer_id, FILE_APPEND | LOCK_EX);
I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>
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';
}
I am having some difficulty with reading info from a text file. Is it possible to use php and get one line at a time, and compare that line to a variable, one character at a time? Every time I add the character searching algorithm it messes up. or does the file reading only do full files/lines/character
ex:
$file=fopen("text/dialogue.txt","r") or exit("unable to open dialogue file");
if($file == true) {
echo "File is open";
fgets($file);
$c = "";
while(!feof($file)) {
$line = fgets($file)
while($temp = fgetc($line)) {
$c = $c . $temp;
//if statement and comparrison
}
}
} else {
echo "File not open";
}
fclose($file);
You may use php file function to read a file line by line
<?php
$lines = file("myfile.txt");
foreach($lines as $line){
## do whatever you like here
echo($line);
}
?>
Please check php manual
http://php.net/manual/en/function.file.php
I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}