Solution to multi server environment with a CodeIgniter website - codeigniter

I have a local, staging and production environment for my CodeIgniter based site. Increasingly I find everytime I deploy a version I have more and more little bits of code to change because of server variations.
What would be a good (and quick) solution I could add that would allow me to set these variables by just using one setting. Where would be the best place to insert this in the index.php, some sort of hook?

If you're using Apache, you can set an environmental variable which can be read by PHP in your Virtual Hosts file for the site:
<VirtualHost *:80>
DocumentRoot /path/to/site
ServerName local.mysite.com
ErrorLog /path/to/error_log
CustomLog /path/to/access_log common
<Directory /path/to/site>
SetEnv ENVIRONMENT local
RewriteEngine On
Options FollowSymLinks Indexes
AllowOverride AuthConfig Options FileInfo
</Directory>
</VirtualHost>
So with that, you now can check for and set the server environment accordingly in your index.php file:
// always default to production for safety
$environment = 'production';
// check for an environment override
if (function_exists('apache_getenv') && apache_getenv("ENVIRONMENT")) {
$environment = apache_getenv("ENVIRONMENT");
} else if (getenv("ENVIRONMENT")) {
$environment = getenv("ENVIRONMENT");
}
// set the environment constant
define('ENVIRONMENT', $environment);
With this setup, you now have the freedom to deploy your sites and add additional configuration parameters to your application/config/[file].php files for each environment.
Alternative...
Another possibility for handling multi-environment setups is to create a file outside of the document root and is ignored by your version control system (i.e. .gitignore) which contains the value of the server environment. You could then just read that file via file_get_contents() or equivalent.

define a "LIVE" constant which is TRUE or FALSE based on the current domain its on (put this in your index.php file)
if(strpos($_SERVER['HTTP_HOST'], 'mylivesite.com'))
{
define('LIVE', TRUE);
}
else
{
define('LIVE', FALSE);
}
and then check to see if you are live or not and assign the variables accordingly
if(LIVE)
{
$active_group = "production";
}
else
{
$active_group = "test";
}
ive been doing this with our 5 environment setup for the past year with no problems

An old question, but Codeigniter Reactor has support for environment variables built in now. You simply open up the index.php file and choose your environment. There is a post about them here: http://ilikekillnerds.com/2011/03/how-to-use-codeigniter-reactor-environment-variables/

The official CodeIgniter doc suggests this for multiple database environment:
Gobal variable in config.php file to set the environment:
$active_group = "test";
Multiple settings in database.php
$db['test']['hostname'] = "localhost";
$db['test']['username'] = "root";
$db['test']['password'] = "";
$db['test']['database'] = "database_name";
...
$db['production']['hostname'] = "example.com";
$db['production']['username'] = "root";
$db['production']['password'] = "";
$db['production']['database'] = "database_name";
...
See the doc for further details.

Having many little bits of code that change because of server variations is a bad sign that you're modifying code that's not supposed to be modified for the application. The only things that you're supposed to change between servers is your configuration variables located in config.php, which should have default values for the developers to change depending on the environment.

Related

Deprecated: mysql_connect() message and Warnings occur in step 3 of the opencart configuration setup after we enter the details and hit continue

