Reputation: 97
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);
?>
Upvotes: 0
Views: 1126
Reputation: 418
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;
}
Upvotes: 1
Reputation: 1019
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.
Upvotes: 0
Reputation: 1118
You may have made a mistake. What is $dat ?
$current .= $dat;
Plus I have doubts about the use of !==, why not a simple != ?
Upvotes: 1
Reputation: 111859
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);
?>
Upvotes: 0