Don't echo things with certain characters - php

I have a php program that looks at a log file and prints it to a page (code below). I don't want the user of said website to be able to look at any line containing a /. I know I could use trim to delete certain characters, but is there a way to delete the entire line? For example, I want to keep something like "Hello" and delete something like /xx.xx.xx.xx connected. All the lines I wish to delete have the same common key, /. Peoples names in said log file have <>s around them, so I must use htmlspecialcharacters
$file = file_get_contents('/path/to/log', true);
$file = htmlspecialchars($file);
echo nl2br($file);
Thanks for your help!
EDIT:
Thanks for all of the answers, currently tinkering with them!
EDIT2:
final code:
<?php
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
$line = htmlspecialchars($line . "\n");
echo nl2br($line);
}
}
?>

Do you mean, like this?
$file = file_get_contents('/path/to/log', true);
// Separate by line
$lines = explode(PHP_EOL, $file);
foreach ($lines as $line) {
if (strpos($line, '/') === false) {
// If the line doesn't contain a "/", echo it
echo $line . PHP_EOL;
}
}
For anyone wondering, PHP_EOL is the PHP constant for "end of line" and promotes consistency between different systems (Windows, UNIX, etc.).

If you are iterating through the file line by line you can check with preg_match if the line contains /character and skip the echo if it does. If not, first split them at new line and iterate over that array.
If you don't want to split the file you can probably use preg_replace with a regexp such as (^|\n).*/.*(\n|$) and replace with empty string.

Use the str_replace function -
http://php.net/manual/en/function.str-replace.php. Alternate solution (before escaping the special characters) -
/* pattern /\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/ = /xx.xx.xx.xx connected */
/* pattern will be replaced with "newtext" */
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines as $line)
$correctline = preg_replace( '/\/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\sconnected/', 'newtext', $line );
echo $correctline;
}

<?php
$file = file_get_contents("/path/to/log", true);
$lines = explode("\n", $file);
foreach ($lines AS $num => $line)
{
if ( strpos($line, "/") === false ) // Line doesn't contain "/"
{
echo htmlspecialchars($line) . "\n";
}
}
?>

Related

Search for string in text file and print after space occur in PHP

This might be an easy one but not for me.
I have this function:
function pingAddress($ip) {
// Read from file
$lines = file('F:\share\result.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $ip) !== false)
echo $line;
}
}
The text file looks like this:
192.168.50.104 UP
192.168.50.105 UP
192.168.50.106 DOWN
192.168.50.107 UP
If I give ip 192.168.50.1 for example it returns all the lines from 192.168.50.1 to 192.168.50.199 and I need it to return only that specific line and if possible only what's after ip: UP or DOWN.
Help would be nice :-)
By using strpos(), you are accepting partial matches, which causes 192.168.50.1 to match all your examples.
Instead, split the line on a space, and check for a full IP match. Then you can return the UP or DOWN part.
function pingAddress($ip) {
// Read from file
$lines = file('F:\share\result.txt');
foreach($lines as $line){
$parts = explode(' ', $line);
if($parts[0] == $ip){
return $parts[1];
}
}
}
echo pingAddress('192.168.50.1'); // nothing returned
echo pingAddress('192.168.50.105'); // UP
Just add a "return;" after "echo $line;" The function stops, after the searched string is found.
function pingAddress($ip) {
// Read from file
$lines = file('F:\share\result.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $ip) !== false)
echo $line;
return;
}
}
You would need to check that there is a space after the IP address to ensure it is the full address and not part of another IP.
I've also changed this so that it reads the file a line at a time, so if it finds the IP address it stops reading there (and returns the UP or DOWN). This saves reading the entire file before searching...
function pingAddress($ip) {
// Add space for search
$ip .= ' ';
$fp = fopen("a.csv", "r");
while ( $line = fgets($fp) )
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $ip) !== false)
return trim(substr($line, strlen($ip)));
}
fclose($fp);
return '';
}

Can I add an image path from a .txt file in a webpage using PHP?

