0

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!

2 Answers 2

1
<?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;

?>
Sign up to request clarification or add additional context in comments.

3 Comments

Still having an issue if you have time to help: I'm trying to get a bit of logic working based on whether the value of a radio button is checked as yes or no. If it's yes then I want to replace the content using fopen with some data that was inputted into an input field. If it's no then I want to replace the content with nothing. Here's my code: (there's no errors at all. It just doesn't seem to like my radio buttons. (I got it working fine testing if an input field was empty or not btw.) pastebin.com/fQN608A7 I just pasted the areas related to my issue so not all the file is there).
for the record, I tested $enableSocialIcons and it does return yes or no successfully when I try to echo it after form submission
If the radio button is no: Array ( [field] => [enableSocialIcons] => yes [twitter] => ) if the radio button is yes: Array ( [field] => [enableSocialIcons] => yes [twitter] => ) The str_replace works fine and adds my twitter link in fine. But my problem is that when I select no, it's not doing what I want. It's acting as if I've selected yes. From what I understand, It should be doing a str_replace on that comment to make it completely blank. sorry about the bad formatting, it does it automatically on comments.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.