Lo que veremos hoy es un Asistente de Instalación en CodeIgniter para instalaciones de script en los servidores, El instalador de script se encargará de crear la base de datos y tablas en el servidor sin la necesidad de abrir el PHPMyAdmin ni abrir archivos manualmente.
Asistente de Instalación
A continuación se decribe los pasos para desarrollar este script en lenguaje PHP con el framework de CodeIgniter, este script es para toda las versiones de CodeIgniter.

Asistente de Instalación – Directorio Config
En el directorio config se encuentran dos plantillas las cuales remplazaran al a los archivos originales de application/config/ de CodeIgniter.
En el directorio config se encuentran dos archivos el config.php y el database.php estos dos son plantillas similares a los archivos de CodeIgniter situados en application/config/, no es necesario copiar esta plantilla todo el tiempo, puedes optar por copiar los archivos de config y database de
application/config/ de CodeIgniter.
config.php
La plantilla config.php es para configurar la dirección de la aplicación, me refiero a la dirección del $config[‘base_url’] = »; en la linea 25 se encuentra la variable con la cual se reemplazará la dirección (%DEFAULT_URL%)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = '%DEFAULT_URL%';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = TRUE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression which characters are permitted
| within your URLs. When someone tries to submit a URL with disallowed
| characters they will get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ folder. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = 'coa11kk55kkwwkzi777e88c6o7po9k00i2e2';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or 'gmt'. This pref tells the system whether to use
| your server's local time as the master 'now' reference, or convert it to
| GMT. See the 'date helper' page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
/* End of file config.php */
/* Location: ./application/config/config.php */
database.php
En el archivo database.php
se encuentra la plantilla para configurar la conexión a la base de datos, exactamente en la línea 38,39,40 y 43
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the "Database Connection"
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database type. ie: mysql. Currently supported:
mysql, mysqli, postgre, odbc, mssql, sqlite, oci8
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Active Record class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the "default" group).
|
| The $active_record variables lets you determine whether or not to load
| the active record class
*/
// The following values will probably need to be changed.
$db['default']['username'] = "%USERNAME%";
$db['default']['password'] = "%PASSWORD%";
$db['default']['database'] = "%DATABASE%";
// The following values can probably stay the same.
$db['default']['hostname'] = "%HOSTNAME%";
$db['default']['dbdriver'] = "mysql"; //Updated to latest driver.
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$active_group = "default";
$active_record = TRUE;
/* End of file database.php */
/* Location: ./application/config/database.php */
Directorio Include
En este directorio tenemos a tres archivos para llevar a cabo la instalación, recuerda que el directorio config contenía las plantillas.
core_class.php
El core_class
permite escribir las configuraciones en las plantillas para esto es importante revisar las direcciones de los archivos a escribir, las escrituras van dirigido para database.php
y config.php
<?php
class Core {
// Función para escribir el archivo de configuración
function write_config($domain) {
// ruta de configuración
$template_path = 'config/config.php';
$output_path = '../application/config/config.php';
// Abre el archivo
$config_file = file_get_contents($template_path);
$saved = str_replace("%DEFAULT_URL%",$domain,$config_file);
// Escribe el nuevo archivo config.php
$handle = fopen($output_path,'w+');
// Chmod el archivo, en caso de que el usuario lo haya olvidado.
@chmod($output_path,0777);
// Verificar permisos de archivos
if(is_writable($output_path)) {
// escribe el archivo
if(fwrite($handle,$saved)) {
@chmod($output_path,0644);
return true;
} else {
return false;
}
} else {
return false;
}
}
// Función para validar los datos del post.
function validate_post($data)
{
/* Validando el nombre de host, el nombre de la base de datos y el nombre de usuario. La contraseña es opcional. */
return !empty($data['hostname']) && !empty($data['username']) && !empty($data['database']);
}
// Función para mostrar un error
function show_message($type,$message) {
return $message;
}
// Función para escribir el archivo de configuración
function write_database($data) {
// ruta de configuración
$template_path = 'config/database.php';
$output_path = '../application/config/database.php';
// Abre el archivo
$database_file = file_get_contents($template_path);
$new = str_replace("%HOSTNAME%",$data['hostname'],$database_file);
$new = str_replace("%USERNAME%",$data['username'],$new);
$new = str_replace("%PASSWORD%",$data['password'],$new);
$new = str_replace("%DATABASE%",$data['database'],$new);
// Escribe el nuevo archivo database.php
$handle = fopen($output_path,'w+');
// Chmod el archivo, en caso de que el usuario lo haya olvidado.
@chmod($output_path,0777);
// Verificar permisos de archivos
if(is_writable($output_path)) {
// escribe el archivo
if(fwrite($handle,$new)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
database_class.php
Este archivo se encarga de crear la base de datos y las tablas, hay que tener en cuenta el directorio donde se encuentra el script SQL, este archivo busca el directorio asignado para luego ejecutar el script, para este ejemplo el directorio del archivo SQL se encuentra en install/assets/database.sql
<?php
class Database {
// Funciona con la base de datos y las tablas y rellénalas con los datos predeterminados
function create_database($data)
{
// Conectar a la base de datos
$mysqli = new mysqli($data['hostname'],$data['username'],$data['password'],'');
// Verificar errores
if(mysqli_connect_errno())
return false;
// Crear la declaración preparada
$mysqli->query("CREATE DATABASE IF NOT EXISTS ".$data['database']);
// cierra la conexión
$mysqli->close();
return true;
}
// Función para crear las tablas y llenarlas con los datos predeterminados.
function create_tables($data)
{
// Conectar a la base de datos
$mysqli = new mysqli($data['hostname'],$data['username'],$data['password'],$data['database']);
// Verificar errores
if(mysqli_connect_errno())
return false;
// Abrir el archivo SQL por defecto
$query = file_get_contents('assets/database.sql');
// Ejecutar una consulta múltiple
$mysqli->multi_query($query);
// cierra la conexión
$mysqli->close();
return true;
}
}
timezones_class.php
Este archivo contiene las zonas horarias de cada país.
<?php
class Timezones {
function get_timezones()
{
$timezones = array(
'' => "Please select",
'Pacific/Midway' => "(GMT-11:00) Midway Island",
'US/Samoa' => "(GMT-11:00) Samoa",
'US/Hawaii' => "(GMT-10:00) Hawaii",
'US/Alaska' => "(GMT-09:00) Alaska",
'US/Pacific' => "(GMT-08:00) Pacific Time (US & Canada)",
'America/Tijuana' => "(GMT-08:00) Tijuana",
'US/Arizona' => "(GMT-07:00) Arizona",
'US/Mountain' => "(GMT-07:00) Mountain Time (US & Canada)",
'America/Chihuahua' => "(GMT-07:00) Chihuahua",
'America/Mazatlan' => "(GMT-07:00) Mazatlan",
'America/Mexico_City' => "(GMT-06:00) Mexico City",
'America/Monterrey' => "(GMT-06:00) Monterrey",
'Canada/Saskatchewan' => "(GMT-06:00) Saskatchewan",
'US/Central' => "(GMT-06:00) Central Time (US & Canada)",
'US/Eastern' => "(GMT-05:00) Eastern Time (US & Canada)",
'US/East-Indiana' => "(GMT-05:00) Indiana (East)",
'America/Bogota' => "(GMT-05:00) Bogota",
'America/Lima' => "(GMT-05:00) Lima",
'America/Caracas' => "(GMT-04:30) Caracas",
'Canada/Atlantic' => "(GMT-04:00) Atlantic Time (Canada)",
'America/La_Paz' => "(GMT-04:00) La Paz",
'America/Santiago' => "(GMT-04:00) Santiago",
'Canada/Newfoundland' => "(GMT-03:30) Newfoundland",
'America/Buenos_Aires' => "(GMT-03:00) Buenos Aires",
'Greenland' => "(GMT-03:00) Greenland",
'Atlantic/Stanley' => "(GMT-02:00) Stanley",
'Atlantic/Azores' => "(GMT-01:00) Azores",
'Atlantic/Cape_Verde' => "(GMT-01:00) Cape Verde Is.",
'Africa/Casablanca' => "(GMT) Casablanca",
'Europe/Dublin' => "(GMT) Dublin",
'Europe/Lisbon' => "(GMT) Lisbon",
'Europe/London' => "(GMT) London",
'Africa/Monrovia' => "(GMT) Monrovia",
'Europe/Amsterdam' => "(GMT+01:00) Amsterdam",
'Europe/Belgrade' => "(GMT+01:00) Belgrade",
'Europe/Berlin' => "(GMT+01:00) Berlin",
'Europe/Bratislava' => "(GMT+01:00) Bratislava",
'Europe/Brussels' => "(GMT+01:00) Brussels",
'Europe/Budapest' => "(GMT+01:00) Budapest",
'Europe/Copenhagen' => "(GMT+01:00) Copenhagen",
'Europe/Ljubljana' => "(GMT+01:00) Ljubljana",
'Europe/Madrid' => "(GMT+01:00) Madrid",
'Europe/Paris' => "(GMT+01:00) Paris",
'Europe/Prague' => "(GMT+01:00) Prague",
'Europe/Rome' => "(GMT+01:00) Rome",
'Europe/Sarajevo' => "(GMT+01:00) Sarajevo",
'Europe/Skopje' => "(GMT+01:00) Skopje",
'Europe/Stockholm' => "(GMT+01:00) Stockholm",
'Europe/Vienna' => "(GMT+01:00) Vienna",
'Europe/Warsaw' => "(GMT+01:00) Warsaw",
'Europe/Zagreb' => "(GMT+01:00) Zagreb",
'Europe/Athens' => "(GMT+02:00) Athens",
'Europe/Bucharest' => "(GMT+02:00) Bucharest",
'Africa/Cairo' => "(GMT+02:00) Cairo",
'Africa/Harare' => "(GMT+02:00) Harare",
'Africa/Tunis' => "(GMT+01:00) Tunisie(Zarzis)",
'Europe/Helsinki' => "(GMT+02:00) Helsinki",
'Europe/Istanbul' => "(GMT+02:00) Istanbul",
'Asia/Jerusalem' => "(GMT+02:00) Jerusalem",
'Europe/Kiev' => "(GMT+02:00) Kyiv",
'Europe/Minsk' => "(GMT+02:00) Minsk",
'Europe/Riga' => "(GMT+02:00) Riga",
'Europe/Sofia' => "(GMT+02:00) Sofia",
'Europe/Tallinn' => "(GMT+02:00) Tallinn",
'Europe/Vilnius' => "(GMT+02:00) Vilnius",
'Asia/Baghdad' => "(GMT+03:00) Baghdad",
'Asia/Kuwait' => "(GMT+03:00) Kuwait",
'Africa/Nairobi' => "(GMT+03:00) Nairobi",
'Asia/Riyadh' => "(GMT+03:00) Riyadh",
'Asia/Tehran' => "(GMT+03:30) Tehran",
'Europe/Moscow' => "(GMT+04:00) Moscow",
'Asia/Baku' => "(GMT+04:00) Baku",
'Europe/Volgograd' => "(GMT+04:00) Volgograd",
'Asia/Muscat' => "(GMT+04:00) Muscat",
'Asia/Tbilisi' => "(GMT+04:00) Tbilisi",
'Asia/Yerevan' => "(GMT+04:00) Yerevan",
'Asia/Kabul' => "(GMT+04:30) Kabul",
'Asia/Karachi' => "(GMT+05:00) Karachi",
'Asia/Tashkent' => "(GMT+05:00) Tashkent",
'Asia/Kolkata' => "(GMT+05:30) Kolkata",
'Asia/Kathmandu' => "(GMT+05:45) Kathmandu",
'Asia/Yekaterinburg' => "(GMT+06:00) Ekaterinburg",
'Asia/Almaty' => "(GMT+06:00) Almaty",
'Asia/Dhaka' => "(GMT+06:00) Dhaka",
'Asia/Novosibirsk' => "(GMT+07:00) Novosibirsk",
'Asia/Bangkok' => "(GMT+07:00) Bangkok",
'Asia/Jakarta' => "(GMT+07:00) Jakarta",
'Asia/Krasnoyarsk' => "(GMT+08:00) Krasnoyarsk",
'Asia/Chongqing' => "(GMT+08:00) Chongqing",
'Asia/Hong_Kong' => "(GMT+08:00) Hong Kong",
'Asia/Kuala_Lumpur' => "(GMT+08:00) Kuala Lumpur",
'Australia/Perth' => "(GMT+08:00) Perth",
'Asia/Singapore' => "(GMT+08:00) Singapore",
'Asia/Taipei' => "(GMT+08:00) Taipei",
'Asia/Ulaanbaatar' => "(GMT+08:00) Ulaan Bataar",
'Asia/Urumqi' => "(GMT+08:00) Urumqi",
'Asia/Irkutsk' => "(GMT+09:00) Irkutsk",
'Asia/Seoul' => "(GMT+09:00) Seoul",
'Asia/Tokyo' => "(GMT+09:00) Tokyo",
'Australia/Adelaide' => "(GMT+09:30) Adelaide",
'Australia/Darwin' => "(GMT+09:30) Darwin",
'Asia/Yakutsk' => "(GMT+10:00) Yakutsk",
'Australia/Brisbane' => "(GMT+10:00) Brisbane",
'Australia/Canberra' => "(GMT+10:00) Canberra",
'Pacific/Guam' => "(GMT+10:00) Guam",
'Australia/Hobart' => "(GMT+10:00) Hobart",
'Australia/Melbourne' => "(GMT+10:00) Melbourne",
'Pacific/Port_Moresby' => "(GMT+10:00) Port Moresby",
'Australia/Sydney' => "(GMT+10:00) Sydney",
'Asia/Vladivostok' => "(GMT+11:00) Vladivostok",
'Asia/Magadan' => "(GMT+12:00) Magadan",
'Pacific/Auckland' => "(GMT+12:00) Auckland",
'Pacific/Fiji' => "(GMT+12:00) Fiji",
);
return $timezones;
}
}
Index.php
En el index.php
de install
se encuentra las etiquetas HTML y código PHP de la interfaz principal del instalador para proceder con la instalación.
<?php
error_reporting(0); // Al configurar esto en E_ALL, se demostró que la causa de no redireccionamiento eran pocas líneas en blanco agregadas en algunos archivos php.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="UTF-8">
<title>PDV Intalador</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700,900,300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/css/font-awesome.min.css">
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<style media="screen">
.hide {
display: none;
}
body {
background: url(../assets/img/login.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
color: #472033;
font-family: 'Lato', sans-serif;
}
.installmodal-container {
padding: 30px;
max-width: 700px;
width: 100% !important;
background-color: #F0F0F0;
margin: 0 auto;
margin-top: 150px;
border-radius: 2px;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.modal-backdrop {
background: none;
}
.logo {
margin-top: 50px;
}
.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
background: none;
border: none;
background-color: #472033;
color: white;
border-radius: 3px;
}
.nav-tabs>li>a {
text-align: center;
color: #472033;
font-weight: 400;
text-transform: uppercase;
border: none;
font-size: 18px;
}
.nav-tabs>li>a>p {
font-weight: 500;
font-size: 10px;
margin: 0;
text-transform: capitalize;
}
.nav-tabs>li>a:hover {
background: none;
border: none;
}
.nav-tabs {
border: none;
}
.label-success {
background-color: #4CAF50;
}
.btn-next {
background-color: #472033;
color: white;
float: right;
}
.btn-next:hover {
background-color: #425c77;
color: white;
}
</style>
</head>
<body>
<?php
require_once('includes/core_class.php');
require_once('includes/database_class.php');
$db_config_path = "../application/config/database.php";
$installPos = "../FILE";
?>
<center><img src="../assets/img/logo.png" alt="logo" class="logo"></center>
<div class="modal fade" id="install-modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="installmodal-container">
<?php
if (is_file($installPos)) {
$step = isset($_GET['step']) ? $_GET['step'] : '0';
switch($step){
default:
$error = FALSE;
if(phpversion() < "5.3"){$error = TRUE; $check1 = "<span class='label label-danger'>Your PHP version is ".phpversion()."</span>";}else{$check1 = "<span class='label label-success'>v.".phpversion()."</span>";}
if(!extension_loaded('mcrypt')){$error = TRUE; $check2 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check2 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!extension_loaded('mbstring')){$error = TRUE; $check4 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check4 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!extension_loaded('mysqli')){$error = TRUE; $check12 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check12 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!extension_loaded('gd')){$check5 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check5 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!extension_loaded('pdo')){$error = TRUE; $check6 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check6 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!extension_loaded('dom')){$check7 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check7 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!extension_loaded('curl')){$error = TRUE; $check8 = "<span class='label label-danger'><i class='fa fa-times' aria-hidden='true'></i></span>";}else{$check8 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!is_writeable($db_config_path)){$error = TRUE; $check9 = "<span class='label label-danger'>Please make the application/config/database.php file writable.</span>";}else{$check9 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(!is_writeable("../files")){$check10 = "<span class='label label-danger'>files folder is not writeable!</span>";}else{$check10 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
if(ini_get('allow_url_fopen') != "1"){$check11 = "<span class='label label-warning'>Allow_url_fopen is not enabled!</span>";}else{$check11 = "<span class='label label-success'><i class='fa fa-check' aria-hidden='true'></i></span>";}
?>
<ul class="nav nav-tabs">
<li class="active"><a>Requerimientos<p>Archivos necesarios</p></a></li>
<li class=""><a>Base de datos<p>Configuración</p></a></li>
<li class=""><a>Página Web<p>Configuración</p></a></li>
<li class=""><a>Final<p>Éxito !</p></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="Checklist">
<h3>Archivos necesarios</h3>
<table class="table table-striped">
<thead><tr><th>Requerimientos</th><th>Resultado</th></tr></thead>
<tbody>
<tr><td>PHP 5.3+ </td><td><?php echo $check1; ?></td></tr>
<tr><td>Extensión GD PHP</td><td><?php echo $check5; ?></td></tr>
<tr><td>Extensión Mysqli PHP</td><td><?php echo $check12; ?></td></tr>
<tr><td>Extensión Mcrypt PHP</td><td><?php echo $check2; ?></td></tr>
<tr><td>Extensión MBString PHP</td><td><?php echo $check4; ?></td></tr>
<tr><td>Extensión DOM PHP</td><td><?php echo $check7; ?></td></tr>
<tr><td>Escritura carpeta de archivos</td><td><?php echo $check10; ?></td></tr>
<tr><td>Extensión PDO PHP</td><td><?php echo $check6; ?></td></tr>
<tr><td>Extensión CURL PHP</td><td><?php echo $check8; ?></td></tr>
<tr><td>Allow_url_fopen esta habilitado</td><td><?php echo $check11; ?></td></tr>
<tr><td>Escritura de archivo (database.php)</td><td><?php echo $check9; ?></td></tr>
</tbody>
</table>
<form method="get"><input type="hidden" name="step" value="1" />
<button type="submit" class="btn btn-next <?=$error ? 'disabled' : '';?>" href="">Siguiente ></button>
</form>
</div>
<?php
break;
case "1": ?>
<ul class="nav nav-tabs">
<li class=""><a>Requerimientos<p>Archivos necesarios</p></a></li>
<li class="active"><a>Base de datos<p>Configuración</p></a></li>
<li class=""><a>Página Web<p>Configuración</p></a></li>
<li class=""><a>Final<p>Éxito !</p></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="Database">
<form id="install_form" method="post" action="?step=1">
<fieldset>
<legend style="padding-top:20px">Configuración de la base de datos</legend>
<div class="alert alert-dismissible alert-success">
Ingrese los datos correctamente,
el instalador creará la <strong>base de datos y tablas</strong>
</div>
<?php
$hide = '';
if($_POST) {
// Cargue las clases y cree los nuevos objetos
$core = new Core();
$database = new Database();
// Validate the post data
if($core->validate_post($_POST) == true)
{
// Primero crea la base de datos, luego crea tablas y luego escribe el archivo de configuración
if($database->create_database($_POST) == false) {
echo "<p style='color:#ED5565'>La base de datos no pudo ser creada, verifique su configuración.</p>";
$error = 1;
} else if ($database->create_tables($_POST) == false) {
echo "<p style='color:#ED5565'>Las tablas de la base de datos no se pudieron crear, verifique su configuración.</p>";
$error = 1;
} else if ($core->write_database($_POST) == false) {
echo "<p style='color:#ED5565'>El archivo de configuración de la base de datos no se pudo escribir, en chmod application/config/database.php 777.</p>";
$error = 1;
}
// Si no hay errores, redirija a la página de registro
if(!isset($error)) {
echo '<div class="alert alert-dismissible alert-success">
<i class="fa fa-check" style="margin:0 7px" aria-hidden="true"></i>¡Bien!, se estableció una conexión con la base de datos.
</div>';
echo '<a href="index.php?step=2" class="label label-success" style="float:right;font-size:20px;"> Continuar instalación > </a>';
$hide = 'hide';
}
}
}?>
<div class="form-group <?=$hide;?>">
<label for="hostname">Hostname</label>
<input type="text" required id="hostname" class="form-control" name="hostname" />
</div>
<div class="form-group <?=$hide;?>">
<label for="database">Nombre de base de datos</label>
<input type="text" required id="database" class="form-control" name="database" />
</div>
<div class="form-group <?=$hide;?>">
<label for="username">Usuario</label>
<input type="text" required id="username" class="form-control" name="username" />
</div>
<div class="form-group <?=$hide;?>">
<label for="password">Contraseña</label>
<input type="password" id="password" class="form-control" name="password" />
</div>
<input type="submit" class="btn btn-next <?=$hide;?>" value="Instalar" id="submit" />
</fieldset>
</form>
</div>
<?php
break;
case "2": ?>
<ul class="nav nav-tabs">
<li class=""><a>Requerimientos<p>Archivos necesarios</p></a></li>
<li class=""><a>Base de datos<p>Configuración</p></a></li>
<li class="active"><a>Página Web<p>Configuración</p></a></li>
<li class=""><a>Final<p>Éxito !</p></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="Config">
<fieldset>
<div class="alert alert-dismissible alert-success">
<i class='fa fa-check' style="margin:0 7px" aria-hidden='true'></i>¡Bien!, se estableció una conexión con la base de datos.
</div>
<legend style="padding-top:20px">Página Web</legend>
<form id="install_form" method="post" action="?step=2">
<?php if($_POST){
$core = new Core();
$company = $_POST['companyname'];
$phone = $_POST['phone'];
$currency = $_POST['currency'];
$tax = $_POST['tax'];
$domain = $_POST['domain'];
$timezone = $_POST['timezone'];
define("BASEPATH", "instalar/");
include("../application/config/database.php");
$con=mysqli_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password'], $db['default']['database']);
$settings = mysqli_query($con,"INSERT INTO ck_ajustes (`id`, `companyname`, `phone`, `currency`, `receiptfooter`, `theme`, `tax`, `timezone`, `language`, `keyboard`, `stripe`) VALUES (1, '$company', '$phone', '$currency', 'Gracias por tu compra', 'Cookie', '$tax', '$timezone', 'spanish', '1', '0');");
if(!$settings){echo "<div class='label label-danger'>Error al guardar configuración a la base de datos</div>";}else if ($core->write_config($domain) == false) {
echo "<div class='alert alert-error'><i class='icon-remove'></i> Error al escribir los detalles de configuración en config/config.php.</div>";
}else{
echo '<a href="index.php?step=3" class="label label-success" style="float:right;font-size:20px;"> Bien, continuar instalación > </a>';
$hide = 'hide';
}
}
?>
<div class="form-group <?=$hide;?>">
<label for="CompanyName">Nombre de la empresa *</label>
<input type="text" required id="CompanyName" class="form-control" name="companyname" />
</div>
<div class="form-group <?=$hide;?>">
<label for="CompanyPhone">Teléfono *</label>
<input type="text" required id="CompanyPhone" class="form-control" name="phone" />
</div>
<div class="form-group <?=$hide;?>">
<label for="Currency">Código de moneda *</label>
<input type="text" required id="Currency" value="USD" class="form-control" name="currency" />
</div>
<div class="form-group <?=$hide;?>">
<label for="TAX">Impuesto por defecto (%)</label>
<input type="text" id="TAX" value="10%" class="form-control" name="tax" />
</div>
<div class="form-group <?=$hide;?>">
<label for="domain">Dominio *</label>
<input type="text" name="domain" class="form-control" value="<?php echo "http://".$_SERVER["HTTP_HOST"].substr($_SERVER["REQUEST_URI"], 0, -25);?>" required/>
</div>
<div class="form-group <?=$hide;?>">
<label class="control-label" for="domain">Zona horaria</a></label>
<div class="controls">
<?php
require_once('includes/timezones_class.php');
$tz = new Timezones();
$timezones = $tz->get_timezones();
echo '<select name="timezone" required="required" data-error="TimeZone is required" class="form-control">';
foreach ($timezones as $key => $zone){
echo '<option value="'.$key.'">'.$zone.'</option>';
}
echo '</select>'; ?>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-1 col-sm-offset-1">
<a href="index.php?step=1" class="btn btn-default pull-right">Anterior</a>
</div>
<div class="col-sm-2 col-sm-offset-8">
<input type="submit" class="btn btn-next <?=$hide;?>" value="Siguiente" id="submit" />
</div>
</div>
</div>
</fieldset>
</form>
</div>
<?php
break;
case "3": ?>
<ul class="nav nav-tabs">
<li class=""><a>Requerimientos<p>Archivos necesarios</p></a></li>
<li class=""><a>Base de datos<p>Configuración</p></a></li>
<li class=""><a>Página Web<p>Configuración</p></a></li>
<li class="active"><a>Final<p>Éxito !</p></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="Done">
<h1>Instalación completada</h1>
<div class="alert alert-dismissible alert-success">
Para iniciar sesión debe ingresar con estos datos:<br /><br />
Usuario: <span style="font-weight:bold; letter-spacing:1px;">admin</span><br />Contraseña: <span style="font-weight:bold; letter-spacing:1px;">12345</span><br /><br />
</div>
<div class="bg-warning"><i class='icon-warning-sign'></i> Recuerde cambiar los datos de sesión</div>
<?php @unlink('../FILE'); ?>
<a href="<?php echo "http://".$_SERVER["HTTP_HOST"].substr($_SERVER["REQUEST_URI"], 0, -25); ?>" class="btn btn-next">Iniciar sesión</a>
</div>
</div>
<?php } ?>
<?php }else{ ?>
<div class="tab-content">
<h1><i class="fa fa-check" aria-hidden="true" style="margin-right:10px"></i>Instalación finalizada</h1>
<p> Puede borrar este directorio manualmente</p>
<?php } ?>
</div>
</div>
<!-- jQuery -->
<script type="text/javascript" src="../assets/js/jquery-2.2.2.min.js"></script>
<!-- efecto waves material -->
<script type="text/javascript" src="../assets/js/waves.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#install-modal').modal('show').on('hide.bs.modal', function (e) {
e.preventDefault();
});
});
var currency = document.getElementById("Currency");
function validatecurrency(){
if(currency.value.length < 3) {
currency.setCustomValidity("The Currency code must be at least 3 characters length");
} else {
currency.setCustomValidity('');
}
}
if(currency) currency.onchange = validatecurrency;
</script>
</body>
</html>
<!-- /*
* Author : AnthonCode
* http://facebook.com/anthoncode
* https://anthoncode.com
*/ -->
Para iniciar el instalador solo se debe agregar la dirección del instalador en el navegador, ejemplo: localhost/miaplicacion/install
es importante agregar «install» después de la aplicación, al finalizar la instalación ya no podrá volver a instalar, esto es porque el instalador antes de instalar verifica que haya un archivo llamado FILE (sin extensión) al finalizar este archivo se elimina, así que ya no se puede instalar nuevamente a menos que se agregue el archivo FILE dentro de la carpeta install.
Si tienes alguna duda o pregunta escribelo en la caja de comentarios.
6 comments
Amigo, yo ya tengo un proyecto en codeigniter, con solo la carpeta install, archivo file y index.php no me carga, solo veo una web en blanco que archivos mas son necesarios?
desde ya muchas gracias
recuerda que debes de ingresar desde esa dirección, ejemplo: mipagina/install si aún te muestra una pantalla en blanco activa el informe de errores de codeigniter: https://anthoncode.com/informe-de-errores-o-mostrar-errores-en-codeigniter/
Hola, también si erres tan amable me podrías enviar el código a mi correo.
Gracias por tu tiempo
el script esta en el blog
Hola es un proyecto excelente. Tengo un problema al momento de implementar y querer crear la base de datos me sale este error.
The database could not be created, please verify your settings
Lo intento instalar en mi Hosting, la única manera que logre que funcione es si previamente entre en phpMyAdmin y creer la base de datos, entonces Lugo completo el formulario con la mina información y si se importa la bd, pero la idea sería sin tener que hacer este procedimiento, sabe cual puede ser el fallo?
Desde ya muchas gracias por el aporte y compartirlo
el instalador realiza la tarea de crear la base de datos, el script no esta encontrando la base de datos. si tienes nuevamente ese error avisame lo revisare o subire de nuevo