I am writing an "unfriend" script for my mini social network, basically the unfriend action needs to remove their id called: $user from their friend list and my id called: $my_id. I have made the scripts that add user id's to each users files but I am not sure how to delete this?
My friend_list file:
1,2,3 // I am user 1
Their friend_list file:
1,2,3 // They are user 3
I currently use this to add each id into the text file:
if($action === 'accept'){
mysql_query("DELETE FROM `friend_req` WHERE `from`='$user' AND `to`='$my_id'");
$fp = fopen($user_data['friend_list'], 'a');
fwrite($fp, ",".$user."");
fclose($fp);
$their_id = friend_list_from_user_id($user);
$fp = fopen($their_id, 'a');
fwrite($fp, ",".$my_id."");
fclose($fp);
}
But to remove $my_id from their friend_list and their $userid from my friend_list I'm thinking I need to use something like this but it isn't working:
if($action === 'unfriend'){
$fp = fopen($user_data['friend_list'], 'a');
unset($user);
fclose($fp);
$their_id = friend_list_from_user_id($user);
unset($my_id);
fclose($fp);
}
But that doesn't seem to work, what should I do to delete only the specified usernames from the respective file?
Oh, and also, this may/may not be of use:
$myFile = $file;
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
$friend = explode(',', $theData);
for($i=0; $i < count($friend); $i++){
if($i >= 0)
{
if($friend[$i] == $user_id) {
$their_user_id = $user_id;
}
}
To solve your issue just do something like:
//get the contents of the file
$contents = file_get_contents($user_data['friend_list']);
$contents = str_replace(",".$friend_id, "", $contents); //remove the friend's id
//open the file again and rewrite the whole thing with the new contents without that id
$fp = fopen($user_data['friend_list'], 'w+');
fwrite($fp, $contents);
fclose($fp);
Related
I'm trying to make a simple search engine, just to know how it works. I'm following an old tutorial on how to do it with php and mySQL.
However it doesn't explain how to create a urllist.txt file. I downloaded a Quantcast-Top-Million.txt file as required but i'm still confused about how to create a urllist and how it's related to the Quantcast-Top-Million.txt file.
$file_handle = fopen("Quantcast-Top-Million.txt",
"r");
while (!feof ($file_handle)){
$line=fgets($file_handle);
if(preg_match('/ˆ\d+/',$line)){
$tmp=explode("\t",$line);
$rank=trim($tmp[0]);
$url=trim($tmp[1]);
if($url != 'Hidden profile') {
echo $i ;
}
}
}
fclose($file_handle);
$file_handle = fopen("urllist.txt", "r");
while (!feof($file_handle)) {
$url = trim(fgets($file_handle));
$content = file_get_contents($url);
$document = array($url,$content);
$serialized = serialize($document);
$fp = fopen('./documents/'.md5($url), 'w');
fwrite($fp, $serialized); fclose($fp);
}
fclose($file_handle);
This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
i was wondering if it is posible to delete a single line in a txt file with php.
I am storing emailadresses in a flat txt file named databse-email.txt
I use this code for it:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email-subscribe'] . ',' . "\n";
$store = file_put_contents('database-email.txt', $email, FILE_APPEND | LOCK_EX);
if($store === false) {
die('There was an error writing to this file');
}
else {
echo "$email successfully added!";
}
}
?>
Form:
<form action="" method="POST">
<input name="email-subscribe" type="text" />
<input type="submit" name="submit" value="Subscribe">
</form>
The content of the file looks like this:
janny#live.nl,
francis#live.nl,
harry#hotmail.com,
olga#live.nl,
annelore#mail.ru,
igor#gmx.de,
natasha#hotmail.com,
janny.verlinden#gmail.com,
All lines are , seperated
Lets say i want to delete only the emailadres: igor#gmx.de
How can i do that?
What i want to achieve is a unsubscribe form and delete a single line in the .txt file
You can use str_replace
$content = file_get_contents('database-email.txt');
$content = str_replace('igor#gmx.de,', '', $content);
file_put_contents('database-email.txt', $content);
Because of the way the filesystem works you can't do this in an intuitive way. You have to overwrite the file with all the lines except the one you want to delete, here's an example:
$emailToRemove = "igor#gmx.de";
$contents = file('database-email.txt'); //Read all lines
$contents = array_filter($contents, function ($email) use ($emailToRemove) {
return trim($email, " \n\r,") != $emailToRemove;
}); // Filter out the matching email
file_put_contents('database-email.txt', implode("\n", $contents)); // Write back
Here's a streaming alternative solution in the cases where the file does not fit in memory:
$emailToRemove = "igor#gmx.de";
$fh = fopen('database-email.txt', "r"); //Current file
$fout = fopen('database-email.txt.new', "w"); //New temporary file
while (($line = fgets($fh)) !== null) {
if (trim($line," \n\r,") != $emailToRemove) {
fwrite($fout, $line, strlen($line)); //Write to new file if needed
}
}
fclose($fh);
fclose($fout);
unlink('database-email.txt'); //Delete old file
rename('database-email.txt.new', 'database-email.txt'); //New file is old file
There is also a way to do this in-place to minimize extra disk needed but that is trickier.
You can do it programmatically which will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file . Like below
$DELETE = "igor#gmx.de";
$data = file("database-email.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("database-email.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
first read the file using fopen and fget , and make array to list the emails you want to remove , use in_array to check if value exists in array , and then after remove unwanted emails save the file using fwrite and you need to close the file after the read and the write operations using fclose
checkout this code
$data = "";
$emailsToRemove = ["igor#gmx.de" , "janny#live.nl"];
//open to read
$f = fopen('databse-email.txt','r');
while ($line = fgets($f)) {
$emailWithComma = $line . ",";
//check if email marked to remove
if(in_array($emailWithComma , $emailsToRemove))
continue;
$data = $data . $line;
}
fclose($f);
//open to write
$f = fopen('databse-email.txt','w');
fwrite($f, $data);
fclose($fh);
for delete special word and next delete blank line try this:
$file = "file_name.txt";
$search_for = "example_for_remove";
$file_data = file_get_contents($file);
$pattern = "/$search_for/mi";
$file_data_after_remove_word = preg_replace($pattern, '', $file_data);
$file_data_after_remove_blank_line = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $file_data_after_remove_word);
file_put_contents($file,$file_data_after_remove_blank_line);
I'm writing a script for a lead contact form that needs to send the first 10 leads to email 1, the second 10 leads to email 2, and so on until it gets to email 4, and then it goes back to email 1.
this is a rotator i have that was built for landing pages, but it rotates 1 each time rather than waiting 10 times, and then rotating. how would I modify this to suit my needs?
Also, it cant happen on every 'refresh' obviously. there would need to be a separate group of code which would go in the action="whatever.php" of the form and thats the code that would increment it.
<?php
//these are the email addresses to be rotated
$email_address[1] = 'email1#email.com';
$email_address[2] = 'email2#email.com';
$email_address[3] = 'email3#email.com';
$email_address[4] = 'email4#email.com';
//this is the text file, which will be stored in the same directory as this file,
//count.txt needs to be CHMOD to 777, full privileges, to read and write to it.
$myFile = "count.txt";
//open the txt file
$fh = #fopen($myFile, 'r');
$email_number = #fread($fh, 5);
#fclose($fh);
//see which landing page is next in line to be shown.
if ($email_number >= count($email_address)) {
$email_number = 1;
} else {
$email_number = $email_number + 1;
}
//write to the txt file.
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $email_number . "\n";
fwrite($fh, $stringData);
fclose($fh);
//include the landing page
echo $email_address[$email_number];
//terminate script
die();
?>
What I understood from your question is there would be form to submit leads and when a lead is submitted, it has to follow your logic. Correct me if I'm wrong.
If that be the case,
use two a text file like track.txt. The initial contents of this text file would be 1,0. Which means leads are sent to first email id 0 times.
So in the action script of the form include the following code.
<?php
$email_address[1] = 'email1#email.com';
$email_address[2] = 'email2#email.com';
$email_address[3] = 'email3#email.com';
$email_address[4] = 'email4#email.com';
$myFile = "track.txt";
//open the txt file
$fh = #fopen($myFile, 'r');
$track = #fread($fh, 5);
#fclose($fh);
$track = explode(",",$track);
$email = $track[0];
$count = $track[1];
if($count >= 10)
{
$count=0;
if($email >= count($email_address))
{
$email = 1;
}
else
{
$email++;
}
}
else
{
$count++;
}
$track = $email.",".$count;
//write to the txt file.
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $track);
fclose($fh);
//send lead to $email
?>
I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/
I use some code here, transfer mysql query data into json data and write into a file. where is the problem? why the file is zero kb?
while($row = mysql_fetch_array($Query)){
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
$countfile="data.txt";
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
$fp = fopen($countfile, 'r');
fwrite($fp, $jsondata);
fclose($fp);
}
Several things.
You dont need (and should avoid) to open the file in every iteration
You open the file read-only (r)
At all something like this should do it
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
fwrite($fp, $jsondata);
}
fclose($fp);
Additional you append separate json structures into the file, what is probably not, what you want. You should first collect all you want to store into one json structure and save it then
$data = array();
while($row = mysql_fetch_array($Query))
{
$data[] = array ('name'=>$row['name']);
}
file_put_contents('data.txt', json_encode($data));
This feels more like what you are probably looking for.
Because you're reopening the file as read only
$fp = fopen($countfile, 'r');
try
$fp = fopen($countfile, 'w'); // to write
or
$fp = fopen($countfile, 'a'); // to append
you could also open the file for writing at the start, append your rows in a variable and then write it all together to the file.
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata .= json_encode($arr) . "\n";
}
fwrite($fp, $jsondata);
fclose($fp);
You are opening the file read-only. You probably want 'w' or 'r+'.
You are opening the file for reading only
$fp = fopen($countfile, 'r');
You also dont need
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
just use:
$fp = fopen($countfile, 'w');