We need help trying to upload our opencart templatemonster.com template correctly on godaddy but we are not clear on how to do that.
FYI our public_html/system/database folder contains a mysqli.php file as well.
We made sure to upload the template via fullpackage (The name of the file is themeXXX(full).zip, where XXX is your theme number) to the public_html folder.
Extracted the zip files in the public_html folder.
Performed the installation using the installation manager .
At step 3 configuration we were prompted to input our database access details and made sure the database was empty. (GoDaddy told us to use the localhost)
After hitting continue:
The deprecated: mysql_connect() message and Warnings occur in step 3 of the opencart configuration setup after we enter the details and hit continue.
Where ‘store’ is the new directory name. Where ‘user’ is your server
account address. Where ‘yourdomainname.co.uk’ is the web domain of
your new website:
(DUMMY LINK FOR DEMONSTRATION PURPOSES) http://www.yourdomainname.co.uk/install/index.php?route=step_3
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/user /public_html/system/database/mysql.php on line 6
Lines 5-16:
public function __construct($hostname, $username, $password, $database) {
if (!$this->link = mysql_connect($hostname, $username, $password)) {
trigger_error('Error: Could not make a database link using ' . $username . '#' . $hostname);
}
if (!mysql_select_db($database, $this->link)) {
trigger_error('Error: Could not connect to database ' . $database);
}
Errors:
Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/system/database/mysql.php:6) in /home/user/public_html/system/engine/controller.php on line 28
Warning: Cannot modify header information - headers already sent by (output started at /home/user/public_html/system/database/mysql.php:6) in /home/user/public_html/system/engine/controller.php on line 29
Lines 27-31
protected function redirect($url, $status = 302) {
header('Status: ' . $status);
header('Location: ' . str_replace(array('&', "\n", "\r"), array('&', '', ''), $url));
exit();
}
Template Features
OpenCart Compatibility: 1.5.6.x
OpenCart Engine: 1.5.6.4
(Trimmed)
Sources Available
PSD PNG PHP TPL JS
Hosting Requirements
Web Server (preferably Apache)
PHP (at least 5.2)
MySQL
Curl
Fsock
OpenCart Templates Help Center
Software Required
Adobe Photoshop CS+
For uncompressing a template ZIP package: WinZip 9+ (Windows);
Stuffit Expander 10+ (Mac)
Apache Server
PHP v. 5 or higher
MySQL 4.1.14 or later
OpenCart 1.5.6.4
Sublime Text2 or later, Notepad++ or any php-editor
A commenter stated
mysql_ calls will work on this server but are causing deprecation
notices. A quick fix would be to turn off warnings in your php.ini
file, in your error_reporting value. Or you could try turning off
display errors, set display_errors to 0.
I like the comment but could someone provide a slightly more comprehensive explanation or visual resource to this suggestion? Such as articulating a little further how to proceed? Should I download the file through GoDaddys public FTP or should I use FileZilla FTP client (does it matter), make a copy, make the proper changes then re-upload?
I like the possible solution but I am curious to know if these are the only ones.
UPDATE
I just changed display_errors = 1; to display_errors = 0;
saved the file (I edited the file withing GoDaddy's text editor)
re-input our database access details
hit continue on step 3 configuration and got the same error.
php.ini
magic_quotes_gpc = Off;
register_globals = Off;
default_charset = UTF-8;
memory_limit = 64M;
max_execution_time = 36000;
upload_max_filesize = 999M;
safe_mode = Off;
mysql.connect_timeout = 20;
session.use_only_cookies = On;
session.use_trans_sid = Off;
session.cookie_httponly = On;
session.gc_maxlifetime = 172800;
allow_url_fopen = on;
;display_errors = 0;
;error_reporting = E_ALL;
???
I have a similar experience! You don't need to enable these extensions the PHP Version needs to be update:
Sign into GoDaddy
Go to My Products under your sign in name at the top right.
Go to Web Hosting and click the Manage button.
Click manage again.
Scroll to the Software header and click "Select PHP Version"
Then change to an earlier version, in which this extension is not deprecated.
Let me know how that works for you.

modify apache httpd.conf using ruby

Hey guys I'm trying to change in httpd.conf using ruby code 1.8.5 could you help me with it please
Apache configuration file The Apache configuration file must be configured specifically
for the server you have installed it on, i.e. the ServerName configuration item must be set to the IP address of the VM, not to 127.0.0.1 or any other generic address. TheServerAdmin configuration item must be set to cit470-sp2014-teamYOUR_TEAM_NUMBER#gmail.com. Create a gmail account with that name if you
have not done so already.
SSL All content must also be accessible using encrypted https versions of your URLs.
User directories Configure the server so that individual users can create their own web
sites by putting files in the public_html subdirectory of their home directory. These files should be available by both URLs of the form http://your_ip/~username and of the form http://your_ip/users/username. This may require that you create rewrite rules with mod_rewrite.
]# ./apconfigure.rb
./apconfigure.rb:8: warning: parenthesize argument(s) for future version
./apconfigure.rb:18: syntax error
.gsub(/ServerAdmin (.+)/, "ServerAdmin cit470su2015team2#gmail.com")
^
./apconfigure.rb:19: syntax error
.gsub(/UserDir disable/, "UserDir public_html")
^
./apconfigure.rb:20: syntax error
.gsub(userdir_regex, replacement) + "\nServerName 10.2.7.84 \nRewriteEngine on\nRewriteRule ^/users/(.*)$ /~$1 [PT]"
^
this is my code
#!/usr/bin/ruby
# This script edits the Apache configuration files and enables UserDir,
# as well as a custom RewriteRule
# path to apache config file
config_file = "/etc/httpd/conf/httpd.conf"
file = File.read(config _file)
# regex to uncomment the sample UserDir directives
userdir_regex = /#<Directory \/home\/\*\/public_html>.+?<\/Directory>/m
replacement = file.match(userdir_regex).to_s.gsub('#','')
# make some substitutions: change ServerName and ServerAdmin, enable UserDir,
# add rewrite rules.
edited_file =
file
.gsub(/ServerAdmin (.+)/, "ServerAdmin cit470su2015team2#gmail.com")
.gsub(/UserDir disable/, "UserDir public_html")
.gsub(userdir_regex, replacement) + "\nServerName 10.2.7.84 \nRewriteEngine on\nRewriteRule ^/users/(.*)$ /~$1 [PT]"
# write the changes to the file
File.open(config_file, 'w') do |f|
f.puts edited_file
end

