I'm rather new to PHP, and was trying to remove all lines where any instance of the string variable 'user' appears. My current code
if($action == "removeUser")
{
foreach(file('users.txt') as $line)
{
if (strpos($line, $parameters) !== false)
{
$line = "";
}
}
}
For some reason this doesn't seem to have any effect at all. What am I doing wrong?
You need to open the file and read the lines.
<?php
if($action == "removeUser")
{
$filename = "users.txt";
// Open your file
$handle = fopen($filename, "r");
$new_content='';
echo "Valid input: <br><br>";
// Loop through all the lines
while( $line = fgets($handle) )
{
//try to find the string 'user' - Case-insensitive
if(stristr($line,"user")===FALSE)
{
// To remove white spaces
$line=trim($line);
if($line!='') echo $line."<br>";
//if doesn't contain the string "user",
// add it to new input
$new_content.=$line."\n";
}
}
// closes the file
fclose($handle);
$new_content=trim($new_content); // Remove the \n from the last line
echo "<br>Updating file with new content...";
file_put_contents($filename,$new_content);
echo "Ok";
}
?>
Related
I have some websites and I want to add a new code just after <?php
I wrote this code but not works:
<?php
error_reporting(0);
$dir = __DIR__;
$index = $dir.'/index.php';
if (is_file($index)) {
$content = file_get_contents($index);
if (strpos($content, 'validator') === false) {
str_replace('<?php', '<?php require_once \'path/validator.php\';', $content);
//Write the index:
$write = fopen($index,"w");
fwrite($write,$content);
fclose($write);
}
//Check again:
$content = file_get_contents($index);
if (strpos($content, 'validator') === true) {
echo "Line added successfuly";
unlink($dir.'/install.php');
} else {
echo "Line not added";
}
}
?>
How can I do this?
Thanks...
strpos() never returns true. It either returns a numeric index or false.
So change the second check to
if (strpos($content, 'validator') !== false)
By the way, you can use file_put_contents() to write the file in one step, just as you use file_get_contents() to read it.
I need to search a string in .cfg file, and delete the whole line. I'm using file_get_contents to retrieve the the data in .cfg file, and I'm storing it in a variable, searching is good but not knowing how to delete the whole line?
I have a string in following way:
user $username insecure-password $password
I want to search $username and delete the whole line.
Use a little Regex to match the line:
<?php
$file = 'blah
etc
user delboy1978uk insecure-password 123456
etc
etc';
$regex = '#\nuser\s\w+\sinsecure-password\s.+\n#';
preg_match($regex, $file, $matches);
$file = str_replace($matches[0], "\n", $file);
echo $file;
Which outputs:
blah
etc
etc
etc
See it here: https://3v4l.org/BcDWK
With this method you can read each config file line by line search in each line.
$h = fopen('yourfile', 'r') ;
$match = 'username' ;
$output = [] ;
if ($h) {
while (!feof($h)) {
$line = fgets($h);
//your current search function, which search each line
if ( your_search_function($line, $match) === false) {
//array $output will not contain matching lines.
$output[] = $line;
}
}
fclose($h);
//write back to file or do something else with $output
$hw = fopen('yourfile', 'w') ;
if( $hw ) {
foreach( $output as $line ) {
fputs($hw, $line) ;
}
fclose($hw) ;
}
}
I'm trying to develop a PHP application where it takes comments from users and then match the string to check if the comment is positive or negative. I have list of negative words in negative.txt file. If a word is matched from the word list, then I want a simple integer counter to increment by 1. I tried the some links and created the a code to check if the comment has is negative or positive but it is only matching the last word of the file.Here's the code what i have done.
<?php
function teststringforbadwords($comment)
{
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $string)
{
$row = explode($new_tab, $string);
if(isset($row['0']) && $row['0'] != ""){
$outoutArr[] = trim($row['0']," ");
}
}
//---------------------------------------------------------------
foreach($outoutArr as $word) {
if(stristr($comment,$word)){
return false;
}
}
return true;
}
if(isset($_REQUEST["submit"]))
{
$comments = $_REQUEST["comments"];
if (teststringforbadwords($comments))
{
echo 'string is clean';
}
else
{
echo 'string contains banned words';
}
}
?>
Link Tried : Check a string for bad words?
I added the strtolower function around both your $comments and your input from the file. That way if someone spells STUPID, instead of stupid, the code will still detect the bad word.
I also added trim to remove unnecessary and disruptive whitespace (like newline).
Finally, I changed the way how you check the words. I used a preg_match to split about all whitespace so we are checking only full words and don't accidentally ban incorrect strings.
<?php
function teststringforbadwords($comment)
{
$comment = strtolower($comment);
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = strtolower(fread($fopen,filesize("$file")));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $bannedWord)
{
foreach (preg_split('/\s+/',$comment) as $commentWord) {
if (trim($bannedWord) === trim($commentWord)) {
return false;
}
}
}
return true;
}
1) Your storing $row['0'] only why not others index words. So problem is your ignoring some of word in text file.
Some suggestion
1) Insert the text in text file one by one i.e new line like this so you can access easily explode by newline to avoiding multiple explode and loop.
Example: sss.txt
...
bad
stupid
...
...
2) Apply trim and lowercase function to both comment and bad string.
Hope it will work as expected
function teststringforbadwords($comment)
{
$file="sss.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
foreach(explode("\n",$fread) as $word)
{
if(stristr(strtolower(trim($comment)),strtolower(trim($word))))
{
return false;
}
}
return true;
}
Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.
The JavaScript part is correct but I'm having trouble with PHP:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
If it's only 50 words then just make an array out of it and check if it's in the array.
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
You are not searching the "word" into your code, but maybe the code below will help you
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
here is something fancy, regular expression :)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.
here is a working example : http://ideone.com/LmgksA
You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
This matches any word token in a string.
Lets say the text file " data1.txt" contains:
56715||Jim||Green||19
5678||Sara||Red||92
53676||Mark||Orange||6
56787||Mike||Purple||123
56479||Sammy||Yellow||645
56580||Martha||Blue||952
ect...
.
.
I would like to echo only the line beginning with "5678||". "5678" is the exact $refVal or reference value. The line should display like this:
My name is: $nameVar
My color is: $colorVar
My number is: $numVar
Thanks...
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgetcsv($fh, 0, '||')) {
if ($line[0] == 5678) {
echo <<<EOL
My name is: $line[1]
My color is $line[2]
My number is $line[3]
EOL;
break; // if there's only ever one '5678' line in the, get out now.
}
}
fclose($fh);
alternate version, as suggested by Jared below. Probably will be faster, as it only does the array creation on the line that actually matches, and not for each line as the fgetcsv version does.
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgets($fh)) {
if (strpos($line, '5678||') === 0) { // only if right at start of string
$data = explode('||', $line);
echo <<<EOL
my name is blah blah blah
EOL;
break;
}
}
You can split each line into an array using explode, like so:
foreach ($lines as $line)
{
$t = explode('||', $line);
if ($t[0] == $refVal) {
// echo the rest of $t array however you want
// $t[1] would be the name, $t[2] the color, etc
}
}