Combining multiple php files - php

The current code provided on previous question is working. I need help to modify it so I can tell it what php files to combine.
The code below combines every .php file it finds in a directory.
(ie: Need to combine only the following pages, page1.php, page2.php, page3.php, page4.php, page5.php, page6.php, page7.php, page8.php, page9.php, page10.php, page11.php, page12.php )
Thanks in advance.
<?php
foreach (glob("*.php") as $filename) {
$code.=file_get_contents("./$filename");
}
file_put_contents("./combined.php",$code);
?>

If you know the file names and they are not going to change then you can do this:
<?php
$files = array("a.php", "b.php", "c.php");
$comb;
foreach ($files as $k)
{
$comb .= file_get_contents("./".$k);
}
file_put_contents("./combined.php",$comb);
?>
If you are getting them from a form submission then do something like this:
<?php
$files = array();
foreach ($_POST['files_to_combine'] as $k)
{
$files .= $k;
}
$comb;
foreach ($files as $k)
{
$comb .= file_get_contents("./".$k);
}
file_put_contents("./combined.php",$comb);
?>
** As a security note please make sure to sanitize your inputs if you use the second method! this code is only a proof of concept to make it simple to understand and use.

I have no idea why I get negative on my question asking to have it modified seeing how the programmer that answered it copied it from another site.
I don't do this for a living and have no plans too. These are personal
things I try to do to make my job go easier and without paper.
So here is the answer.
<?php
$txt1 = file_get_contents('page-001.php');
$txt1 .= "\n" . file_get_contents('page-002.php');
$txt1 .= "\n" . file_get_contents('page-003.php');
$txt1 .= "\n" . file_get_contents('page-004.php');
$txt1 .= "\n" . file_get_contents('page-005.php');
$txt1 .= "\n" . file_get_contents('page-006.php');
$txt1 .= "\n" . file_get_contents('page-007.php');
$txt1 .= "\n" . file_get_contents('page-008.php');
$txt1 .= "\n" . file_get_contents('page-009.php');
$txt1 .= "\n" . file_get_contents('page-010.php');
$txt1 .= "\n" . file_get_contents('page-011.php');
$txt1 .= "\n" . file_get_contents('page-012.php');
$fp = fopen('newcombined.php', 'w');
if(!$fp)
die('Could not create / open text file for writing.');
if(fwrite($fp, $txt1) === false)
die('Could not write to text file.');
echo 'Text files have been merged.';
?>

Related

PHP - Webform to csv (splitting commas from field (not wanted))

I have some PHP on my 'website' that I am using to send some data from a webform into a csv file.
It is working, but the field called 'primary_classification' contains some text which have commas in. With those classifications, it is splitting the text across two cells in the csv.
This is the PHP:
<?php
$keys = array('user_name', 'gr_num', 'primary_classification');
$csv_line = array();
foreach($keys as $key){
array_push($csv_line,'' . $_GET[$key]);
}
$fname = 'test.csv';
$csv_line = implode(',',$csv_line);
if(!file_exists($fname)){$csv_line = "\r\n" . $csv_line;}
$fcon = fopen($fname,'a');
$fcontent = $csv_line;
fwrite($fcon,$csv_line."\n");
fclose($fcon);
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('The classification has been added!')
window.location.href='http://localhost:8080/classification.html';
</SCRIPT>");
?>
This is the output from the csv when using 'Individual behaviour' (working), and 'Education, learning and skills' (not working).
Does anyone know where I am going wrong?
Thanks
I am pretty sure it is enough if you wrap your fields in quotes, so simply change:
array_push($csv_line,'' . $_GET[$key]);
into
array_push($csv_line, '"' . $_GET[$key] . '"');

PHP Formatter for single-line code blocks

I am trying to configure the Eclipse PHP formatter to keep the opening and closing php tags on 1 line if there is only 1 line of code between them (while keeping the default new line formatting if there are more lines of code).
Example:
<td class="main"><?php
echo drm_draw_input_field('fax') . ' ' . (drm_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="inputRequirement">' . ENTRY_FAX_NUMBER_TEXT . '</span>' : '');
?></td>
Should be formatted to:
<td class="main"><?php echo drm_draw_input_field('fax') . ' ' . (drm_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="inputRequirement">' . ENTRY_FAX_NUMBER_TEXT . '</span>': ''); ?></td>
Is there any way to achieve this with Eclipse? Or another suggestion/formatter?
EDIT:
It seems Eclipse does not have such a formatting option, as explained in the comments below. Any existing alternatives that can do this?
As i already mentioned under question comment "As i know you can't do such thing in eclipse as eclipse has only options to format code part i mean the text part inside php tags <?php ...code text... ?>"
But you can achieve it with this php script
Very important before start: Backup your php project which you are going to mention in dirToArray() function
// Recursive function to read directory and sub directories
// it build based on php's scandir - http://php.net/manual/en/function.scandir.php
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value){
if (!in_array($value,array(".",".."))){
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result = array_merge(
$result,
dirToArray($dir . DIRECTORY_SEPARATOR . $value)
);
}else{
$result[] = $dir . DIRECTORY_SEPARATOR . $value;
}
}
}
return $result;
}
// Scanning project files
$files = dirToArray("/home/project"); // or C:/project... for windows
// Reading and converting to single line php blocks which contain 3 or less lines
foreach ($files as $file){
// Reading file content
$content = file_get_contents($file);
// RegExp will return 2 arrays
// first will contain all php code with php tags
// second one will contain only php code
// UPDATED based on Michael's provided regexp in this answer comments
preg_match_all( '/<\?php\s*\r?\n?(.*?)\r?\n?\s*\?>/i', $content, $blocks );
$codeWithTags = $blocks[0];
$code = $blocks[1];
// Loop over matches and formatting code
foreach ($codeWithTags as $k => $block){
$content = str_replace($block, '<?php '.trim($code[$k]).' ?>', $content );
}
// Overwriting file content with formatted one
file_put_contents($file, $content);
}
NOTE: This is just simple example and of course this script can be improved
// Result will be that this
text text text<?php
echo "11111";
?>
text text text<?php
echo "22222"; ?>
text text text<?php echo "33333";
?>
<?php
echo "44444";
echo "44444";
?>
// will be formated to this
text text text<?php echo "11111"; ?>
text text text<?php echo "22222"; ?>
text text text<?php echo "33333"; ?>
<?php
echo "44444";
echo "44444";
?>
In sublimetext, the manual command is ctrl + J.
Automagically, might i suggest you take a look at this:
https://github.com/heroheman/Singleline

