Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am working on a project which calls many php files via <?php include 'filename'; ?>
What I want to do is I want a php function or code that replaces all include occurences with the actual file, so that all my 6-7 files are converted into one single PHP file. I have to distribute it to many people, so having a single PHP file would be good in that context. Calling that php file would create a new php file with all the included files.
I want to ship my full project in a single file, just as adminer does !
Any idea how to do it ?
For example :-
...php-code...
<?php
include 'dologin.php';
?>
...php code...
would be converted to :-
...php code...
function dologin();{
...(dologin.php file)...
...php code...
You don't want to use include() here, what you essentially want to do is take a bunch of files and combine them into one. There's no need to actually parse the files as you go, you just need to open them, read until the end, and stick what you got into another file - repeating until done.
Something like this:
<?php
$sources = array('file1.php', 'file2.php', 'file3.php');
$out = fopen('final.php', 'w+');
if ($out === false)
die('Could not open output file');
foreach($sources as $source) {
$buff = file_get_contents($source);
fwrite($out, $buff);
}
fclose($out);
?>
Notes:
I do very little error checking here. What happens if you can't open one of the source files, or the length of what you read is wildly different from what you expect?
I do very little error checking here. What happens if fwrite() fails?
I do very little error checking here. Is it safe to just keep appending as I do? Should newlines be injected after each file is written to the output file? Are you sure you won't end up with a missing ?>
I do very little error checking here. No editor is going to accidentally save an input file with a byte-order-mark at the beginning?
You'll of course need to handle doing something with the generated file, and unlinking it once done (though the flags sent to fopen() will truncate it, which is why I went with that family of functions, aside from the convenience of file_get_contents()). Check the manual for more info on how they work.
Honestly, though - depending on your platform, a simple shell script would probably suffice. I'm pretty sure this is what you're trying to do from the extra info you edited into your question.
This is what I exactly wanted. Please improve this php code if you can.
<?php
$a = file_get_contents("sample file");
$match = "/include '.*';/";
preg_match_all($match, $a, $matches);
foreach($matches['0'] as $b)
{
$c = explode("'", $b);
$c = $c['1'];
$temp = file_get_contents($c);
if(preg_match("/<?php/", $temp))
{
$a = str_replace($b, "?>". file_get_contents($c) . " \n ?>\n<?php \n", $a);
}
else
{
$a = str_replace($b, "?>". file_get_contents($c) . "\n<?php \n", $a);
}
}
file_put_contents("combined.php", $a); ?>
I understood that You want to integrate the included file into a function.
I never thought of this question before because it's useless, but maybe you have some "unknown" reasson behind that, so i have to answer.
Here is how:
dologin.php
<?php
... php code
?>
the function:
function dologin(){
global $variable1;
global $variable2;
// paste php code from the dologin.php file here
}
NOTE:
change $variable1 and $variable2 to the variable that may be included from another file in your main file that you're trying to use the function in, if these variables are getting used in the function ithout doing this you'll face the variables scope problem.
That's it now you have a function instead of a PHP file.
Try this...
Note I haven't had a chance to test this but get_included_files gives you everything thats included then you can just build a new file with the contents of all of them.
<?php
...All the include statements ....
$my_includes = get_included_files ();
$file = "everything.php"
file_put_contents($file, "<?PHP");
foreach($my_includes as $included){
$file_contents = file_get_contents($included);
file_put_contents($file, $file_contents, FILE_APPEND);
}
$this_file = __FILE__;
// put the current file in and close
file_put_contents($file, $this_file, FILE_APPEND);
file_put_contents($file, "?>", FILE_APPEND);
?>
Related
This may be simple to do, sorry if this is quite broad. I am fine with looking for any alternatives, but I would just like some help.
I need to be able to read variables from a file in PHP.
For instance, I would have a file like this:
$test = 10
$greeting = "Hello"
And PHP would be able to take these values and actually use them. The "code" above would be the entire file, add or take a few variables. The reason why I need to do it like this is so that other PHP files can also write variables to it. Is there any method that can do this, or something similar to this.
Thanks
Edit: This file would be a TXT file; it's not meant to be .php
Read lines from your text file:
<?php
$myfile = fopen("variables.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
//echo fgets($myfile) . "<br>";
// <Your code logic here.>
}
fclose($myfile);
?>
For each iteration of the while loop do whatever it is you need to do with the values read in from the text file.
I found a method. I'm still fairly new to PHP, so I'm using it quite strictly. I've decided to make a never ending PHP file, with all my variables in it:
<?php
//File name is variables.php
$test = 10;
$greeting = "Hello";
So then other PHP files can still write to it and other PHP files can read from it:
<?php
include "variables.php";
echo $greeting;
Output would be Hello.
Thank you for all your help everyone.
$dosya=fopen('a.txt','r');
$dosya2=fopen('f.txt','w');
function getTitle($satir) {
$data = file_get_contents("http://$satir");
$title = preg_match('/<title[^>]*>(.*?)<\/title>/ims',$data,$matches)?$matches[1]:null;
$title=str_replace(",", null, $title);
$title=str_replace("-", null, $title);
$title=trim($title);
$title= explode(" ",$title);
foreach ($title as $val) {
echo $val."<br>";
fwrite($dosya2, $val)."<br>"; //??
}
}
fclose($dosya);
fclose($dosya2);
?>
why does not it write into text file ?
Did you even open the file somewhere? If you opened it outside the scope of the function, you need to get it from the global scope. See variable scopes.
function getTitle($satir) {
global $dosya2;
$data = file_get_contents("http://$satir");
$title = preg_match('/<title[^>]*>(.*?)<\/title>/ims',$data,$matches)?$matches[1]:null;
$title=str_replace(",", null, $title);
$title=str_replace("-", null, $title);
$title=trim($title);
$title= explode(" ",$title);
foreach ($title as $val) {
echo $val."<br>";
fwrite($dosya2, $val)."<br>"; //??
}
fclose($dosya2);
}
Another point, is that some machines might not display the file before you actually close it. So add the fclose to the end of the script as I did as well. Try the code I pasted and let us know. Make sure your file is opened.
Another point is about code style. It's good to keep your code structure on point and readable. If your function says getTitle, then you should use the function to get the title, not to write it into a file. Maybe create a separate writer function for this case. Or if it's the only place where you're writing, rename the function. It's not a fault, it's just "bad style".
Edit - I see you edited your code. Your files get closed before the function gets fired. That's because when you include the file into your PHP page which you're using, it parses the whole file. Your file starts with opening the file and ends with closing them. So PHP opens the files and closes them right away. You need to have a separate function to close the files if you wish to do that. My advise would be to use a completely separate function to read / write the files, so you wouldn't use the memory uselessly. Open the file when you need to read it and close it when you're done, open the file when you need to write and close it when you're done.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a problem while trying to open a file and display its contents using php
My file called hello.txt
Here is my PHP code
<?php
$filename = 'hello.txt';
$filePath = 'c:\\Users\\bheng\\Desktop\\'.$filename;
if(file_exists($filePath)) {
echo "File Found.";
$handle = fopen($filePath, "rb");
$fileContents = fread($handle, filesize($filePath));
fclose($handle);
if(!empty($fileContents)) {
echo "<pre>".$fileContents."</pre>";
}
}
else {
echo "File Not Found.";
}
?>
I got this from
http://php.net/manual/en/function.fread.php
I keep getting error:
fread(): Length parameter must be greater than 0
Can someone help me please?
Although there are good answers here about using file_get_contents() instead, I'll try to explain wht this is not actually working, and how to make it work without changing the method.
filesize() function uses cache. You probably executed this code while still having the file empty.
Use the clearstatcache function each time the file change, or before testing its size :
clearstatcache();
$fileContents = fread($handle, filesize($filePath));
Also obviously make sure that your file is not empty ! Test it :
clearstatcache();
if(file_exists($filePath) && filesize($filePath)) {
// code
}
It needn't be that hard, and it certainly doesn't require you to read a file in binary mode:
if (file_exists($filePath))//call realpath on $filePath BTW
{
echo '<pre>', file_get_contents($filePath), '</pre>';
}
All in all, you really don't want to be doing this kind of stuff too much, though
If you need to read the entire file's content, there is a shortcut function
http://php.net/manual/en/function.file-get-contents.php
So you don't need to bother creating a file handler and closing it afterwards.
$fileContents = file_get_contents($filePath);
using file_get_contents method of php
echo file_get_contents("text.txt");
Problem
I'm trying to edit HTML/PHP files server side with PHP. With AJAX Post I send three different values to the server:
the url of the page that needs to be edited
the id of the element that needs to be edited
the new content for the element
The PHP file I have now looks like this:
<?php
$data = json_decode(stripslashes($_POST['data']));
$count = 0;
foreach ($data as $i => $array) {
if (!is_array($array) && $count == 0){
$count = 1;
// $array = file url
}
elseif (is_array($array)) {
foreach($array as $i => $content){
// $array[0] = id's
// $array[1] = contents
}
}
}
?>
As you can see I wrapped the variables in an array so it's possible to edit multiple elements at a time.
I've been looking for a solution for hours but can't make up my mind and tell what's the best/possible solution.
Solution
I tried creating a new DOMElement and load in the html, but when dealing with a PHP file, this solution isn't possible since it can't save php files:
$html = new DOMDocument();
$html->loadHTMLFile('file.php');
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
(From this answer)
Opening a file, writing in it and saving it comes is another way to do this. But I guess I must be using str_replace or preg_replace this way.
$fname = "demo.txt";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("oldword", "newword", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
(From this page)
I read everywhere that str_replace and preg_replace are risky 'caus I'm trying to edit all kinds of DOM elements, and not a specific string/element. I guess the code below comes close to what I'm trying to achieve but I can't really trust it..
$replace_with = 'id="myID">' . $replacement_content . '</';
if ($updated = preg_replace('#id="myID">.*?</#Umsi', $replace_with, $file)) {
// write the contents of $file back to index.php, and then refresh the page.
file_put_contents('file.php', $updated);
}
(From this answer)
Question
In short: what is the best solution, or is it even possible to edit HTML elements content in different file types with only an id provided?
Wished steps:
get file from url
find element with id
replace it's content
First of all, you are right in not wanting to use a regex function for HTML parsing. See the answer here.
I'm going to answer this question under the presumption you are committed to the idea of retrieving PHP files server-side before they are interpreted. There is an issue with your approach right now, since you seem to be under the impression that you can retrieve the source PHP file by the URL parameter - but that's the location of the result (interpreted PHP). So be careful your structure does what you want.
I am under the assumption that the PHP files are structured like this:
<?php include_some_header(); ?>
<tag>...</tag>
<!-- some HTML -->
<?php //some code ?>
<tag>...</tag>
<!-- some more HTML -->
<?php //some code ?>
Your problem now is that you cannot use an HTML reader (and writer), since your file is not HTML. My answer is that you should restructure your code, separating templating language from business logic. Get started with some templating language. Afterwards, you'll be able to open the template, without the code, and write back the template using a DOM parser and writer.
Your only alternative in your current setup is to use the replace function as you have found in this answer. It's ugly. It might break. But it's definitely not impossible. Make backups before writing over your own code with your own code.
I would need a tool, if it exists or if you can write in under 5 mins (don't want to waste anyone's time).
The tool in question would resolve the includes, requires, include_once and require_once in a PHP script and actually harcode the contents of then, recursively.
This would be needed to ship PHP scripts in one big file that actually use code and resources from multiple included files.
I know that PHP is not the best tool for CLI scripts, but as I'm the most pro-efficient at it, I use it to write some personal or semi-personal tools. I don't want un-helpful answers or comments that tell me to use something else than PHP or learn something else.
The idea of that approach is to be able to have a single file that would represent everything needed to put it in my personal ~/.bin/ directory and let it live there as a completely functional and self-contained script. I know I could set include paths in the script to something that would honor the XDG data directories standards or anything else, but I wanted to try that approach.
Anyway, I ask there because I don't want to re-invent the wheel and all my searches gave nothing, but if I don't have any insight here, I will continue in the way I was going to and actually write a tool that will resolve the includes and requires.
Thanks for any help!
P.S.: I forgot to include examples and don't want to rephrase the message:
Those two files
mainfile.php
<?php
include('resource.php');
include_once('resource.php');
echo returnBeef();
?>
resource.php
<?php
function returnBeef() {
return "The beef!";
}
?>
Would be "compiled" as (comments added for clarity)
<?php
/* begin of include('resource.php'); */?><?php
function returnBeef() {
return "The beef!";
}
?><?php /* end of include('resource.php); */
/*
NOT INCLUDED BECAUSE resource.php WAS PREVIOUSLY INCLUDED
include_once('resource.php');
*/
echo returnBeef();
?>
The script does not have to output explicit comments, but it could be nice if it did.
Thanks again for any help!
EDIT 1
I made a simple modification to the script. As I have begun writing the tool myself, I have seen a mistake I made in the original script. The included file would have, to do the least amount of work, to be enclosed out of start and end tags (<?php ?>)
The resulting script example has been modified in consequence, but it has not been tested.
EDIT 2
The script does not actually need to do heavy-duty parsing of the PHP script as in run-time accurate parsing. Simple includes only have to be treated (like include('file.php');).
I started working on my script and am reading the file to unintelligently parse them to include only when in <?php ?> tags, not in comments nor in strings. A small goal is to also be able to detect dirname(__FILE__)."" in an include directive and actually honor it.
An interesting problem, but one that's not really solvable without detailed runtime knowledge. Conditional includes would be nearly impossible to determine, but if you make enough simple assumptions, perhaps something like this will suffice:
<?php
# import.php
#
# Usage:
# php import.php basefile.php
if (!isset($argv[1])) die("Invalid usage.\n");
$included_files = array();
echo import_file($argv[1])."\n";
function import_file($filename)
{
global $included_files;
# this could fail because the file doesn't exist, or
# if the include path contains a run time variable
# like include($foo);
$file = #file_get_contents($filename);
if ($file === false) die("Error: Unable to open $filename\n");
# trimming whitespace so that the str_replace() at the end of
# this routine works. however, this could cause minor problems if
# the whitespace is considered significant
$file = trim($file);
# look for require/include statements. Note that this looks
# everywhere, including non-PHP portions and comments!
if (!preg_match_all('!((require|include)(_once)?)\\s*\\(?\\s*(\'|")(.+)\\4\\s*\\)?\\s*;!U', $file, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ))
{
# nothing found, so return file contents as-is
return $file;
}
$new_file = "";
$i = 0;
foreach ($matches as $match)
{
# append the plain PHP code up to the include statement
$new_file .= substr($file, $i, $match[0][1] - $i);
# make sure to honor "include once" files
if ($match[3][0] != "_once" || !isset($included_files[$match[5][0]]))
{
# include this file
$included_files[$match[5][0]] = true;
$new_file .= ' ?>'.import_file($match[5][0]).'<?php ';
}
# update the index pointer to where the next plain chunk starts
$i = $match[0][1] + strlen($match[0][0]);
}
# append the remainder of the source PHP code
$new_file .= substr($file, $i);
return str_replace('?><?php', '', $new_file);
}
?>
There are many caveats to the above code, some of which can be worked around. (I leave that as an exercise for somebody else.) To name a few:
It doesn't honor <?php ?> blocks, so it will match inside HTML
It doesn't know about any PHP rules, so it will match inside PHP comments
It cannot handle variable includes (e.g., include $foo;)
It may introduce scope errors. (e.g., if (true) include('foo.php'); should be if (true) { include('foo.php'); }
It doesn't check for infinitely recursive includes
It doesn't know about include paths
etc...
But even in such a primitive state, it may still be useful.
You could use the built in function get_included_files which returns an array of, you guessed it, all the included files.
Here's an example, you'd drop this code at the END of mainfile.php and then run mainfile.php.
$includes = get_included_files();
$all = "";
foreach($includes as $filename) {
$all .= file_get_contents($filename);
}
file_put_contents('all.php',$all);
A few things to note:
any include which is actually not processed (ie. an include inside a function) will not be dumped into the final file. Only includes which have actually run.
This will also have a around each file but you can have multiple blocks like that with no issues inside a single text file.
This WILL include anything included within another include.
Yes, get_included_files will list the script actually running as well.
If this HAD to be a stand-alone tool instead of a drop in, you could read the inital file in, add this code in as text, then eval the entire thing (possibly dangerous).