how to display context of .cfg file in php? - php

I have a .cfg file which contains some code. I would like to display the whole .cfg in php page. Code for my_config.cfg is here:
# ATA/IDE/MFM/RLL support
#
account_name=changl
#
# IDE, ATA and ATAPI Block devices
#
CONFIG_BLK_DEV_IDE=y
CONFIG_BLK_DEV_IDEDISK=y
CONFIG_BLK_DEV_IDECD=n
Now I wrote a php code which checks the condition and display what i write in echo. But instead of that I want to display everything from the file. Here is the php code:
<?php
$config_file = "my_config.cfg";
$comment = "#";
$fp = fopen($config_file, "r");
while (!feof($fp)) {
$line = trim(fgets($fp));
if ($line && !preg_match("/^$comment/", $line)) {
$pieces = explode("=", $line);
$option = trim($pieces[0]);
$value = trim($pieces[1]);
$config_values[$option] = $value;
}
}
fclose($fp);
if ($config_values['account_name'] == "changl")
echo "account_name is changl";
else
echo "account_name is not changl";
?>
The code is working properly. but I want to display the data in the file. Please any help is appreciated.

The easiest way is to use parse_ini_file():
$config_values = parse_ini_file('my_config.cfg');
After that you can work with $config_values like with any other regular array

Related

Delete file specific file content between a characters using php [duplicate]

This question already has answers here:
RegEx to remove /** */ and // ** **// php comments
(3 answers)
Closed 4 years ago.
I need to delete a particular file content that is between these two characters /* & */ using PHP. The file from which I am trying to remove these comments is very large and includes a large data set, So optimized solution will be appreciated.
Example content:
/*SOME TEXT HERE
*/ 12314
So, the final file should contain only
1234
Here is the method that keeps on running until we got the comments string. Please note that the comments are only at one place in the file and they are always on the top of the file. Please let me know how can I delete those lines on which match the comments condition?
Below is the method that I updated.
$reading = fopen(public_path('file.csv'), 'r');
$writing = fopen(public_path('file.csv'), 'w');
$counter = 0;
$line = "";
$no_of_lines = 0;
while (!feof($reading) && $counter != 2) {
$new_line = fgets($reading);
if ($matched_string = strstr($new_line, "/*")) {
$line = $line . $matched_string;
$counter++;
} elseif ($matched_string = strstr($new_line, "*/")) {
$line = $line . $matched_string;
$counter++;
} else {
$line = $line . $new_line;
fwrite($writing, "");
}
$no_of_lines++;
}
fclose($writing);
fclose($reading);
First open the file but one line at a time to save memory:
<?php
$reading = fopen('myfile', 'r');
$writing = fopen('newfile', 'w');
while (!feof($reading)) {
$line = fgets($reading);
// We will put the removal logic in here
fputs($writing, $line);
}
fclose($reading);
fclose($writing);
For the removal, use some regex.
<?php
$line = preg_replace('#\/\*.+\*\/#', '/* */', $line);
You can see this working here https://3v4l.org/XmltD
If you don't want the /* either, just change the replace call to this:
$string = preg_replace('#\/\*.+\*\/#', '', $string);

php - one time access by looking up serial in a .dat file

