Modifications within the main system
In your script (the system that will be sold), it should check if the file exists config.inc.php
, which in our case, will (or should be) in the folder system
.
if (!file_exists('system/config.inc.php')) {
echo "Clique <a href='./install/' title='Iniciar instalacao'>aqui</a> para iniciar a instalacao do sistema.";
exit;
}
Explaining the above code: it will check whether the file config.inc.php
exists inside the folder system
. Note that we put a denial operator !
before the function, that is, if it does not exist it returns true
and executes the code within the condition, which only displays a message and a link to the folder install/
(which will contain the installation system) and stop executing the script using Exit.
If the file config.inc.php
already existing, it is also interesting to put a new condition (below the previous one) to check the folder install
exists, if yes, we will oblige the user to delete it in order to use the system, since maintaining that folder would be a security risk.
if (file_exists('install/')) {
echo "Por favor, delete a pasta install.";
exit;
}
Okay, these are the only changes within the system that you will sell. Now we will have to create a new system to do the installation.
It is interesting that it does not depend on any file of the main system, ie, all css file, images, files connection to database, functions, anyway... everything must exist inside the folder install
to be used only by the installer.
Creating the installer
Create a file index.php
inside the briefcase install
. This file will be responsible for calling the pages according to the step (progress) that will be passed via $_GET
. See the model below and modify according to your needs.
<?php
$step = (isset($_GET['step'])) ? (int) $_GET['step'] : null;
//Quantidade de etapas que seu instalador irá ter.
$qntEtapas = 3;
if (empty($step) || $step > $qntEtapas) {
header('Location: ./?step=1');
}
//Crie uma pasta chamada step e dentro dela, coloque as páginas seguindo o modelo: pagina-1.php pagina-2.php pagina-3.php, conforme a quantidade de etapas.
require_once 'step/pagina-' . $step . '.php';
Now you have to build the layout of the pages of each step, which is a little off the subject, so I won’t tell you how to do it. But, I’ll give you a hint: the pages of each step will usually only have the form different, so it would be interesting if you create 2 files .php
called header.php
and footer.php
, and include them, leaving the pages of the steps cleaner and facilitating maintenance.
Below, an example of a step page (with the same image fields you posted from Wordpress).
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$database = (isset($_POST['database'])) ? trim($_POST['database']) : null;
$username = (isset($_POST['username'])) ? trim($_POST['username']) : null;
$password = (isset($_POST['password'])) ? trim($_POST['password']) : null;
$hostname = (isset($_POST['hostname'])) ? trim($_POST['hostname']) : null;
$dbprefix = (isset($_POST['dbprefix'])) ? trim($_POST['dbprefix']) : null;
if (!empty($database) || !empty($username) || !empty($hostname)) {
//Nesse caso em especifico, precisamos fazer uma conexão com o banco
//usando os dados informados pelo usuário, para ter certeza de que estão
//corretos.
function dbTest($host, $user, $pass, $db) {
try {
$pdo = new PDO("mysql:host={$host};dbname={$db};charset=utf8", $user, $pass);
return $pdo;
} catch (PDOException $e) {
return false;
}
}
if (dbTest($hostname, $username, $password, $database)) {
//Se a conexão der certo, cria (caso não exista) o arquivo config.inc.php
//dentro da pasta system e escreve os dados nele.
file_put_contents('../system/config.inc.php',
'<?php'
. ' $hostname = ' . "'{$hostname}'; \n"
. ' $username = ' . "'{$username}'; \n"
. ' $password = ' . "'{$password}'; \n"
. ' $database = ' . "'{$database}'; \n"
. ' $dbprefix = ' . "'{$dbprefix}'; \n"
);
//Redireciona para próxima etapa, se for o caso.
header('Location: ./?step=2');
} else {
echo 'Desculpe, mas não foi possível conectar-se ao banco de dados informado.';
}
} else {
echo 'Por favor, preencha os campos corretamente...';
}
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Instalando sistema | Etapa 1 de 1</title>
</head>
<body>
<form action="" method="post">
<label for="database">Nome do banco</label>
<input type="text" id="database" name="database"><br>
<label for="username">Usuário</label>
<input type="text" id="username" name="username"><br>
<label for="password">Senha</label>
<input type="password" id="password" name="password"><br>
<label for="hostname">Servidor MySQL</label>
<input type="text" id="hostname" name="hostname" value="localhost"><br>
<label for="dbprefix">Prefixo da tabela</label>
<input type="text" id="dbprefix" name="dbprefix">
<hr>
<button type="submit">Ir para próxima etapa</button>
</form>
</body>
</html>
Notice that the big X of the question is the function file_put_contents
, it is she who will record the data passed in the specified file.
To insert tables in the database informed by the user, you just need to execute a query normally, only putting the SQL code to create it.
The SQL code you must do manually, or create the tables via phpMyAdmin, Mysql Workbench or any other program that helps you with this, then copy the generated SQL and put in your script to run as a normal query.
It’s the same as giving one SELECT * FROM usuarios WHERE id = 1;
only changes the SQL command.
That’s basically it. Now is to take a look at what was said here, and improve the code to suit your needs.
Recommended readings
Function file_exists
Ternary operator in PHP
Function file_put_contents
Ask the user? I don’t understand.
– Guilherme Nascimento
Yes, let’s say you inserted the folder into the localhost. When inserting the SQL file in phpMyAdmin, automatically the script before entering the system it asks the client the data of connection to the server and after connection it insert the tables.
– Pedro Quezado
I think I’ve seen this question here. But I’m not sure, it tells me what you want is something similar to this http://i.stack.Imgur.com/Qnuzw.png ?
– Guilherme Nascimento
I think it’s a valid question, but I think it’s too broad for one question. Basically what the script will do is to see if there is already a configuration file, if it does not exist, ask the data and save. But it’s good that you say which parts you know and which parts you don’t. Can you check if a file exists? Can you generate a text file and save? Do you know how to make a basic form and take the data? Do you know how to use the data and test the connection? And so on.
– Bacco
No, William... apparently you don’t understand.. To this end https://encrypted-tbn1.gstatic.com/images?q=tbn:And9gcrctdsuahmncgsg_mtmr2fargec9wrdb0i3fiflkykcexjg78hqhcjnjpqxbq
– Pedro Quezado
It’s not that I didn’t understand, it was really hard to understand. What you want is an installation setup or a configuration environment? Because if it is, you can’t understand why a user (I think it’s a sales system) would have to have access to data from the database. If it is an Ecommerce, it has to have a login and password, but the part, the system itself can not order data from the real database, the best would actually be you create a bank (or more) and each user with your credential would be autologged into your bank (which can be shared) specific.
– Guilherme Nascimento
Really now it has totally changed the meaning, I had to delete the answer, I will try to formulate an answer as soon as I have a time.
– Guilherme Nascimento