Writing data to file adds ^M at end of line - php

Using PHP i'm writing content to a .htaccess file using fwrite, this all works correctly but when i view the .htaccess in Vim afterwards it displays ^M at the end of each line that has been added. This doesn't seem to cause any issues but i'm unsure quite whats happening to cause this and whether it can be prevented?
this is the PHP:
$replaceWith = "#SO redirect_301\n".trim($_POST['redirect_301'])."\n#EO redirect_301";
$filename = SITE_ROOT.'/public_html/.htaccess';
$handle = fopen($filename,'r');
$contents = fread($handle, filesize($filename));
fclose($handle);
if (preg_match('/#SO redirect_301(.*?)#EO redirect_301/si', $contents, $regs)){
$result = $regs[0];
}
$newcontents = str_replace($result,$replaceWith,$contents);
$filename = SITE_ROOT.'/public_html/.htaccess';
$handle = fopen($filename,'w');
if (fwrite($handle, $newcontents) === FALSE) {
}
fclose($handle);
When i check in Vim afterwards i will see something like this:
#SO redirect_301
Redirect 301 /from1 http://www.domain.com/to1^M
Redirect 301 /from2 http://www.domain.com/to2^M
Redirect 301 /from3 http://www.domain.com/to3
#EO redirect_301
The server is running CentOS and i'm working locally on a Mac

Your newlines are incoming as \r\n, not as \n.
Before writing to the file, you should replace the invalid input:
$input = trim($_POST['redirect_301']);
$input = preg_replace('/\r\n/', "\n", $input); // DOS style newlines
$input = preg_replace('/\r/', "\n", $input); // Mac newlines for nostalgia

Related

How can I remove unwanted spaces from txt file

I'm trying to modify my txt file what I'm using in dokuwiki.
I generate timestamp on top of the txt file like this:
function filecont($file,$data)
{
$fileContents = file($file);
array_shift($fileContents);
array_unshift($fileContents, $data);
$newContent = implode("\n", $fileContents);
$fp = fopen($file, "w+");
fputs($fp, $newContent);
fclose($fp);
}
And my original txt file looks like this:
Now when I use my function:
$txt= "Last generated: " . date("Y M D h:i:s");
filecont($file,$txt);
I get a result like this:
Now I don't want to remove my ====== Open IoT book ======, it's probably because I don't have empty space in the first line?
But the worst problem that I have Is that is generates many empty spaces what I don't want.
I only want to get last generated at the top of the txt file and anything else untouched
I tested your code and removed the extra newlines by changing the line:
$fileContents = file($file);
to
$fileContents = file($file, FILE_IGNORE_NEW_LINES);
Adding the FILE_IGNORE_NEW_LINES flag stops a newline being added to each element/line.
http://php.net/manual/en/function.file.php.
I also removed the array_unshift(), which leaves '====== Open IoT book ======' in the file.
So my final function looked like this:
function filecont($file,$data)
{
$fileContents = file($file, FILE_IGNORE_NEW_LINES);
//array_shift($fileContents); Removed to preserve '====== Open IoT book ======' line.
array_unshift($fileContents, $data);
$newContent = implode("\n", $fileContents);
$fp = fopen($file, "w+");
fclose($fp);
}
Might just delete this line
array_shift($fileContents);
solve your problem?
when you get elements of file you need to check whether Last generated: is as your first row or not accordong to it yu need to use array_shift
$fileContents = file($file);
if(stripos($fileContents[0],"Last generated:") !== false)
{
array_shift($fileContents); //if found use shift
}
array_unshift($fileContents, $data);

Batch download URLs in PHP?

So, I have a PHP script that is supposed to download images that the user inputs. However, if the user uploads a TXT file and it contains direct links to images, it should download the images from all the URLs in the file. My script seems to be working, although it seems that only the last file is downloaded while the others are stored as files containing no data.
Here's the portion of my script where it parses the TXT
$contents = file($file_tmp);
$parts = new SplFileObject($file_tmp);
foreach($parts as $line) {
$url = $line;
$dir = "{$save_loc}".basename($url);
$fp = fopen ($destination, 'w+');
$raw = file_get_contents($url);
file_put_contents($dir, $raw);
}
How do I make it download every URL from the TXT file?
When you iterate over an SplFileObject, you get the whole line, including whitespace. Your URL will thus be something like
http://example.com/_
(php seems to mangle the newline to an underscore) and thus you'll get an error for many URLs (some URLs will still work fine, since they contain the important information prior. For instance, Batch download URLs in PHP? works, but https://stackoverflow.com/_ does not). If an error occurs, file_get_contents will return false, and file_put_contents will interpret that like an empty string.
Also, the line $fp = fopen ($destination, 'w+'); is really strange. For one, since $destination is not defined, it would error anyways. Even if $destination is defined, you'll end up with lots of file handles and overwrite that poor file multiple times. You can just remove it.
To summarize, your code should look like
<?php
$file_tmp = "urls.txt";
$save_loc = "sav/";
$parts = new SplFileObject($file_tmp);
foreach($parts as $line) {
$url = trim($line);
if (!$url) {
continue;
}
$dir = "{$save_loc}".basename($url);
$raw = file_get_contents($url);
if ($raw === false) {
echo 'failed to donwload ' . $url . "\n";
continue;
}
file_put_contents($dir, $raw);
}
It looks like line
$parts = new SplFileObject($file_tmp);
isn't necessary as well as
$fp = fopen ($destination, 'w+');
file() function reads entire file into array. You just have call trim() on each array element to remove new line from characters. Following code should work properly:
<?php
$save_loc = './';
$urls = file('input.txt');
foreach($urls as $url) {
$url = trim($url);
$destination = $save_loc . basename($url);
$content = file_get_contents($url);
if ($content) {
file_put_contents($destination, $content);
}
}

