Jump to content

Writing to file with variables not coming out right..


Slips

Recommended Posts

Hello all,

 

I am trying to create a PHP CLi Script that will help me setup new config and server files / directories for every new web project i get instead of me having to manually create everything with each project. The script accepts the project name, and y/n for whether i want to create subdomains for css, jss and image files. After it has that, it must create a new http config file under sites-available (in Linux), by pasting the config file text.

 

Problem : If I output regular text to the file, it displays exactly in the format that I write the string variable. But when I use a printf, or try to use variables directly in the config text, it starts formatting the text in the config file in a strange way. I just want the variables to just be replaced and the text to appear in the exact format below. The text displays perfectly as i typed below in the config file if I don't use any variables.

 

$subDomainConfig .=
'<VirtualHost *:80>
ServerAdmin webmaster@%1$s
ServerName  %1$s.%2$s
ServerAlias %1$s.%2$s

# Indexes + Directory Root.
DirectoryIndex index.html index.php
DocumentRoot /var/www/%2$s/public_html/

# CGI Directory
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Location /cgi-bin>
	Options +ExecCGI
</Location>


# Logfiles
ErrorLog  /var/www/%2$s/logs/apache/error.log
CustomLog /var/www/%2$s/logs/apache/access.log combined
</VirtualHost>		
'.PHP_EOL;
$httpConfigFileText = sprintf($subDomainConfig, $subDomain, $shortProjectName);

 

The above code outputs text in this way in the file :

 

<VirtualHost *:80>

ServerAdmin webmaster@images

ServerName  images.mysite

 

ServerAlias images.mysite

 

 

# Indexes + Directory Root.

DirectoryIndex index.html index.php

DocumentRoot /var/www/mysite

/public_html/

 

# CGI Directory

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

<Location /cgi-bin>

Options +ExecCGI

</Location>

 

 

# Logfiles

ErrorLog  /var/www/mysite

/logs/apache/error.log

CustomLog /var/www/mysite

/logs/apache/access.log combined

</VirtualHost>

Link to comment
Share on other sites

Hmmm all variables seem fine on my checking but here is the full code anyways. The script is incomplete, but with regards to creating a working HTTP config file i guess this is all that is needed for now :

 

Don't worry about the include file, its called because it contains a function that converts a text into camelcaps.

 

Here is a quick overview of the logic so you guys can understand this code quicker :

1. Run script in command prompt

2. Ask user for Full project name. User types something like "PHP Freaks"

3. Ask user for short project name. User types something like "phpf" (Needed for naming directories)

4. Start a foreach loop that asks user if they want a separate domain for css,jss,images files. If user types 'y' - use sprintf, and replace the customize the vhost config text (<Virtual Host:*80> ... </Virtual Host>)  with the respective subdomain name, and concantenate it to the final config text , inside each iteration.

5. Looping and concatenation done, final config text is ready to paste with the vhost config text for 3x subdomains. Open a file and write to it.

 

 

 

include '/var/www/common/lib/functions/all.php';

// Ask for the Project full name and short name (Needed for naming conventions for files and directories etc.)

fwrite(STDOUT,'Enter the full name of the Web Project please :');
$fullProjectName = fgets(STDIN);

fwrite(STDOUT, "Enter the short name for the project please : ");
$shortProjectName = fgets(STDIN);



$projectAliases = array($shortProjectName => $fullProjectName);

// 1. Create a new File in sites-available folder.
$sitesAvailableFolder = '/etc/apache2/sites-available';
$httpConfigFile = $sitesAvailableFolder.'/'.convertToCamelCaps($projectAliases[$shortProjectName], TRUE);

if(!is_file(trim($httpConfigFile))) {
//HTTP config file does not exist, lets begin creating the config text
echo 'HTTP Config file ', $httpConfigFile, 'not found, please follow the instructions below to create one.', PHP_EOL;

$subDomainList = array('css', 'jss', 'images');
// In the foreach loop below , using a $variable.= in the first iteration gives an error because it has nothing to concatenate to,
// so I created 2 empty variables to concatenate to, anyone know any better ways of doing this?
$subDomainConfig = ''; 
$httpConfigFileText = '';

foreach ($subDomainList as $index => $subDomain) {
	fwrite(STDOUT, 'Would you like to add a subdomain for ' .ucwords($subDomain). ' files?');
	${$subDomain.'Install'} = fgets(STDIN);
	if (trim(${$subDomain.'Install'}) == 'y') {
$subDomainConfig .=
'
<VirtualHost *:80>
ServerAdmin webmaster@%2$s
ServerName  %1$s.%2$s
ServerAlias %1$s.%2$s
# Indexes + Directory Root.
DirectoryIndex index.html index.php
DocumentRoot /var/www/%2$s/public_html/

# CGI Directory
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Location /cgi-bin>
	Options +ExecCGI
</Location>


# Logfiles
ErrorLog  /var/www/%2$s/logs/apache/error.log
CustomLog /var/www/%2$s/logs/apache/access.log combined
</VirtualHost>		
'.PHP_EOL;
		$httpConfigFileText.= sprintf($subDomainConfig, $subDomain, $shortProjectName);
	}
}				




// Take the contenated config text and write it to the file.

try {
	if ($fileHandle = @fopen($httpConfigFile, 'w')) {
		if (!fwrite($fileHandle, $httpConfigFileText)) { 
			throw new Exception('Failed to write the Virtual host configuration for '.$fullProjectName); 
		} else {
			echo 'The HTTP Config file was successfully created.', PHP_EOL;
		}
	} else {
		throw new Exception('Failed to create the HTTP Config file '.$httpConfigFile);
	}	
} catch (Exception $e) {
	echo 'Exception caught : ', $e->getMessage();		
}

} else {
echo 'The file, ', $httpConfigFile, 'already exists.', PHP_EOL;
}   

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.