Many web applications such as WordPress lead you through the whole installation process from asking for SQL details to getting some user login details etc.
Due to the complexity of what these are, I'll be leading you through the installation of a basic fictitious site that includes the following steps:
- Enter MySQL details
- Set up MySQL Tables etc.
- Insert Site Title, Tagline, Contact Email.
- Insert Admin User's details [username, display name and password].
- Success/Error Page
The SQL
Firstly we need to actually create the SQL that we want to run when the site is being installed - for our needs this is going to simply create two tables: users
and settings
.
users
will have 5 columns:
-
user_id
(Auto-Increment, Primary Key, Int) -
username
(Varchar, 30) -
display_name
(Varchar, 50) -
password
(Varchar, 40) -
admin
(Int, 1)
settings
will have 3 columns:
-
setting_id
(Auto-Increment, Primary Key, Int) -
setting_name
(Varchar, 30) -
setting_value
(Varchar, 100)
I understand that having the settings table constructed like this is probably not the best setup as not all settings will fit into the varchar
setup, this is something for you to consider when you're working away. With those basics worked out, we can write some SQL…
CREATE TABLE `users` (
`user_id` int(11) auto_increment,
`username` varchar(30),
`display_name` varchar(50),
`password` varchar (40),
`admin` int(1),
PRIMARY KEY (`user_id`)
);
CREATE TABLE `settings` (
`setting_id` int(11) auto_increment,
`setting_name` varchar(30),
`setting_value` varchar(100)
PRIMARY KEY (`setting_id`)
);
Let's Write Some HTML & CSS
As there's not a huge amount of data that is required to be entered, we are going to throw all of this on a single form for the user to complete, you can break this page down into steps if you want using some JavaScript or something else. However, that's beyond the scope of this post for now.
So what I've done just quickly is thrown together a form, there's nothing fancy about it at all, it just has a few input boxes for the user to enter their details etc. At the moment, it's a basic HTML form - we will in the next step create the PHP page that it posts to.
This HTML is simpler than the example, due to character limits on Forrst, I had to strip the CSS/Labels etc out.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>PHP Installer - @MichaelW90</title>
</head>
<body>
<form method='post' action='./install.php'>
<p>
<h2>MySQL Details:</h2>
MySQL Host: <input type='text' name='sql-host' /><br />
MySQL Username: <input type='text' name='sql-username' /><br />
MySQL Password: <input type='text' name='sql-password' /><br />
MySQL Database: <input type='text' name='sql-database' /><br />
</p>
<p>
<h2>Site Details:</h2>
Site Name: <input type='text' name='settings-sitename' /><br />
Site Tagline: <input type='text' name='settings-sitetagline' /><br />
Site Contact Email: <input type='text' name='settings-siteemail' /><br />
</p>
<p>
<h2>Admin User Details:</h2>
Admin Username: <input type='text' name='admin-username' /><br />
Admin Displayname: <input type='text' name='admin-name' /><br />
Admin Password: <input type='text' name='admin-pass1' /><br />
Admin Password Again: <input type='text' name='admin-pass2' /><br />
</p>
<p style='border-top:1px solid #c6c6c6; padding-top: 10px;' >
<input type='submit' value='Install!' />
<input type='reset' value='Start Again!' />
</p>
</form>
</body>
</html>
It's time to PHPify!
Now we can move on to the PHP section. Before we do this, let's get the logic down on what we're actually going to be doing in the PHP - and then we can just bash it out & hopefully have a fully working system!
- Check if any fields are blank - error if they are.
- Test the SQL Connection - error if no connection.
- Run the SQL - error if it fails.
- Insert the user details into
users
table - error if it fails. - Insert the settings into
settings
table - error & rollback user detail insert if it fails. - If we reached here it was a huge raging success - output success message.
A few things extra things to consider adding:
- Check that the form is submitted via post
- Store the SQL details (as I haven't written this in, there is no reason you can't compile a 'sql-connect.php' file on the fly.)
- Delete the
/install/
directory after successful installation. - Disallow use of the site until
/install/
has been deleted. - Disallow install to run if there is already a
users
and/orsettings
table. Stops malicious reinstalls or whatever.
1. Check if any fields are blank - error if they are.
<?php
/*
Let's set some variables + functions that we will use throughout!
error() - output error in nicely formatted box.
*/
function error($msg){
die("<div style='font-family: helvetica; border: 1px solid; padding: 10px; color: #D8000C; background: #FFBABA;'><strong>An Error Occurred:</strong><br />{$msg}</div>");
}
/*
Check that none of the user inputs are blank
If they are, then set error to true & break out the loop
Check that the two entered passwords match
*/
$error = false;
foreach($_POST as $key => $item){
if(trim($item) == ""){
$error = true;
break;
}
}
if($error)
error("All fields are required, please ensure they are all entered.");
if($_POST['admin-pass1'] != $_POST['admin-pass2'])
error("The two admin passwords do not match");
?>
From this point forward, assume that all PHP follows that already posted before.
2. Test the SQL Connection - error if no connection.
*
Try to connec to SQL - if it returns false, we know it failed.
*/
$connect = mysql_connect($_POST['sql-host'], $_POST['sql-username'], $_POST['sql-password']);
if(!$connect)
error("The SQL host, username and password combination failed. Please try again");
/*
Try to select database - if it returns false, we know it failed.
*/
$database = mysql_select_db($_POST['sql-database'], $connect);
if(!$database)
error("Unable to connect to database {$_POST['sql-database']}, please check it exists & try again.");
3. Run the SQL - error if it fails.
/*
Define what the SQL is that we need to run.
Run the SQL
If it returns false, we know that it has failed
*/
$sql = <<<SQL
CREATE TABLE `users` (
`user_id` int(11) auto_increment,
`username` varchar(30),
`display_name` varchar(50),
`password` varchar (40),
`admin` int(1),
PRIMARY KEY (`user_id`)
);
CREATE TABLE `settings` (
`setting_id` int(11) auto_increment,
`setting_name` varchar(30),
`setting_value` varchar(100)
PRIMARY KEY (`setting_id`)
);
SQL;
$sql = mysql_query($sql, $connect);
if(!$sql)
error("Creating tables failed: " . mysql_error());
4. Insert the user details into users
table - error if it fails.
/*
Insert the User Details into `users`
Compile SQL & Run - If it returns false we know it fails
*/
$sql = "INSERT INTO `users` (`username`, `display_name`, `password`, `admin`)\n" .
"VALUES ('{$_POST['admin-user']}', '{$_POST['admin-name']}', '" . sha1($_POST['admin-pass1']) . "', '1')";
$sql = mysql_query($sql, $connect);
if(!$sql)
error("Unable to insert admin user details into user database: " . mysql_error());
5. Insert the settings into settings
table - error & rollback user detail insert if it fails.
/*
Insert the Settings into `settings`
Compile SQL & Run - If it returns false we know it fails
Delete the user from the `users` table & display error.
*/
$sql = "INSERT INTO `settings` (`setting_name`, `setting_value`)\n" .
"VALUES ('sitename', '{$_POST['settings-sitename']}'), \n" .
"('sitetagline', '{$_POST['settings-sitetagline']}'), \n" .
"('siteemail', '{$_POST['settings-siteemail']}')";
$sql = mysql_query($sql, $connect);
if(!$sql){
mysql_query("DELETE FROM `users` WHERE `user_id` = '1'");
error("Unable to insert site settings into user database: " . mysql_error());
}
6. If we reached here it was a huge raging success - output success message.
echo "Wooo! Your site is successfully installed! You can now go and play with it!";
Thanks for reading
So that's the ultimate basics of how to make one of those 'installer' things. There are obviously hundreds of ways that you can improve on what I've written, and as always, it's offered simply as a base for you to build off.
Remember these things:
- The
mysql_
functions should be replaced formysqli()
, I didn't merely demonstrative purposes. - You should make sure that you sanitize anything that you input into your database. It's not as critical here as no one will SQL inject their own site, however it's only a few extra words!
Let me know your thoughts, and if you think it's super awesome - why not share it with others, like it, or comment!
来源:http://forrst.com/posts/How_to_Write_a_PHP_MySQL_Install_Wizard-PUc
模块检测的方法
phpinfo() 转 数组
function phpinfo_array($return=false)
{
/* Andale! Andale! Yee-Hah! */
ob_start();
phpinfo(-1);
$pi = preg_replace(
array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms',
'#<h1>Configuration</h1>#', "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#',
"#[ \t]+#", '# #', '# +#', '# class=".*?"#', '%'%',
'#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
.'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
'#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
'#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
"# +#", '#<tr>#', '#</tr>#'),
array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ',
'<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'.
"\n".'<tr><td>PHP Egg</td><td>$1</td></tr>',
'<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
'<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
'<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'),
ob_get_clean());
$sections = explode('<h2>', strip_tags($pi, '<h2><th><td>'));
unset($sections[0]);
$pi = array();
foreach($sections as $section)
{
$n = substr($section, 0, strpos($section, '</h2>'));
preg_match_all('#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',$section, $askapache, PREG_SET_ORDER);
foreach($askapache as $m) $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:array_slice($m,2);
}
return ($return === false) ? print_r($pi) : $pi;
}
单独:
print_r(get_loaded_extensions());
//print_r(apache_get_modules());
print_r(PHP_VERSION)
标签:settings,sql,SQL,user,模块,error,安装程序,PHP From: https://blog.51cto.com/u_8895844/6147983