How to open file with special characters in the name - php

In PHP, how can I open a file that has special characters in the name?
The name is similar to iPad|-5542fa5501f31.log
Per another forum, I've tried:
$logid = str_replace(" ", "\x20", $_GET['logid']);
$logid = str_replace("|", "\x7C", $logid);
To massage the name, but that doesn't work for me either.
I've also already tried:
$dst_file = escapeshellarg($dst_file);
And of course started out with just straight:
$logid = $_GET['logid'];
The initial file was created by a PHP script on a Linux system. I'm confused why a PHP script can write a file name like that, but can't open it for reading.
Here's my current code:
$logid = str_replace(" ", "\x20", $_GET['logid']);
$logid = str_replace("|", "\x7C", $logid);
$logdate = str_replace("-", "/", $_GET['date'])."/";
$dst_file = $uploads_dir.$logdate.$logid.'.log';
// read the data from the log file
echo "<pre>\n";
if (file_exists($dst_file)) {
$file_handle = fopen($dst_file, "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
if (strlen($line) < 3) continue;
echo $line;
}
fclose($file_handle);
} else {
echo $dst_file." does not exist\n";
}
echo "</pre>\n";

The only thing I found was to rename the file then open. The problem is no PHP functions so I tried system commands. None worked. The ftp RNTO command will rename it. But it would be much better to filter out "special characters" when the file is saved.

Somebody on another forum had suggested using popen, so I tried this, and it works:
$logid = $_GET['logid'];
$logdate = str_replace("-", "/", $_GET['date'])."/";
$dst_file = escapeshellarg($uploads_dir.$logdate.$logid.'.log');
echo "<pre>\n";
$handle = popen("cat ".$dst_file, 'r');
while(!feof($handle)) {
$line = fgets($handle);
if (strlen($line) > 3) {
echo $line;
}
ob_flush();
flush();
}
pclose($handle);
echo "</pre>\n";
The exact same code, except using fopen/fclose (no cat) will not work.

I was struggling to open the file "2017-09-19_Comisión_Ambiental.jpg", that "ó" was giving me this error :
file_get_contents ... failed to open stream: No such file or directory in ...
So I used utf8_decode on the filename and it worked :
$data = file_get_contents( utf8_decode( $filename ) );
I know this is an old question, there's even an accepted answer, I just posted it because it might help somebody.

Related

Search for text in a 5GB+ file then get whole line

I want to search for the text Hello (example) in a TXT file whose size is 5GB+ then return the whole line.
I've tried using SplFileObject but what I know is that the line number is required to use SplFileObject, like that:
$linenumber = 2094;
$file = new SplFileObject('myfile.txt');
$file->seek($linenumber-1);
echo $file->current();
But as previously mentioned, I want to search for a string then get the whole line, I don't know the line number.
Any help would be appreciated.
this should work:
<?php
$needle = 'hello';
$count = 1;
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$pos = strpos($line, $needle);
if ($pos !== false) {
echo $line . PHP_EOL;
echo "in line: ".$count . PHP_EOL;
break;
}
$count++;
}
fclose($handle);
} else {
// error opening the file.
}
This is the answer that I can use. Thanks a lot to #user3783243
For Linux:
exec('grep "Hello" myfile.txt', $return);
For Windows:
exec('findstr "Hello" "myfile.txt"', $return);
Now $return should contain the whole line.
Unfortunately, this doesn't work if exec() and system() functions are disabled by your server administrator in the php.ini file. But for me it works fine.
If someone have a better solution I'd be glad to know it :)

Fwrite PHP - How to output full loop to file?

