`
天梯梦
  • 浏览: 13730875 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

PHP网站安装程序制作 (附:模块检测的方法)

 
阅读更多

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:

  1. Enter MySQL details
  2. Set up MySQL Tables etc.
  3. Insert Site Title, Tagline, Contact Email.
  4. Insert Admin User's details [username, display name and password].
  5. 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!

  1. Check if any fields are blank - error if they are.
  2. Test the SQL Connection - error if no connection.
  3. Run the SQL - error if it fails.
  4. Insert the user details into users table - error if it fails.
  5. Insert the settings into settings table - error & rollback user detail insert if it fails.
  6. 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/or settings 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 for mysqli(), 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]+#", '#&nbsp;#', '#  +#', '# class=".*?"#', '%&#039;%',
	  '#<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)

 

参考:http://www.php.net/manual/en/function.phpinfo.php#87463

 

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    php如何制作安装程序

    - **配置环境检查**:检测服务器环境,确认支持的应用所需模块,如GD2图像处理库、PDO数据库扩展、URL重写模块等。 在实际开发过程中,可能还会遇到其他问题,如错误处理、用户输入验证等。确保提供清晰的错误提示...

    phpStudy 2016.10.31 再次更新,支持自定义php版本

    7. 本程序分为安装版和非安装版,无论是安装还是免安装,最后的效果完全一致。 8. 端口问题无法启动时,请使用菜单『强制启动端口』进行端口检测,尝试启动。 系统服务和非服务启动的区别: 系统服务启动:开机就会...

    wordpress 网站建设源程序

    如果您曾自己制作或者修改主题,可能您需要做一些修改以使模板在跨版本更新后正常工作。 从其他内容管理系统“搬家” WordPress 支持导入多种系统的数据。请先按照上述步骤安装 WordPress。安装后,您可在后台使用...

    TayCMS免费企业建站系统 for PHP v1.8 build 20130808.zip

    上传到空间后,访问您的域名,首次使用程序会自动跳转到安装程序,按照安装程序说明,检测系统环境,目录权限,设置数据库帐号,管理员帐号后 安装完成。 安装完成后请删除安装文件:source\app\controllers\...

    友邻B2B系统(PHPB2B) 5.0 开发版.zip

    友邻B2B网站系统(PHPB2B)是一款基于PHP程序和Mysql数据库、以MVC架构为基础的开源B2B行业门户电子商务网站建站系统,系统代码完整、开源,功能全面,架构优秀,提供良好的用户体验、多国语言化及管理平台,是目前...

    巅云自助建站系统免费版 v3.0

    这是一款免费可视化拖拉排版智能建站软件,适用于搭建企业官网,功能模块化是特色,拖拽排版才是本软件的重点,那些商业的自助建站平台才有的功能在该软件程序可免费使用。如果你正在为制作自己的网站没有技术发愁,...

    CentOS 6.2 使用教程.zip

    6. **安装完成与首次启动**:安装完成后,重启系统,首次登录时,可能会进行一些初始化设置,如时区、硬件检测等。 二、使用第三方YUM源 1. **添加源**:CentOS 6.2的默认YUM源可能无法提供最新软件包。为了获得...

    phpstudy-x64.zip

    该程序包集成最新的Apache+Nginx+LightTPD+PHP+MySQL+phpMyAdmin+Zend Optimizer+Zend Loader,一次性安装,无须配置即可使用,是非常方便、好用的PHP调试环境。该程序绿色小巧简易迷你仅有35M,有专门的控制面板。...

    程序员文摘第77期-精选最有价值的文章

    * Burpsuite介绍及安装教程:介绍了Burpsuite工具的使用和安装方法,包括图文版安装教程。 IoT * 图像分割:介绍了基于Kmeans聚类分水岭优化脂肪肝图像分割的方法,并提供了Matlab代码实现。 微服务 * IntelliJ ...

    红头船企业网站系统RHSCMS v1.0 beta10.rar

    5.改进安装程序,检测写入权限并防止重复安装。 四、安装说明: 1.全新安装需把upload文件夹里面的(注意,是里面的)子目录和文件全部上传到网站根目录下,再按提示选择数据库、填写数据库信息,然后点击安装链接...

    Discuz插件制作教程

    ### Discuz插件制作教程知识点详解 #### 一、Discuz插件机制概览 - **定义**:Discuz插件机制是指Discuz系统中一套完整且灵活的扩展功能实现方式,它允许开发者通过编写特定的插件代码来增强或定制Discuz的功能,...

    若干源程序资料12.rar

    2012-06-11 21:42 275,968 Window7系统如何安装Visual_C++_6.0.doc 2012-06-11 21:26 2,399,725 windows API 一日一练.pdf 2012-06-11 21:28 249,332 Windows核心编程源码.rar 2012-06-11 21:40 1,000,923 Windows...

    易创网站管理系统(DIRCMS) 2011 SP3 UTF8.rar

    易创网站管理系统(DIRCMS)是国内自主研发的一款功能强大而又不失小巧简洁的由PHP Mysql架构的内容管理系统。DirCMS代码全部开源,便于使用者二次开发或定制;并采用简洁的模板标签技术,使制作模板更加容易,一般...

    网站制作——宏图外贸国际有限公司毕业设计.doc

    【网站制作——宏图外贸国际有限公司毕业设计】 随着信息技术的快速发展,越来越多的企业意识到拥有一个官方网站的重要性。宏图外贸国际有限公司的网站制作项目就是一个典型的例子,它利用了现代Web技术和编程语言...

    BageCMS v3.1.0.rar

    采用MVC设计模式,模板定制方便灵活,内置小挂工具,方便制作各类功能和效果,BageCms可用于企业建站、个人博客、资讯门户、图片站等各类型站点。 特点: 1.开源免费 无论是个人还是企业展示型网站均可用本系统来...

    程序员文摘第55期-精选最有价值的文章

    【Docker安装】 Docker 是一种流行的容器化技术,用于构建、部署和运行应用程序。在离线环境中安装 Docker,可以遵循以下步骤: 1. **下载 Docker 离线包**: 可以从 Docker 的官方网站下载稳定版本的 Docker ...

    PHP开发实战1200例(第1卷).(清华出版.潘凯华.刘中华).part1

    实例061 网页框架的制作 92 实例062 图片验证码 93 实例063 健康生活提醒 95 2.5 循环控制 96 实例064 员工生日列表 96 实例065 员工详细信息浏览 97 实例066 员工信息的批量删除 98 实例067 表格的动态创建 99 实例...

    bycms内容管理系统-PHP

    可调用本系统数据,也可以调用其他mysql数据库,轻松实现多个网站应用程序的数据整合。 主要特性: 基于tp5.1,遵循PSR-2、PSR-4规范,Composer及单元测试,异常严谨的错误检测和安全机制,详细的日志信息,为你的...

    网管教程 从入门到精通软件篇.txt

    如果系统检测到无效或非标准分区表标记,将提示用户是否继续执行该命令。除非您访问驱动器有问题,否则不要继续进行。向系统分区写入新的主引导记录可能破坏分区表并导致分区无法访问。  format  将指定的驱动器...

Global site tag (gtag.js) - Google Analytics