Find and replace word in text file - php

I want to detect if a word in a text file exists, and then remove it.. so, this is my code:
<?php
$search = $id;
$lines = file("./user/".$_GET['own'].".txt");
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
// open to read and modify
$file = "./user/".$_GET['own'].".txt";
$fh = fopen($file, 'r+');
$data = fread($fh, filesize($file));
$new_data = str_replace($id."\n", "", $data);
fclose($fh);
// Open to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_data);
fclose($fh);
$status = "has been successfully deleted.";
}
}
// If the text was not found, show a message
if(!$found)
{
$status = "is not exist in your list.";
}
?>
I got this work hours before.. I did some changes to my script and somehow, it didnt work anymore.. can anyone see through the code and tell me what is wrong??
or can anybody give simpler way to do what I want?? my code is messed..

I want to detect if a word in a text file exists, and then remove it..
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents);
file_put_contents($filename,$contents);
?>
That is all that there is to it.
Edit:
To make this equivalent to your solution, one can use
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents,$count);
if($count>0)
{
file_put_contents($filename,$contents);
echo "found and removed";
}
else
{
echo "not found";
}
?>

Related

How to find multiple lines from file with PHP?

I'm writing a PHP script to search for a few lines in a pcap file. This pcap file will be piped through tail -> PHP.
I need to find a few lines like (Host: www.google.com) or (Domain: amazon.com) etc..
I'm new with PHP and struggling to get this code working, the actual output of all the fetched data need to be inserted into a SQL DB. I've used regex to filter out the binary stuff from the pcap.
I've tried multiple loops like the wile, foreach, for, but I'm not getting the clue how to do this in my script.
The code that I have so far is:
<?php
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search1 = 'Location';
$search2 = 'Host:';
$search3 = 'User';
$search4 = 'Cookie';
$search5 = 'Domain:';
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
if(strpos($buffer, $search1) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
fclose($handle);
}
?>
I've read many posts on the internet, but couldn't find any solution or I've not enough knowledge about PHP to get this done. Can anyone help me with this?
If it's working for first then loop it think about algorithm always
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search = ['Location','Host:','User','Cookie','Domain:'];
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
foreach($search as $seek){
if(strpos($buffer, $seek) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
}
fclose($handle);
}
?>

PHP data processing not outputting

Hi I am trying to get this external text file to print inside my php document. The code looks fine to me however when I echo it does not output anything and I am not sure why this is. Can anybody help me out as I am new to this.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
$fp = fopen($location, 'r');
if ($fp) {
$readin = fread($fp);
fclose($fp);
} else {
echo 'Can\'t open input.txt';
}
Not sure what you're trying to 'echo' but have you checked if the file exists in the first place?
Your code could be written as:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location) && $data = file_get_content($location)){
echo $data;
} else {
echo 'File not found';
}
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} esle {
echo 'File not found';
}
See here for more: http://php.net/manual/en/function.file-get-contents.php, http://php.net/manual/en/function.filesize.php

Read serialized file, record by record

I save to file data from form:
$name = $_POST['name'];
$url = $_POST['url'];
$comm = $_POST['comm'];
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data));
Now, I would like to read this file record by record.
$file_handle = fopen("db.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$arr = unserialize($line);
var_dump($arr);
}
fclose($file_handle);
But this code read only last record. How to read all file?
Replace file_put_contents("db.txt", serialize($data)); to
file_put_contents("db.txt", PHP_EOL .serialize($data), FILE_APPEND);
file_put_contents("db.txt", serialize($data));// will over write the file again and again. so you cant able to read all the data. FILE_APPEND helps to append the data And PHP_EOL helps to leave a line breake.
Hi i try this code for your solution:
<?php
$name = "rdn";
$url = "http://google.it";
$comm = "com";
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data)."\n",FILE_APPEND);
$fh = fopen('db.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
var_dump(unserialize($line));
}
fclose($fh);
?>
without "\n" don't work!

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

php - search TXT file by users $_post from form

Im having a little problem.
I have a txt file that i can write users names.
Thats ok!
But im trying to search the txt file by user input ($_POST['username']).
I getting user do not exist all the time..
anyone that can give me some tips?
My txt file contains:
Admin
Sheldon
Penny
Here is the code:
$user = $_POST['username'];
function CreateAccount($user){
if($_POST['reg']){
$file = 'test.txt';
$data = $user ."\n";
fopen($file, 'a');
file_put_contents($file, $data, FILE_APPEND);
}
}
function userSearch($user){
if($_POST['read']){
$file = 'test.txt';
$searchUser = $user;
fopen($file, 'r');
$content = file_get_contents($file);
if(strpos($content, $user)){
echo "exist";
}else{
echo "nope..";
}
}
}
String positions with strpos start at 0 not 1. So if the position is 0 it will equate to false.
Simple fix for your if statement may help
if(strpos($content, $user) !== FALSE){
PHP strpos
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
t.txt:
AdminSheldonLeonard
t.php
<?php
$file = "t.txt";
$name = "Sheldon";
$string = file_get_contents($file);
$array = file($file, FILE_IGNORE_NEW_LINES);
if(in_array($name,$array)){
echo "found ";
}else{
echo "nope ";
}
if(strstr($string,$name)){
echo "found ";
}else{
echo "nope ";
}
?>
output:
found found

Categories