PHP Write and Read from Text File

I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}

Renaming file with PHP

I am using code that i found on here which works great but the moment i try to access a file in a sub-directory it just doesn't want to work.
It gets a file, creates a temp file to write to, then looks for some text in the file and replaces that text with new text, then saves the updated file, then deletes the temp file.
The below works fine:
$reading = fopen('links.htm', 'r');
$writing = fopen('links.tmp', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('links.tmp', 'links.htm');
} else {
unlink('links.tmp');
}
This doesnt work:
$reading = fopen('path/to/links.htm', 'r');
$writing = fopen('path/to/links.tmp', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('path/to/links.tmp', 'path/to/links.htm');
} else {
unlink('path/to/links.tmp');
}
Any suggestions?
The path is absolute i defined it in the code earlier and use it to create file and write files to but when i want the code above to work in the same way it just doesn't want to.
Also the folders permissions has been set to write and read which also works fine.
Ran the code in the sub folder and works fine but not from the top level directory.
Error reporting is turned off, turned it on now:
The process cannot access the file because it is being used by another process. (code: 32)
So after a week of looking around, testing, breaking and recoding a lot i found a simple way to do this.
Since most of the content is dynamically created as well as the links.htm file, it was quite hard finding where and when the file is accessed since the code accesses about 300 of my clients sites and updates the links file.
Simple fix:
$path = "path/on/server/";
$conn_id = ftp_connect("ftp.testftp.com") or die("Could not connect");
ftp_login($conn_id,"admin","ert456");
$old_file = $path.'links.htm';
$new_file = $path.'_template.htm';
ftp_rename($conn_id, $old_file, $new_file);
$source = fopen($new_file, "w");
$localTarget = "path/to/links.htm";
ftp_fget($conn,$source,$localTarget,FTP_ASCII);
$reading = fopen('path/to/links.htm', 'r');
$writing = fopen('path/to/_template.htm', 'w+');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'::template::')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('path/to/_template.htm', 'path/to/links.htm');
} else {
unlink('path/to/_template.htm');
}
$local_file = "path/to/links.htm";
ftp_put($conn_id, $path, $local_file, FTP_BINARY);
ftp_close($conn_id);
There is probably easier ways to do this but this is what worked for me, hope it helps someone.
PHP will need to have write permissions to that directory in order to write to it. It may be that it has write permissions to the current directory ., but does not have permissions to write to the subdirectory ./path/to/.
Edit: If you get a PHP error, you should include it in your question.
Edit after OP Edit:
That error means that something currently has links.htm opened. I see that you're fclose()ing the file before renaming it, so my guess is that you probably have links.htm open in some other application (e.g. browser or text editor).
Edit #3:
If you do not have one of the links.htm or links.tmp files open in another application, it could be that you're using Windows - in which case the rename() call will execute before the fclose() even though it comes after it in the code. The solution to this is to add a sleep() call after closing the handle:
fclose($reading); fclose($writing);
sleep(1); // this should allow the handle to be properly closed before the rename() call

write the out put on file

I am very new to php, and i have search and put together this script to convert text to csv and write the out put on the file.
$File = "/var/apache2/htdocs/loginS/host.txt";
$Handle = fopen($File,"r");
$Content = fread ($Handle,filesize ($File));
fclose($File);
fclose($Handle);
$Content = explode("\t", $Content);
foreach($Content as $Value) {
//echo $Value."|"; // till this line working
fwrite($save, $Value);
fclose($save);
}
the problem is when I try to write on the file. I got only one line.what is my error.
You are calling fclose() on the file in your loop that is writing records. fclose() closes the file handle so it is no longer valid and cannot be written to.
Move fclose($save); after the } that ends the foreach() with your content.
Also, you could simplify things a bit by calling $Content = file_get_contents($File); since that is what you are doing in effect with fread(). Also, since $File is just a string variable, calling fclose() on it is unnecessary and doesn't do anything. You were correctly closing it by calling fclose() on $Handle. But using file_get_contents() will eliminate the need for both. The only file you would need is the one you were writing to.
Here is an example using the file() function which reads each line of a file into an array.
$file = '/var/apache2/htdocs/loginS/host.txt';
$content = file($file);
$save = fopen('./out.csv', 'w+');
foreach($content as $line) {
$line = rtrim($line, "\r\n"); // remove the newline from $line
$parts = explode("\t", $line);
$lineCsv = implode('|', $parts); // or ',' ?
fwrite($save, $lineCsv . "\n"); // write output to file
}
fclose($save);

Categories