I need to dynamically add in the img src full file path to a file from a .txt file. So far i have been using the below code to populate titles, and descriptions:
< ?php
$myFile = "film_music/feature1.txt";
$lines = file($myFile);//file in to an array<br />
echo $lines[0]; //line 1
? >
The feature file contains all details for movies that will eventually be displayed here:
http://www.londonosophy.com/film_music2.php
Currently the file contains the following rows:
Sightseers (2012)
Dark comedy, featuring Alice Lowe
images/Sightseers-TinaPencil.jpg
Does anyone know php code that can read line X (or line 3 in this case) and dynamically populate the img src="" file path?
Many thanks in advance for your suggestions!
If you need to iterate over lines and need to check if line contains file path (for example, if sometimes there are white lines between blocks and sometimes they are missing), then:
<?php
$myFile = 'film_music/feature1.txt';
$lines = file($myFile);
$needle = 'images/';
$needleLen = strlen($needle);
foreach ($lines AS $line) {
$line = trim($line);
if (substr($line, 0, $needleLen) == $needle) {
echo '<img src="' . $line . '" alt="" />';
}
}
?>
You need to fetch 3rd line of the file every time, because it contains that path of the image.
<?php
global var $raw;
$myFile = "film_music/feature1.txt";
// open file...
$lines = file($myFile);//file in to an array<br />
for($i=2;$i<=no_of_lines;$i+3){
$raw = $lines[$i];
}
// Populate $raw variable where you need.
?>
Use $fh = fopen(...) and loop every line.
while (!feof($fh)) {
$line = fgets($fh);
if ($line === false) {
throw new Exception("File read error");
}
[do your things.]
}
http://www.php.net/manual/en/function.fopen.php
You can read each line of text line as:
$lines=file('file.txt');
$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line however you like
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
if you don't need any special processing, this should do what you're looking for
$lines = file($lines, FILE_IGNORE_NEW_LINES);
may this help you... :)
you can check all line of text file with in_array("you want", $lines) as you desire...if its not dynamically....

Reading text after a certain character in php

Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>

strings comparison in PHP

I feel like the biggest fool on the planet earth. But I am looping through a text file and attempting to compare each line and find the line breaks... You know... "\n". But I can't seem to compare the strings!!!!
Here is what I am doing.
$filename = 'StatesCities.txt';
$file = file($filename);
$matchedLines = array();
foreach($file as $line) {
$matchesLines[] = $line;
if(strcmp($line, "La Mesa") == 0)
{
echo("Yeah");
}
echo($line);
echo("<br />");
}
Are you trying to remove the line breaks? If that's the case then you can explode them.
$file = file_get_contents( $file_path );
$page = explode( "\n", $file );
//Now they're gone
foreach( $page as $line )
{
if( strpos( $line, 'searchfor' ) !== false )
{
//do this
}
}
The strpos is how I usually search in a string, just make sure to use !== which checks for false not false or 0. If the string your looking for has a strpos of 0 ( first character ) it would return a false positive if you don't check for the type with !==. Good luck.
Your question says you're looking for "\n" but your code is looking for "La Mesa". Perhaps you wanted to say
if (strpos($line, "\n"))
?
The file() function will maintain newline characters (\n) in the array that it creates by default. See here for more info; in particular, the flags section. To fix your problem...
Instead of this:
$file = file($filename);
Use this:
$file = file($filename, FILE_IGNORE_NEW_LINES);

Any function to take an array of strings and return a CSV line?