Adding PHP Line Spaces In Codeigniter

I am trying to write file but just need to work out best way to make some gaps/spaces between some code “[‘default’][‘hostname’]” space . ‘=’ . space “‘localhost’”can not work it out.
At the moment when reload page it produces $db['default']['hostname']='localhost'; but need gap/space $db['default']['hostname'] = 'localhost';
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index(){
$output = '<?php' . "\n";
$output .= "\n";
$output .= '// DB' . "\n";
$output .= '$db' . "['default']['hostname']" space . '=' . space "'localhost'". ";" . "\n";
$file = fopen(APPPATH . 'config/database-test.php', 'w');
fwrite($file, $output);
fclose($file);
$this->load->view('welcome_message');
}
}
$output .= '$db' . "['default']['hostname']" space . '=' . space "'localhost'". ";" . "\n";
This line has syntax errors because you're missing the concat operator before the first space and after the second one (whatever the space is meant to be).
Instead of complicating things, why don't you just write this and avoid the concat hell:
$output .= '$db' . "['default']['hostname'] = 'localhost';\n";
I think I have found answer to make gap . " " . seems to do the trick.
$output .= '$db' . "['default']['hostname']" . " " . '=' . " " . "'localhost'". ";" . "\n";
As an additional note, I see you are writing a config file to be processed later.
I have found output buffering and var_export to do this job exceptionally well.
ob_start();
var_export($config);
$out = ob_get_clean();
then
fwrite($f, '$config = '.$out.';'); etc...
http://us3.php.net/manual/en/function.ob-get-clean.php
http://us3.php.net/manual/en/function.var-export.php
basically this will turn an array into a parse-able string such as
array(
'default'=>array(
'hostname'=>'localhost',
'user' => 'user', ///etc
)
)
then just add the variable part and the ending semi-colon
if you plan to do multiple values this would be a much cleaner approach

Echo file content based on separator

I have a txt file with lines in this format
this is a name|this is a type|this is a description
this is a name|this is a type|this is a description
this is a name|this is a type|this is a description
I need to access those lines and echo them like this:
<li type="this is a type" description="this is a description">this is a name</li>
I have no idea how to approach this.
Thanks in advance
Normally I wouldn't write code for you without you having provided an example of what you've tried, but in this case it's pretty basic.
Use PHP's file function to read a file into an array (line by line), then use explode to break that line up:
<?php
$contents = file('yourfile.txt');
foreach($contents as $eachline) {
list($name, $type, $description) = explode("|", $eachline);
echo '<li type="' . $type . '" description="' . $description . '">' . $name . '</li>';
}
?>
PHP manual: http://us2.php.net/manual/en/function.file.php
The first step is to read every line of the file.
How to read a file line by line in php
After that explode the string by the pipe symbol $out = explode("|", $string);
after that you have an array and you can access the values with $out[0]; for example.
This is easypeasy:
$parts = explode("|", $line);
$out = "<li type='$parts[1]' description='$parts[2]'>$parts[0]</li>"

php file put contents reverse

Ok sorry if its a stupid question im a begginer.
Im making a small shoutbox just for practise.
It inserts the shout infos in a txt file.
My problem is that, it lists the text from top to bottom, and i would like to do this reversed.
if(isset($_POST['submit'])) {
$text = $_POST['text'];
if(!empty($text)) {
$text = $_POST['text'];
$name = $_POST['name'];
$time = date("H:i");
$content =
"<div class='text'><em>" . $time . "</em>
<span class='c11'><b>" . "<a href='userinfo_php_willbe_here.php' target='_blank'>" . htmlspecialchars($name) . "</a>" . ":</span></b>
" . htmlspecialchars($text) . "
</div>\n";
file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
}
}
here is my code.
i was googleing around with not much luck maybe i wasnt looking hard enough.
could please someone give me a hint?
thank you
No way to do so with one function call. You need to read the content from your target file, prepend the data in php and rewrite the whole file (see file_get_contents).
$fileContent = file_get_contents($file);
$fileContent = $content . $fileContent;
file_put_contents($file, $fileContent, LOCK_EX);
You can also use the array_reverse like so:
// Data in file separated by new-line
$data = explode("\n",file_get_contents("filename.txt"));
foreach(array_reverse($data) as $value) {
echo $value."\n";
}
You can only prepend to a file by means of reading it and writing afterwards.
file_put_contents($file, $content . file_get_contents($file), LOCK_EX);

Categories