Creating a config file in PHP
One simple but elegant way is to create a config.php
file (or whatever you call it) that just returns an array:
<?php
return array(
'host' => 'localhost',
'username' => 'root',
);
And then:
$configs = include('config.php');
Best Way to create configuration file(config.php) php
i find best way to create config.php file for my project
index.php
<?php
include 'config.php';
try
{
$host=$config['DB_HOST'];
$dbname=$config['DB_DATABASE'];
$conn= new PDO("mysql:host=$host;dbname=$dbname",$config['DB_USERNAME'],$config['DB_PASSWORD']);
//new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
}
catch(PDOException $e)
{
echo "Error:".$e->getMessage();
}
?>
config.php
<?php
$config=array(
'DB_HOST'=>'localhost',
'DB_USERNAME'=>'root',
'DB_PASSWORD'=>'',
'DB_DATABASE'=>'gobinath'
);
?>
I want a create a config file, using the values of the form
to create the config file from the user input, you can create an empty config.php
file then use fwrite
and fopen
to open and write to that file.
<?PHP
$errors = "";
if (isset($_POST["submit"])) {
if (empty($_POST['servername'])) {
echo "Enter servername";
$errors++;
} else {
$servername = $_POST['servername'];
}
if (empty($_POST['username'])) {
echo "enter username";
$errors++;
} else {
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
echo "enter password";
$errors++;
} else {
$password = $_POST['password'];
}
if (empty($_POST['dbname'])) {
echo "enter database";
$errors++;
} else {
$dbname = $_POST['dbname'];
}
if ($errors <= 0) { // no errors
$string = '<?php
$dbhost = "' . $servername . '";
$dbuname = "' . $username. '";
$dbpass = "' . $password . '";
$dbname = "' . $dbname . '";
?>';
$fp = fopen("config.php", "w");
if (fwrite($fp, $string)) {
echo "db created";
}
fclose($fp);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<form name="form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<tr><td colspan="2" align="center"> Database </tr>
<tr><td>Servername:</td>
<td><input type="text" name="servername" value="" ></td></tr>
<tr><td>Username:</td>
<td><input type="text" name="username" value="" ></td>
</tr>
<tr><td>Password:</td>
<td><input type="text" name="password" value="" ></td>
</tr>
<tr><td>Database Name:</td>
<td><input type="text" name="dbname" value="" > </td>
</tr>
<tr><td colspan="2" align="center"><input type="submit" name="submit"></td></tr>
</form>
</table>
</body>
</html>
How to import a config.php file in a php script
The problem with the code is that you're not actually returning the config in your MailConfiguration.php
. You define it as a variable, which you never use in the constructor.
Instead of storing the config array in a variable in your config file, do:
return [
'mailSender' => 'wk@someSender.com',
'mailSubject' => 'XXX',
'maxConnections' => 400,
'maxTime' => 600,
'csv' => 'mailaccounts.csv',
];
Now the config array will be loaded into $this->mailConfigs
in your constructor.
Then, when you want to use it, just do:
public function getMailConfig()
{
return $this->mailConfigs;
}
since it contains the same array as you returned in the config file.
Suggestion
It's good to build configs so you can load different config files for different environments (prod, staging, local, testing etc). So would suggest that you pass the path to the config file to the constructor. Then you can pass different files for different environments. Example:
public function __construct($configFile)
{
$this->mailConfigs = require $configFile;
}
and when you instantiate the class:
$mailer = new Mailer(__DIR__ . '/../../Config/MailConfiguration.php');
Then you can make the file you're passing in conditional on the current environment.
How to create a global configuration file in php
define()
is quite a good way of doing things. An alternative is to define a global array. such as
$config['display_ad']=true;
$config['something_else']='a value';
//...
function doSomething() {
global $config;
if ($config['display_ad']) echo 'Ad code goes here';
}
The latter way is what many projects use, such as phpmyadmin, the reason could be, that you cannot define()
a non-scalar value, e.g. define('SOME_ARRAY',array('a','b'))
is invalid.
creating configuration file in php
i have done it by making an array
$config = array (
"{b0ff543d-d294-42c8-83eb-d72161ec6771}" => '/var/www/youngib/rahul/'
);
$source=$config[$_REQUEST['applicationid']];
thanks
rahul
Creating new Apache config file from PHP
Ok, this is a really bad plan for this, but somehow this is the best solution for this.
To do this in a proper way, I'll use the bash script, and I'll call that script from PHP.
$output = shell_exec("sudo /path/to/script/script.sh $SiteName $Domain");
script.sh
#! /bin/bash
#First parameter given by calling the script
sitename=$1
#Second parameter given by calling the script
domain=$2
#Directorium where are stored files of the web app
dirlocation="/var/www/$sitename"
#Creating a new directorium
mkdir $dirlocation
#Copying the defoult files of app to the just created dir
cp -R /var/www/someapp/* $dirlocation
#Creating the new configurationg file for Apache and VHost
vhost_script="/etc/apache2/sites-available/$sitename.conf"
cat > "${vhost_script}" << EOF
<VirtualHost *:80>
ServerName $domain
DocumentRoot $dirlocation
<Directory $dirlocation>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
EOF
#Enabling the site in Apache
a2ensite $sitename.conf
#Reloading the Apache
systemctl reload apache2.service
Also in order to do this from a PHP, I need to give www-data
permission for running only that script with sudo.
To do so open the sudoers
file (sudo visudo /etc/sudoers
) and add the following line
www-data ALL=(root) NOPASSWD: /path/to/script/script.sh
I know this is maybe not the best solution, but this is what I've found for this purpose.
Disclaimer: This is only a showcase of how to do this, also the bash script here is a really simple one.
Related Topics
How to Convert Output of Number_Format Back to Numbers in PHP
Find Out Which Class Called a Method in Another Class
PHP Remove Duplicate Values from Multidimensional Array
Save Current Page as HTML to Server
PHP Header() Redirect with Post Variables
What Does a Successful MySQL Delete Return? How to Check If Delete Was Successful
How to Output JavaScript with PHP
PHP Date() and Strtotime() Return Wrong Months on 31St
Need a Good Regex to Convert Urls to Links But Leave Existing Links Alone
Removing Last Comma from a Foreach Loop
Php: Force File Download and Ie, Yet Again
Passing PHP Variable into JavaScript
Case Insensitive String Comparison
How to Find the Date of a Day of the Week from a Date Using PHP