tctc91
tctc91

Reputation: 1363

Writing some data to a specific area within a file in PHP

I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?

Ideally, I'd like to:

  1. Use fopen to get the file
  2. Search for a comment called <!-- test -->
  3. Replace that comment with new data.

This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).

Thanks!

Upvotes: 0

Views: 194

Answers (2)

Josh
Josh

Reputation: 12566

<?php 
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
  // Open file for read and string modification 
  $file = "/test"; 
  $fh = fopen($file, 'r+'); 
  $contents = fread($fh, filesize($file)); 
  $new_contents = str_replace("hello world", "hello", $contents); 
  fclose($fh); 

  // Open file to write 
  $fh = fopen($file, 'r+'); 
  fwrite($fh, $new_contents); 
  fclose($fh); 
}
?> 

From: http://www.php.net/manual/en/function.fopen.php#81325

EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:

<?php

echo '<pre>';
print_r($_POST);
echo '</pre>';

exit;

?>

Upvotes: 1

rogerlsmith
rogerlsmith

Reputation: 6786

If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.

Upvotes: 0

Related Questions