I have an array of strings and want a way to create a CSV line from them. Something like:
$CSV_line = implode(',',$pieces);
Will not work as the pieces may contain comma and double quotes.
Is there a PHP built in function that takes the pieces and return a well formatted CSV line?
Thanks,
Roge
If you want to write that line to a file, you can use fputcsv
Using the streams functionnality of PHP, it should be possible to write to a variable -- indeed, there's one guy in the comments of str_getcsv who posted his implementation of str_putcsv :
<?php
function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
// Open a memory "file" for read/write...
$fp = fopen('php://temp', 'r+');
// ... write the $input array to the "file" using fputcsv()...
fputcsv($fp, $input, $delimiter, $enclosure);
// ... rewind the "file" so we can read what we just wrote...
rewind($fp);
// ... read the entire line into a variable...
$data = fread($fp, 1048576); // [changed]
// ... close the "file"...
fclose($fp);
// ... and return the $data to the caller, with the trailing newline from fgets() removed.
return rtrim( $data, "\n" );
}
?>
Note : this code is not mine -- it's a copy-paste of the one posted by Ulf on php.net.
You could even write a Class to do this
class CSV_ARRAY {
static public function arr_to_csv_line($arr) {
$line = array();
foreach ($arr as $v) {
$line[] = is_array($v) ? self::arr_to_csv_line($v) : '"' . str_replace('"', '""', $v) . '"';
}
return implode(",", $line);
}
static public function arr_to_csv($arr) {
$lines = array();
foreach ($arr as $v) {
$lines[] = self::arr_to_csv_line($v);
}
return implode("\n", $lines);
}
}
you could useit like this
$csvlines = CSV_ARRAY::arr_to_csv_line($myarray);
file_put_contents($csvlines,"mycsv.csv");
thats it ;-)
As far as I know there is no such built in function. The one I'm aware of is fputcsv that does exactly what you want
but it does not return the CSV line, but writes it to a file.
<?php
$pieces = array (
'a,b,c,d', // contains comma.
'"1","2"' // contains double quotes.
);
$fp = fopen('file.csv', 'w');
fputcsv($fp, $pieces); // "a,b,c,d","""1"",""2""" written
fclose($fp);
?>
Most of the times you want create the line of CSV and write it to the file. So the above function should suffice.
I'd written one such function for PHP4 as it does not support fputcsv. I'll share it with you:
// If a value contains a comma, a quote, a space, a tab, a newline, or a linefeed,
// then surround it with quotes and replace any quotes inside it with two quotes
function make_csv_line($values)
{
// iterate through the array ele by ele.
foreach($values as $key => $value)
{
// check for presence of special char.
if ( (strpos($value, ',') !== false) || (strpos($value, '"') !== false) ||
(strpos($value, ' ') !== false) || (strpos($value, "\t") !== false) ||
(strpos($value, "\n") !== false) || (strpos($value, "\r") !== false))
{
// if present, surround the ele in quotes..also replace
// already existing " with ""
$values[$key] = '"' . str_replace('"', '""', $value) . '"';
}
}
// now create the CSV line by joining with a comma, also put a \n at the end.
return implode(',', $values) . "\n";
}
Here is a simpler fputcsv implementation:
$stdout = fopen('php://output','w'); // 'stdout' is for CLI, 'output' is for Browser
fputcsv($stdout, array('val,ue1','val"ue2','value3','etc'));
fflush($stdout); // flush for fun :)
fclose($stdout);
I snarfed this elswhere on SO and posted here for faster reference, please bump/credit the original posting:
Is my array to csv function correct?
Well, the thing is, there is no well formatted CSV. For instance, Open Office uses the semicolon (;) as default delimiter, while Excel expects it to be a comma (,). But fact is, no standard exists.
Assuming the Array looks something like this:
Array
0 => Some string
1 => Some other string, with comma
2 => And a third one with "double quotes"
);
You could either use implode with a different delimiter, e.g.
$delimiter = chr(9); // Tab
$delimiter = ';' // Semicolon. Excel's default
$delimiter = '|' // Pipe
$delimiter = "','"; // Comma plus Single Quote
If that is not working, run the String array through array_filter first and change the double quotes and comma via callback to whatever you think they should be, before exploding with just a comma delimiter:
$csv = implode(',' array_filter($array, 'my_csv_prepare'));
But keep in mind, this does not guarantee your consuming application to be able to read the CSV. It really depends on how they implemented CSV parsing. Like I said: no standard.

Categories