It's dangerous not recognizing URL Root

I'm using Flask's It's Dangerous to generate encrypted URLs. It's awesome, but I've encountered an issue - I'm running a script daily on Heroku Scheduler. The script lives outside of the app folder, in the directory where the run.py and Procfile are. I create the payload using three variables, the last one being the function assigned to a URL.
payload = reactivate_account_link(candidate.candidate_id, candidate.email, 'reactivate_account')
reactivate_account_link is the following...
def reactivate_account_link(candidate_id, candidate_email, path):
s = get_serializer()
loads = [candidate_id, candidate_email]
payload = s.dumps(loads)
return url_for(path, payload=payload, _external=True)
The problem is that the URL doesn't have the proper root. It creates...
http://localhost/candidates/reactivate_account/WzYsInN1cmFqa2FwQGdtYWlsLmNvbSJd.A484cnO8rRcAqe2M2mNrfoGludo/
as opposed to
http://[--DOMAIN--]/candidates/reactivate_account/WzYsInN1cmFqa2FwQGdtYWlsLmNvbSJd.A484cnO8rRcAqe2M2mNrfoGludo/
This is true for both local and prod. I want to avoid hardcoding the URL.
You need to configure the SERVER_NAME for the app, otherwise you get the default of 'localhost'. Wherever you create and configure your app, add:
SERVER_NAME = 'myapp.heroku.com' # or whatever the external url should be

How to disable Kint in local environment under Laravel 4

