PHP Cant read file with special chars - php

I'm loading a file by this script:
$hFile = fopen($sFile, "r");
$sContent = "";
while(!feof($hFile)) {
$sContent .= fread($hFile, 4096);
}
fclose($hFile);
It works as it should do, but i tried to load a file called test.txt
which contains the following string: <>863b?)(/&(§&/))!)!=WLKM! K!*ÜQWW!W3³³w2_:LPE
The variable $sContent now doesn't contain anything.

$html = mb_convert_encoding($html, "UTF-8");
Do this before writing to the file in the first place.

Related

Overwriting content of PHP file

I want to ovewrite some labeled data in PHP Config file which looks like this:
define("__dbhost__", '{DB_HOST}');
define("__dbname__", '{DB_NAME}');
define("__dbuser__", '{DB_USER}');
define("__dbpass__", '{DB_PASS}');
define("__dbport__", '{DB_PORT}');
So the file is really simple.
The way i'm trying to replace data is by:
$searchF = array('{DB_HOST}','{DB_NAME}','{DB_USER}','{DB_PASS}', '{DB_PORT}');
$replaceW = array('a','c','d','b','a');
$fname = "../app/config/database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace($searchF, $replaceW, $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
But once finished and after I open the file I get
Resource id #16
Inside of it.
What's going on and why typical str_replace won't work for this case?
Just read the entire file into a string:
$searchF = array('{DB_HOST}','{DB_NAME}','{DB_USER}','{DB_PASS}', '{DB_PORT}');
$replaceW = array('a','c','d','b','a');
$fname = "../app/config/database.php";
$content = file_get_contents($fname);
$content = str_replace($searchF, $replaceW, $content);
file_put_contents($fname, $content);
Read file into string
Replace on that string
Write string to file

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 fgets() won't work unless it's implemented with a variable?

I'm writing some code that can read in from a .txt file a display it on a webpage.
I had problems in my initial code, in that it would read in any text and it would erase whatever was in the document.
My original code:
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$line = fgets($input);
fclose($input);
return $line
}
It only started working once I put in a While loop to go through EVERY LINE
function readIn(){
$input = fopen("input.txt", "r"); //Open the file, save opened file in input
$fullText = ""; //Variable full text
while(!feof($input)){
$line = fgets($input);
$fullText = $fullText . $line;
}
fclose($input);
return $fullText;
}
echo readIn();
Use "file_get_contents" to read an entire file into a variable, and then output in whatever fashion you choose.

PHP editing Microsoft Word document str_replace and preg_replace don't work

Assume, I've got MSWord file source.doc with next content "Content of Microsoft Word file".
For example, I'd like to open it via PHP and replace word "Microsoft" to "Openoffice" and save the result into result.doc.
Here is the code using preg_replace:
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = preg_replace( '/Microsoft/i', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
Or using str_replace:
$content = file_get_contents( SOMEPATH . '/source.doc' );
$new_content = str_replace( 'Microsoft', 'Openoffice', $content );
file_put_contents( SOMEPATH . '/target.doc', $new_content );
None of them doesn't work. Code runs without any exceptions, but target.doc is the same as source.doc. Replacement not performs.
I've tried a lot of different reciepts, such as regular expression modificators, iconv and so on, but nothing helps.
var_dump of $content shows raw structure of source.doc that is full of unusual characters and as I suppose some of it stops str_replace or preg_replace scanning. Can't figure out which char is it and what should I do if I'll find it.
var_dump of $new_content is identical to $content.
Thanks forward for any help!
If you have a DOCX file you need to replace something in, its basically a zipped up xml archive.
Here's an example on how to replace the word "Microsoft" with "Openoffice" in a DOCX file.
$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
if ($zip->open($wordDoc) === TRUE) {
//Read contents into memory
$oldContents = $zip->getFromName($fileToModify);
//Modify contents:
$newContents = str_replace('Microsoft', 'Openoffice', $oldContents);
//Delete the old...
$zip->deleteName($fileToModify);
//Write the new...
$zip->addFromString($fileToModify, $newContents);
//And write back to the filesystem.
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
Hope this helps!
I think this is what you are looking for :) http://phpword.codeplex.com/ since doc files are not ordinary text files (try opening one with notepad..you'll get my point)

How to correctly use the PHP function 'fgets'?

I assume I'm using the fgets() wrong. I'm tring to open a PHP file and then try to match a line in that file with a variable I create. If the line does match then I want to write/insert PHP code to the file right below that line. Example:
function remove_admin(){
$findThis = '<tbody id="users" class="list:user user-list">';
$handle = #fopen("../../fns-control/users.php", "r"); // Open file form read.
if ($handle) {
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 479); // Read a line.
if ($buffer == '<tbody id="users" class="list:user user-list">') // Check for string.
{
Now I want to write PHP code to the file, starting on line 480. How can I do that?
Useful information may be: IIS 6 and PHP 5.2.
Try this:
<?php
function remove_admin(){
$path = "../../fns-control/users.php";
$findThis = '<tbody id="users" class="list:user user-list">';
$phpCode = '<?php echo \'hello world\'; ?>';
#Import file to string
$f = file_get_contents($path);
#Add in the PHP code
$newfile = str_replace($findThis, $findThis . $phpCode, $f);
#Overwrite the existing file
$x = fopen($path, 'w');
fwrite($x, $newfile);
fclose($x);
}

Categories