0

I am trying to save requested string to a text file. If string exist in file, it returns message if not it saves string and return ok message. Below is what I did and its not working. I do not get any file in the current directory.

<?php

$data=$_REQUEST["data"];

function registration($dat)
{
$file = 'data.txt';
if( strpos(file_get_contents($file),$_GET[$dat]) !== false) {
 $current = file_get_contents($file);
 $current .= $dat;
 file_put_contents($file, $current);    
 $result.='Data Added ok!!';
 return $result;
 } else {  
$result.='Data Already Saved';
return $result;
 }
}

echo registration($data);

?>

4 Answers 4

1

Try this UPDATED :: add a new line on each save:

    $data=((string)$_REQUEST["data"]);
    echo registration($data);
    function registration($dat,$file = 'data.txt')
    {
    $result='';
    $fileContent=file_get_contents($file);
    if( strpos($fileContent,$dat) === false) {
     $current = $fileContent;
     $current .= "\r\n".$dat;
     file_put_contents($file, $current);    
     $result.='Data Added ok!!';

     } else { 
    $result.='Data Already Saved';

     }
     return $result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

working (Y) just one quesion how to add linebreak after saving data
1

You may have made a mistake. What is $dat ?

$current .= $dat;

Plus I have doubts about the use of !==, why not a simple != ?

3 Comments

because strpos may return 0 when it finds the search at the beginning of the string, which would be evaluated to false because /* if(0) { } */ php.net/manual/en/language.operators.comparison.php
Ha, yes. I should have read the manual of course. Thanks for upvoting my answer :)
Don't worry Welcome :)
0

You mix here variable with $_GET and $_REQUEST. It should work in your case:

<?php

$data=$_REQUEST["data"];

function registration($data)
{
 $file = 'data.txt';
 $content = file_get_contents($file);

 mb_internal_encoding('UTF-8');
 if( mb_strpos($content, $data) !== false) {

 file_put_contents($file, $content.$data);    
 $result ='Data Added ok!!';
 return $result;
 } else {  
$result ='Data Already Saved';
return $result;
 }
}

echo registration($data);

?>

Comments

0

Create an empty file with name data.txt at the same directory, and change permissions of the file to +w and check your if statement.

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.