I'm using Kint via Composer in Laravel 4 by loading kint first in composer.json so that dd() is defined by kint, not laravel (suggested here).
I want to leave debug calls in my app, and disable Kint if not in the local environment. I'm successfully using config overrides for Anvard using the following structure:
/app/config/local/packages/provider/package_name/overridefile.php
Unfortunately, this is not working for Kint with the following structure:
/app/config/packages/raveren/kint/local/config.php or
/app/config/packages/raveren/kint/local/config.default.php
The Kint documentation states:
You can optionally copy the included config.default.php and rename to config.php to override default values…
…which works for me (/vendor/raveren/kint/config.php)
How do I achieve this:
without editing a file in the /vendor/ directory that will get overwritten by composer
so that kint is only enabled in the local envirnoment
I've also tried adding the following to a helpers.php file which is called before composer in /bootstrap/autoload.php as suggested here:
<?php
isset( $GLOBALS['_kint_settings'] ) or $GLOBALS['_kint_settings'] = array();
$_kintSettings = &$GLOBALS['_kint_settings'];
/** #var bool if set to false, kint will become silent, same as Kint::enabled(false) or Kint::$enabled = false */
$_kintSettings['enabled'] = false;
unset( $_kintSettings );
(but no dice :)
Any suggestions? TIA!
I'm not familiar with kint but checked the documentation and found that, to disable kint output, you may use (in runtime)
// to disable all output
Kint::enabled(false);
In Laravel you can check the environment using
$env = App::environment();
if($env == 'your_predefined_environment') {
Kint::enabled(false);
}
To configure your environment, you may check the documentation.
Update : I've setup my local environment as givel below (in bootstrap/start.php)
$env = $app->detectEnvironment(array(
'local' => array('*.dev'),
));
And in my local machine, I've setup a virtual mashine which has laravel4.dev as it's base url, so if I visit the app using laravel4.dev or laravel4.dev/logon then I can check the environment in my BaseController.php and it detects the local environment because of .dev
public function __construct()
{
if(App::environment() == 'local') {
// do something
}
}
In your case, I don't know where is the first debug/trace you used to print the output, so you should keep the environment checking and disabling the Kint code before you use any debug/trace but you may try this (if it works for you) but you can check the environment in your filter/routes files too.
Hmm.. I'm not sure if this is the ideal way to do it, but this works, and seems Laravel'ish:
// top of app/start/global.php
Kint::enabled(false);
and
// app/start/local.php
Kint::enabled(true);
(assuming you've got a local environment defined: see #TheAlpha's answer for more info)
http://laravel.com/docs/lifecycle#start-files

MoinMoin seperate theme folder from MoinMoin htdocs folder

I'd like to seperate my custom theme folder from the default MoinMoin htdocs folder. Here is my directory structure of my current installation:
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/...
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/index.html
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/classic
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/modern
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/mytheme
/path/to/python2.7/lib/site-packages/MoinMoin/web/static/htdocs/mytheme/style.css
And my custom Git-versioned wiki/data directory:
/path/to/git-repo/wikiconfig.py
/path/to/git-repo/wikiserver.py
/path/to/git-repo/wiki/data/...
/path/to/git-repo/wiki/data/plugin/theme/mytheme.py
/path/to/git-repo/wiki/underlay/...
The wikiconfig.py contains the following configuration:
class LocalConfig(multiconfig.DefaultConfig):
wikiconfig_dir = os.path.abspath(os.path.dirname(__file__))
instance_dir = os.path.join(wikiconfig_dir, 'wiki')
data_dir = os.path.join(instance_dir, 'data', '') # path with trailing /
data_underlay_dir = os.path.join(instance_dir, 'underlay', '') # path with trailing /
DesktopEdition = True # give all local users full powers
acl_rights_default = u"All:read,write,delete,revert,admin"
surge_action_limits = None # no surge protection
sitename = u'Foo'
logo_string = u'<span><img src="...">Bar</span>' % url_prefix_static
page_front_page = u'StartPage'
theme_default = 'mytheme'
I would like to move the theme's static files to the /path/to/git-repo folder, because this directory is a Git repository which should contain all custom modifications, and also the theme's static files.
Any ideas how this could be done?
Regards
I suggest you just leave the builtin static stuff where it is.
What you can do for custom and separate theme development is to serve your static stuff at some specific URL and catch that URL in the web server before it gets given to moin.wsgi (and ends up being served by MoinMoin's builtin static file server), something like:
Alias /moin_static196/mytheme /path/to/git-repo/static
WSGIScriptAlias / /..../moin.wsgi
/moin_static196 is the url path moin 1.9.6 uses by default, you can modify it in wikiconfig.py to use anything you like.
You would put the theme python code also into your git repo and just symlink it from the instances data/plugin/theme/ directory.

Resources