How can one retrieve a varibale for instance alias /MyDirectory/ "C:/MyDirectory/MyDirectory/" from http.conf using PHP. Is there an easier way than to open http.conf and read it line by line?
Thanks
You could always use fgets() to read single lines from a file. But why would you want to tinker with your server settings from your program?
$handle = fopen('httpd.conf', 'r');
if($handle) {
while($buffer = fgets($handle) !== false) {
// do something with the data you read
}
if (!feof($handle)) {
echo 'An error occured';
}
fclose($handle);
}
Related
I need a php script that will open an external php file (from the same server folder), go through it line by line, and then normally display the page in the browser, as it would by just opening the external php page directly.
I need to open the external file line by line, so I can do some processing on the content of the file before showing it.
My current code is:
<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
echo "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
?>
This works, and the page is displayed, but any php code in the original external file is not honored - it is written out as text, and not rendered by the browser.
I need the external file to fully display, just as it would if I opened the file (in this case "test.php") by itself.
Other questions I have seen on SO deal with opening or displaying a full file at once, but I need to loop through my file and do some processing on the contents first, so need to evaluate it line by line.
Any ideas would be appreciated.
Thanks
I would save the changes to a temporary file, and then include it.
<?php
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
$newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
// temporary file name
$temp_file = tempnam(sys_get_temp_dir(), 'myfile').".php";
// save modified code
file_put_contents($temp_file, $newCode);
// include modified code
include $temp_file;
// delete file
unlink($temp_file);
?>
Retrieve the content, process it, keep it in memory then eval() it:
<?php
$newCode = "";
$handle = fopen("test.php", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line here, and change if needed
//$line = myLineProcess($line);
$newCode .= "$line\n";
}
fclose($handle);
}
else {
// error opening the file.
}
//run the code
eval('?>'.$newCode.'<?php;');
?>
I am trying to read the contents of a file line by line with Laravel.
However, I can't seem to find anything about it anywhere.
Should I use the fopen function or can I do it with the File::get() function?
I've checked the API but there doesn't seem to have a function to read the contents of the file.
You can use simple PHP:
foreach(file('yourfile.txt') as $line) {
// loop with $line for each line of yourfile.txt
}
You can use the following to get the contents:
$content = File::get($filename);
Which will return a Illuminate\Filesystem\FileNotFoundException if it's not found. If you want to fetch something remote you can use:
$content = File::getRemote($url);
Which will return false if not found.
When you have the file you don't need laravel specific methods for handling the data. Now you need to work with the content in php. If you wan't to read the lines you can do it like #kylek described:
foreach($content as $line) {
//use $line
}
You can use
try
{
$contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
die("The file doesn't exist");
}
you can do something like this:
$file = '/home/albert/myfile.txt';//the path of your file
$conn = Storage::disk('my_disk');//configured in the file filesystems.php
$stream = $conn->readStream($file);
while (($line = fgets($stream, 4096)) !== false) {
//$line is the string var of your line from your file
}
You can use
file_get_contents(base_path('app/Http/Controllers/ProductController.php'), true);
$tmpName = $request->file('csv_file');
$csvAsArray = array_map('str_getcsv', file($tmpName));
I have an issue I can't seem to find the solution for. I am trying to write to a flat text file. I have echoed all variables out on the screen, verified permissions for the user (www-data) and just for grins set everything in the whole folder to 777 - all to no avail. Worst part is I can call on the same function from another file and it writes. I can't see to find the common thread here.....
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
if (!$Handle = fopen($File, 'w')) {
return "Cannot open file ($File)";
exit;
}/*
if(!flock($Handle, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain file lock';
exit(-1);
}*/
if (fwrite($Handle, $NewContents) === FALSE) {
return "Cannot write to file ($File)";
exit;
}else{
return $NewContents;
}
}else{
return "<p align=\"center\">There was an issue saving your settings. Please try again. If the issue persists contact your provider.</p>";
}
}
Try with...
$Handle = fopen($File, 'w');
if ($Handle === false) {
die("Cannot open file ($File)");
}
$written = fwrite($Handle, $NewContents);
if ($written === false) {
die("Invalid arguments - could not write to file ($File)");
}
if ((strlen($NewContents) > 0) && ($written < strlen($NewContents))) {
die("There was a problem writing to $File - $written chars written");
}
fclose($Handle);
echo "Wrote $written bytes to $File\n"; // or log to a file
return $NewContents;
and also check for any problems in the error log. There should be something, assuming you've enabled error logging.
You need to check for number of characters written since in PHP fwrite behaves like this:
After having problems with fwrite() returning 0 in cases where one
would fully expect a return value of false, I took a look at the
source code for php's fwrite() itself. The function will only return
false if you pass in invalid arguments. Any other error, just as a
broken pipe or closed connection, will result in a return value of
less than strlen($string), in most cases 0.
Also, note that you might be writing to a file, but to a different file that you're expecting to write. Absolute paths might help with tracking this.
The final solution I ended up using for this:
function ReplaceAreaInFile($AreaStart, $AreaEnd, $File, $ReplaceWith){
$FileContents = GetFileAsString($File);
$Section = GetAreaFromFile($AreaStart, $AreaEnd, $FileContents, TRUE);
if(isset($Section)){
$SectionTop = $AreaStart."\n";
$SectionTop .= $ReplaceWith;
$NewContents = str_replace($Section, $SectionTop, $FileContents);
return $NewContents;
}else{
return "<p align=\"center\">There was an issue saving your settings.</p>";
}
}
function WriteNewConfigToFile($File2WriteName, $ContentsForFile){
file_put_contents($File2WriteName, $ContentsForFile, LOCK_EX);
}
I did end up using absolute file paths and had to check the permissions on the files. I had to make sure the www-data user in Apache was able to write to the files and was also the user running the script.
As I start the process of writing my site in PHP and MySQL, one of the first PHP scripts I've written is a script to initialize my database. Drop/create the database. Drop/create each of the tables. Then load the tables from literals in the script.
That's all working fine! Whoohoo :-)
But I would prefer to read the data from files rather than hard-code them in the PHP script.
I have a couple of books on PHP, but they're all oriented toward web development using MySQL. I can't find anything about reading and writing to ordinary files.
Yes, I know there's a gazillion questions here on stackoverflow about reading TXT files, but when I look at each one, they're for C or C# or VB or Perl. I'm beginning to think that PHP just can't read files :-(
All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:
program readfile;
handle = open('myfile.txt');
data = read (handle);
while (not eof (handle)) begin
display data;
data = read (handle);
end;
close (handle);
end;
I will also need to write files on the server when I get to the part of my site where people upload avatars, and save them as JPG or GIF files. But that's for later.
Thanks!
From the PHP manual for fread():
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
EDIT
per the comment, you can read a file line by line with fgets()
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:
echo file_get_contents('/path/to/file.txt');
Yes that brief, see file_get_contents, you normally don't need a loop:
$file = new SPLFileObject('/path/to/file.txt');
foreach($file as $line) {
echo $line;
}
Well, since you're asking about resources on the subject, there's a whole book on it in the PHP.net docs.
A basic example:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Why you not read php documentation about fopen
$file = fopen("source/file.txt","r");
if(!file)
{
echo("ERROR:cant open file");
}
else
{
$buff = fread ($file,filesize("source/file.txt"));
print $buff;
}
file_get_contents does all that for you and returns the text file in a string :)
You want to read line by line? Use fgets.
$handle = #fopen("myfile.txt", "r");
if ($handle) {
while (($content = fgets($handle, 4096)) !== false) {
//echo $content;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
I've been struggling with writing a single string into a file.
I'm using just a simple code under Slackware 13:
$fp = fopen('/my/absolute/path/data.txt', 'w');
fwrite($fp, 'just a testing string...');
fclose($fp);
The file gets created (if it's not already created) but it's empty ?!
The directory in which this file is written is owned by apache's user & group (daemon.daemon) and has 0777 permissions.
This has never happened to me before. I'm curious what's the reason I'm not able to write inside the file ?
Thanks in advance.
Try $ df -h
It probably means your disk is full.
In my opinion you could check the return values:
$fp = fopen('/my/absolute/path/data.txt', 'w');
// $fp -> manual: "Returns a file pointer resource on success, or FALSE on error."
if ($fp) {
$bytes_written = fwrite($fp, 'just a testing string...');
if ($bytes_written) {
echo "$bytes_written bytes written!\n";
} else {
echo "Error while writing!\n"
}
$success = fclose($fp);
if ($success) {
echo "File successfully closed!\n";
} else {
echo "Error on closing!\n";
}
} else {
echo "No filepointer ressource!\n";
}
I suggest using file_put_conents($file_name, $file_cotents);
And to retrieve content: file_get_contents($file_name);
Code looks cleaner too.
http://php.net/manual/en/function.file-put-contents.php and
http://www.php.net/manual/en/function.file-get-contents.php
Could be something is happening to the script/file before the file is closed. Check if there are any other processes that try to access the file (you can use lsof). Also try writing to a new file to see if the same thing occurs.
Also, check the return value on fclose() to make sure the file is being closed successfully.