I have created a script that's working great, but I want to take it to the next level and create a file for this information automatically. The problem is that when I add my looped elements to using fwrite, it only writes the first entry to the file.
Sample code:
$totallines=count($lines);
$i=0;
foreach($lines as $line) {
$i=$i;
$trimmed = trim($line);
$linesgetdomain = explode('/',$trimmed);
$domain = $linesgetdomain[2];
$qmark = "?";
$front301qmark = "Front Part ";
$end301qmark = " End Part";
$lastpartqmark = "Last Part $domain";
if (strpos($trimmed,$qmark) !== false) {
strstr($trimmed, '?');
echo $front301qmark;
echo substr(strstr($trimmed, '?'), strlen('?'));
echo $end301qmark;
echo "<br>";
echo $lastpartqmark;
echo "<br>";
} else {
What I tried (placing this before } else {):
$fpqmark = fopen('test.txt', 'w');
fwrite($fpqmark, $front301qmark);
fwrite($fpqmark, substr(strstr($trimmed, '?'), strlen('?')));
fwrite($fpqmark, $end301qmark);
fwrite($fpqmark, PHP_EOL);
fwrite($fpqmark, $lastpartqmark);
fwrite($fpqmark, PHP_EOL);
fclose($fpqmark);
How can I write the entire loop to a file instead of just the first line? The output displays properly in normal format, but not when writing to a file.
Apologizes beforehand if this is a basic question. I'm new to PHP and my understandings of certain concepts are a bit vague. Sort of surprised I even managed to get this script to work. (This is only a small part of it, but if I can learn how to do this, I should be able to do the rest).
instead of using write,
$fpqmark = fopen('test.txt', 'w');
Use apend,
$fpqmark = fopen('test.txt', 'a');
The it will resolve your problem.

php zip file not created despite no erros, no permission problems, no empty folders, no

Okay. Every file exists, is readable, and is writable. ZIP produces no errors, and outputs: "numfiles: 140 status:0".
the code reads a log, checks for specific text, then imports a number of images into a zip folder. everything runs great except the zip folder is always empty. I've read a lot of threads about this, and they all were resolved by changing permissions, modifying paths and checking for read/write/exist/errors. but... nothing has worked. whats up?
<?php
$file = fopen("log.log", "r") or exit("Unable to open file!");
$zip = new ZipArchive();
$filename = "E:/Web Sites/whatever/order_stream/images.zip";
$try_file = $zip->open($filename,ZIPARCHIVE::OVERWRITE);
if ($try_file !== true) {
exit("cannot open <$filename>\n");
}
while(!feof($file)) {
$line = fgets($file);
$results = explode(": ", $line);
if ($results[0] == "Copying" || $results[0] == "File already exists, overwriting") {
$file_name = substr($results[1],19);
$to_zip = "E:/Web Sites/whatever/catalog/pictures/".$file_name;
$to_zip = trim($to_zip);
if (file_exists($to_zip)) {
$zip->addFile($to_zip);
}
}
}
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
fclose($file);
?>
The ZipArchive::addFile() method accepts the path to the file as its first parameter, but not all paths are created equal. addFile() method silently rejects (bug?) the file and you never know what went wrong. An alternative approach would be:
// $zip->addFile($file);
$content = file_get_contents($file);
$zip->addFromString(pathinfo ( $file, PATHINFO_BASENAME), $content);
In addition to getting the code working, file_get_contents() also generates decent error messages if you made an error in the path. In this example
$file = $full_directory_path_ending_with_slash.$filename;
Since in the above question, you have the parts in your fingers, the code could simply become:
$content = file_get_contents($to_zip);
$zip->addFromString($filename, $content);

How can I add multiple strings to one text file, and read the all?

I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}

code was working, but suddenly stopped working

This code opens a text file, then checks to see if each word in the text file
Exists in a another large 2MB dictionary file.
If it does exist, it stores the line from the dictionary file into a variable.
The code was working, but then began to generate Server 500 errors, and now
It only lists about 7 matches and then loads nothing forever.
It used to list the 1000's of matches and then stop.
$file_handle = fopen("POSdump.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$words= explode(" ", $line );
foreach ($words as $word) {
$word = preg_replace('#[^\w+>\s\':-]#', ' ', $word);
$subwords= explode(" ", $word );
$rawword = $subwords[0];
$poscode = $subwords[1];
$rawword = strtoupper($rawword);
$handle = fopen("dictionary.txt","r"); //
if ($handle) {
while (!feof($handle))
{
$buffer = fgets($handle, 4096);
if (preg_match('#\b'.$rawword.'\b#',$buffer)) {
echo $rawword;
echo "</br>";
}
}
}
}
}
?>
Try closing the file when you are done.
This seems to be a memory_limit error. use ini_set('memory_limit', -1) before starting the process.

Categories