i've now written this short script.
It records a serial or token number, checks to see if its in a .dat file, and allows access if its present. Otherwise it denies access to the site.
It also removes the token from the file once it has been redeemed as it were.
However, when i add multiple tokes in the dat file, the code doesn work properly. It only works with a single entry. How would i make it work for multiple entries.
im thinking of maybe implementing some sort of array somewhere? or explode?
index.php
require_once "married.php";
session_start();
$url_request = (isset($_SERVER['HTTPS']) ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip = $_SERVER['REMOTE_ADDR'];
$token = substr($url_request,45);
$_SESSION["cookie"] = $token;
$tk = $_SESSION["cookie"];
$ips = array();
$page = file("urls.dat");
foreach($page as $line)
{
array_push($ips, $line);
}
if(in_array($tk, $ips))
{
//header("Location: mysite.co.uk");
echo "<title>My Site</title>Here is my site";
$file = fopen("ip_match.dat","a");
fwrite($file,$tk . " " . $ip . "\r\n");
fclose($file);
$oldMessage = $_SESSION["cookie"];
$deletedFormat = "";
$str=file_get_contents('urls.dat');
$str=str_replace("$oldMessage", "$deletedFormat",$str);
file_put_contents('urls.dat', $str);
exit;
} else {
echo ("<title>404 Not Found</title>
<h1>Not Found</h1>The requested URL was not found on this server.
<br>
<br>
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. test");
exit;
}
urls.dat
1089yht
url: http://mmmmmmmmmmmmm.co.uk/url/index.php?key=1089yht
ps. Happy Holidays all!
Look at JSON. You could do something like this:
$tokens = ['foo', 'bar'];
file_put_contents('urls.json', json_encode($tokens));
// and then you can decode it back
// returns ['foo', 'bar']
$decodedTokens = json_decode(file_get_contents('urls.json'));
If you still want to use simple text file, you could save every record at new line and then load line by line.
$tokens = [];
while(! feof($file)) {
$line = fgets($file);
// or save to array
$tokens[] = $line;
}
fclose($file);
try
$str = preg_replace("/{$oldMessage}/", $deletedFormat, $str, 1);
Instead of
$str=str_replace("$oldMessage", "$deletedFormat",$str);
Because: str_replace replaces everything.
preg_replace lets you limit how many replacements.

fopen multiple files in php

I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php

Combining two text files with PHP - ForEach loops

I'm completely puzzled where to even start on this, but I need to provide a list of keywords in file A and then the same in list B.
With these too files I want to append the lines in A foreach line in file B
For example:
File A:
line1
line2
line3
File B:
test1
test2
test3
Output to a combined.txt file:
line1test1
line2test1
line3test1
line1test2 ... and so on
If you could provide me the portions of the script to research, a sample script, or even a working way to do it. I would greatly appreciate it.
Per request, here is my sample code:
<?php
$file1 = 'keywords.txt';
$file2 = 'topics.txt';
$combined = 'combined.txt';
$keywords = fopen("keywords.txt", "rb");
$topics = fopen("topics.txt", "rb");
$front = explode($topics);
$back = explode($topics);
while (!feof($keywords) ) {
file_put_contents($combined, . $front ."". $back . "\n");
fclose($keywords & $topics);
}
?>
Hope this helps. Comments are sprinkled throughout the code, which I hope is sufficient explanation as to what I'm doing.
<?php
// Open keywords file for reading
$keywords_file = 'keywords.txt';
$keywords_fh = fopen($keywords_file, 'r');
// Get line by line from keywords file, push into $keywords array
// Make sure to trim each line from fgets, to strip off \n at end.
$keywords = array();
while ($line = trim(fgets($keywords_fh))) {
array_push($keywords, $line);
}
fclose($keywords_fh);
// Open topics file for reading
$topics_file = 'topics.txt';
$topics_fh = fopen($topics_file, 'r');
// Get line by line from topics file, push into $topics array
// Make sure to trim each line from fgets, to strip off \n at end.
$topics = array();
while ($line = trim(fgets($topics_fh))) {
array_push($topics, $line);
}
fclose($topics_fh);
// Open combined file for writing
$combined_file = 'combined.txt';
$combined_fh = fopen($combined_file, 'w');
// Iterate through each keyword.
// For each iteration, iterate through each topic.
// Write the concatenation of keyword and topic to file.
foreach ($keywords as $keyword) {
foreach ($topics as $topic) {
fwrite($combined_fh, "$keyword$topic\n");
}
}
fclose($combined_fh);
Here are some links to PHP documentation for some of the key functions I used:
fopen
trim
fgets
fwrite
fclose
$f1 = explode("\n",file_get_contents("fileA.txt"));
$f2 = explode("\n",file_get_contents("fileB.txt"));
foreach ($f1 as $key => $value) {
$f3[] = $value.$f2[$key];
}
file_put_contents("fileC.txt", implode("\n",$f3));

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
?>

Categories