I have a text file :
Topic identified: Sports
I have 2 php files:
file 1:
<?php
include "topic_detection.php";
$text = isset($_POST["text"]) ? $_POST["text"] : '';
$file = "textfile.txt";
$outputfile= "outputfile.txt";
if(!empty($_POST)){
writetofile($file, $text, "w");
execpython($file);
$topic = getoutput($outputfile);
}
?>
file 2: topic_detection.php
<?php
function writetofile($file, $content, $writeType){
$fo = fopen($file, $writeType);
if($fo){
fwrite($fo,$content);
fclose($fo);
}
}
function execpython($file){
system("python predict.py $file");
}
function getoutput($file1){
$fh= fopen($file1, 'r');
$theData = fread($fh,1);
fclose($fh);
echo $theData;
return $theData;
}
?>
On trying to get the output of $theData, the only output I receive is a 'T' I am guessing this T is coming from the first letter in the text file. In that case, am I not making the call correctly?
here is my call:
<div align="center"><h4 style="line-height:150%;"><?php echo $topic; ?></h5></div>
You are passing fread a length of 1:
$theData = fread($fh,1);
You will always get only the first character.
To read the entire file: (From the PHP docs http://php.net/manual/en/function.fread.php)
$contents = fread($handle, filesize($filename));
You could also use http://php.net/manual/en/function.file-get-contents.php
So I'm working on a little php file that is supposed to alter a specific file for the user. It gets the contents of the file and puts them into a textarea within a form. How can I make it so any edits done within this textarea will be rewritten to the file on the server? And even better, would I be able to allow the user to only edit certain lines, and have only those lines be rewritten?
Here's my code so far:
<?php
$filename = "../tree_c/index.php";
//$fp = fopen ($filename, "w"); <- doesn't seem to work for it opens empty file.
$contents = file_get_contents($filename);
/*
if (isset($_POST['field'])) {
// something here to rewrite the file.
*/
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<textarea name="field"><?php echo $contents ?></textarea>
<input type="submit" value="Save">
</form>
This should work fairly easily:
if (isset($_POST['field'])) {
file_put_contents($filename, $_POST['field']);
}
$datafile = "Files.txt";
$fp = fopen($datafile, "r");
$textdata= fgets($fp, 1024);
$text = '"'.$textdata.'"';
$this->set('text',$text);
if(!empty($this->data))
{
$datas = $this->data['data']['text']; //(your Textarea name)
$myFile = "Files.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $datas);
fclose($fh);
}
hope this ll help you....
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);
}
I am trying to display the contents of a .cpp file in php. I am loading it using fread when I print it out it comes out formatted incorrectly. How can I keep the format without escaping each character?
Assuming you want to look at it in a web browser:
<pre>
<code>
<?php echo htmlspecialchars(file_get_contents($file)); ?>
</code>
</pre>
print it out between the HTML <pre> & <code> tags.
<?php
echo "<pre><code>";
$filename = "./test.cpp";
$handle = fopen($filename, "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096); // assuming max line len is 4096.
echo htmlspecialchars($buffer);
}
fclose($handle);
}
echo "</code></pre>";
?>
We need htmlspecialchars function to print it out correctly.
I'm making this program and I'm trying to find out how to write data to the beginning of a file rather than the end. "a"/append only writes to the end, how can I make it write to the beginning? Because "r+" does it but overwrites the previous data.
$datab = fopen('database.txt', "r+");
Here is my whole file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Facebook v0.1</title>
<style type="text/css">
#bod{
margin:0 auto;
width:800px;
border:solid 2px black;
}
</style>
</head>
<body>
<div id="bod">
<?php
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$comment = $_REQUEST['comment'];
$datab = $_REQUEST['datab'];
$gfile = $_REQUEST['gfile'];
print <<<form
<table border="2" style="margin:0 auto;">
<td>
<form method="post" action="">
First Name :
<input type ="text"
name="fname"
value="">
<br>
Last Name :
<input type ="text"
name="lname"
value="">
<br>
Comment :
<input type ="text"
name="comment"
value="">
<br>
<input type ="submit" value="Submit">
</form>
</td>
</table>
form;
if((!empty($fname)) && (!empty($lname)) && (!empty($comment))){
$form = <<<come
<table border='2' width='300px' style="margin:0 auto;">
<tr>
<td>
<span style="color:blue; font-weight:bold;">
$fname $lname :
</span>
$comment
</td>
</tr>
</table>
come;
$datab = fopen('database.txt', "r+");
fputs($datab, $form);
fclose($datab);
}else if((empty($fname)) && (empty($lname)) && (empty($comment))){
print" please input data";
} // end table
$datab = fopen('database.txt', "r");
while (!feof($datab)){
$gfile = fgets($datab);
print "$gfile";
}// end of while
?>
</div>
</body>
</html>
The quick and dirty:
<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
If you don't want to load the entire contents of the file into a variable, you can use PHP's Streams feature:
function prepend($string, $orig_filename) {
$context = stream_context_create();
$orig_file = fopen($orig_filename, 'r', 1, $context);
$temp_filename = tempnam(sys_get_temp_dir(), 'php_prepend_');
file_put_contents($temp_filename, $string);
file_put_contents($temp_filename, $orig_file, FILE_APPEND);
fclose($orig_file);
unlink($orig_filename);
rename($temp_filename, $orig_filename);
}
What this does is writes the string you want to prepend to a temporary file, then writes the contents of the original file to the end of the temporary file (using streams instead of copying the whole file into a variable), and finally removes the original file and renames the temporary file to replace it.
Note: This code was originally based on a now-defunct blog post by Chao Xu. The code has since diverged, but the original post can be viewed in the Wayback Machine.
I think what you can do is first read the content of the file and hold it in a temporary variable, now insert the new data to the beginning of the file before also appending the content of the temporary variable.
$file = file_get_contents($filename);
$content = 'Your Content' . $file;
file_put_contents($content);
Open a file in w+ mode not a+ mode.
Get the length of text to add ($chunkLength)
set a file cursor to the beginning of the file if needed
read $chunkLength bytes from the file
return the cursor to the $chunkLength * $i;
write $prepend
set $prepend a value from step 4
do these steps, while EOF
$handler = fopen('1.txt', 'w+');//1
rewind($handler);//3
$prepend = "I would like to add this text to the beginning of this file";
$chunkLength = strlen($prepend);//2
$i = 0;
do{
$readData = fread($handler, $chunkLength);//4
fseek($handler, $i * $chunkLength);//5
fwrite($handler, $prepend);//6
$prepend = $readData;//7
$i++;
}while ($readData);//8
fclose($handler);
You can use the following code to append text at the beginning and end of the file.
$myFile = "test.csv";<br>
$context = stream_context_create();<br>
$fp = fopen($myFile, 'r', 1, $context);<br>
$tmpname = md5("kumar");<br>
//this will append text at the beginning of the file<br><br>
file_put_contents($tmpname, "kumar");<br>
file_put_contents($tmpname, $fp, FILE_APPEND);<br>
fclose($fp);<br>
unlink($myFile);<br>
rename($tmpname, $myFile);<br><br>
//this will append text at the end of the file<br>
file_put_contents($myFile, "ajay", FILE_APPEND);
You can use fseek to change the pointer in the note.
It has to be noted that if you use fwrite it will erase the current content. So basically you have to read the whole file, use fseek, write your new content, write the old data of the file.
$file_data = file_get_contents('database.txt')
$fp = fopen('database.txt', 'a');
fseek($fp,0);
fwrite($fp, 'new content');
fwrite($fp, $file_data);
fclose($fp);
If your file is really huge and you don't want to use too much memory, you might want to have two file approach like
$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
$contents .= fread($fp_source, 8192);
fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');
The solution of Ben seems to be more straightforward in my honest opinion.
One last point: I don't know what you are stocking in database.txt but you might do the same more easily using a database server.
One line:
file_put_contents($file, $data."\r\n".file_get_contents($file));
Or:
file_put_contents($file, $data."\r\n --- SPLIT --- \r\n".file_get_contents($file));
This code remembers data from the beginning of the file to protect them from being overwritten. Next it rewrites the all the data existing in file chunk by chunk.
$data = "new stuff to insert at the beggining of the file";
$buffer_size = 10000;
$f = fopen("database.txt", "r+");
$old_data_size = strlen($data);
$old_data = fread($f, $old_data_size);
while($old_data_size > 0) {
fseek($f, SEEK_CUR, -$old_data_size);
fwrite($f, $data);
$data = $old_data;
$old_data = fread($f, $buffer_size);
$old_data_size = strlen($data);
}
fclose($f);
There is no way to write to the beginning of a file like you think. This is I guess due to reason how OS and HDD are seeing the file. It has got a fixed start and expanding end. If you want to add something in the middle or beggining it requires some sliding. If it is a small file just read it all and do your manipulation and write back. But if not, and if you are always adding to the beginning just reverse line order, consider the end as beginning...
file_get_contents() and file_put_contents() use more memory than using the fopen(), fwrite(), and fclose() functions:
$fh = fopen($filename, 'a') or die("can't open file");
fwrite($fh, $fileNewContent);
fclose($fh);