Frage

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);

?>
War es hilfreich?

Lösung

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;
}

Andere Tipps

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

$current .= $dat;

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

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);

?>

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top