search
HomeBackend DevelopmentPHP TutorialPHP expansion-detailed explanation of package management tools (picture)

背景

不得不说的是,昨天其实已经是基本上写完了整个工具了的(Linux上那块的shell脚本没往上添加罢了)。最后整理的时候,犯了个超级大的愚蠢的错误。

那就是忘了反选了,呵呵。一下子把源代码给删了。WTF!!!后来也使用了一些数据恢复软件,也没能成功找回。

于是今天不得不又重写了一遍,而且仅仅完成了Windows平台上的适配。Linux上的拓展管理,就先不写了,有时间再进行完善。

原理

在Windows上安装php的拓展是非常的简单,而且容易的一件事。

下载拓展对应的dll动态链接库, 然后修改php.ini文件,最后重启Apache服务器。

是的,就是这么的简单啦。

下面先说一下这个工具的作用:

  •  爬取目标拓展的链接,做完过滤处理后罗列可以下载得到的拓展库连接。

  • 解压下载的zip压缩包,返回动态链接库存在的位置。

  • 查找本机php环境变量,找到拓展文件夹的位置,拷贝动态链接库并修改php.ini文件内容。

  • 重启Apache服务器。即可生效(这个没有添加自动处理,因为我觉得手动方式会更加理智一点)。

全程我们需要做的就是指定一下要安装的拓展的名称,手动的进行选择要安装的版本,就是这么的简单啦。接下来就一步步地进行分析吧。

下载

这个工具依托的是php官网提供的拓展目录,

当然也可以使用手动下载安装的方式,这个工具就是把这个流程自动化了而已。

获取网页内容

获取网页内容的时候,为了防止网站做了防爬虫处理,我们采用模拟浏览器的方式进行。

def urlOpener(self, targeturl):
        headers = {            
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36'
        }        
        return urllib2.urlopen(urllib2.Request(url=targeturl, headers=headers)).read()

正则与过滤下载链接

下载了一张网页,内容还是很多的。而我们需要的仅仅是网页中预期的下载链接罢了。所以要进行正则匹配,来过滤出我们想要的数据。

而正则有一定的灵活性,所以我们要根据具体情况进行集体的分析,于是我封装了一个函数。

# 获取指定拓展的所有能用的版本
    def getLinks(self, url, regpattern):
        content = self.urlOpener(targeturl=url)
        reg = re.compile(regpattern)        
        return re.findall(reg, content)
def getDownloadLinks(self):
        versionLinks = self.getLinks("http://windows.php.net/downloads/pecl/releases/{}".format(self.extensionname),                  
                           &#39;<A HREF="(/downloads/pecl/releases/{}/.*?)">&#39;.format(self.extensionname))        
                           for index, item in enumerate(versionLinks):            
                           print "{} : {}".format(index, item)
        choice = int(raw_input(&#39;Please choose the special version you want by number!\n&#39;))        
        return versionLinks[choice]    def getTargetUrl(self):
        userChoice = "http://windows.php.net"+str(self.getDownloadLinks())        
        print userChoice
        regpattern = &#39;<A HREF="(/.*?/php_.*?\.zip)">.*?<\/A>&#39;
        targetUrls = self.getLinks(url=userChoice, regpattern=regpattern)        
        # 由于正则匹配度写的不好,第一个链接不能正常匹配,因此采用折断方式,去除第一个无效链接
        return targetUrls[1:]

代码中很多东西写得不是通用的,因为这个工具本身就是要依赖于这个网站而是用的。所以没有做具体的重构处理, 而这已然是足够的了。

下载预期目标

从上面即可获取到经由用户选择的下载链接,然后我们就可以据此来进行特定版本的拓展包下载了。

def folderMaker(self):
        if not os.path.exists(r&#39;./packages/{}&#39;.format(self.extensionname)):
            os.mkdir(r&#39;./packages/{}&#39;.format(self.extensionname))    
            def download(self):
        choices = self.getTargetUrl()        
        for index, item in enumerate(choices):            
        print "{} : {}".format(index, item)
        choice = int(raw_input(&#39;Please choose the special version which suitable for your operation system you want by number!\n&#39;))
        userChoice = choices[choice]        
        # 对外提供友好的用户提示信息,优化的时候可通过添加进度条形式展现
        print &#39;Downloading, please wait...&#39;

        # 开启下载模式,进行代码优化的时候可以使用多线程来进行加速
        data = self.urlOpener(targeturl="http://windows.php.net"+str(userChoice))        
        # 将下载的资源存放到 本地资源库(先进行文件夹存在与否判断)
        filename = userChoice.split(&#39;/&#39;)[-1]
        self.folderMaker()        
        with open(r&#39;./packages/{}/{}&#39;.format(self.extensionname, filename), &#39;wb&#39;) as file:
           file.write(data)        
           print &#39;{} downloaded!&#39;.format(filename)

解压

第一个步骤就是下载,下载的结果就是一个zip压缩包,所以我们还需要对这个压缩包进行处理,才能为我们所用。

文件路径问题

由于是针对Windows而制作,所以文件路径分隔符就按照windows上的来吧(为了代码更加优雅,还可以使用os.sep来兼容不同的操作系统)。

解压

def folderMaker(self, foldername):
        if not os.path.exists(r&#39;./packages/{}/{}&#39;.format(self.extensionname, foldername)):
            os.mkdir(r&#39;./packages/{}/{}&#39;.format(self.extensionname, foldername))            
            print &#39;Created folder {} succeed!&#39;.format(foldername)    
            def unzip(self):
        filelists = [item for item in os.listdir(r&#39;./packages/{}/&#39;.format(self.extensionname)) if item.endswith(&#39;.zip&#39;)]

        filezip = zipfile.ZipFile(r&#39;./packages/{}/{}&#39;.format(self.extensionname, filelists[0]))
        foldername = filelists[0].split(&#39;.&#39;)[0]

        self.folderMaker(foldername=foldername)        
        print &#39;Uncompressing files, please wait...&#39;
        for file in filezip.namelist():
            filezip.extract(file, r&#39;./packages/{}/{}/{}&#39;.format(self.extensionname, foldername, file))
        filezip.close()        
        print &#39;Uncompress files succeed!&#39;

安装与配置

安装与配置其实是两个话题了。

安装

首先是要将下载好的拓展的dll文件放置到php安装目录下的拓展文件夹,这个过程就涉及到了寻找php拓展目录的问题。然后是文件拷贝的问题。

def getPhpExtPath(self):
        # 默认系统中仅有一个php版本
        rawpath = [item for item in os.getenv(&#39;path&#39;).split(&#39;;&#39;) if item.__contains__(&#39;php&#39;)][0]
        self.phppath = rawpath        
        return rawpath+str(&#39;ext\\&#39;)    
        def getExtensionDllPath(self):

            for root, dirs, files in os.walk(r&#39;./packages/{}/&#39;.format(self.extensionname)):
                extensionfolder = root.split(&#39;\\&#39;)[-1]                
                if extensionfolder.__contains__(&#39;dll&#39;):                    
                return root.split(&#39;\\&#39;)[0] + &#39;/&#39; + extensionfolder+&#39;/&#39;+extensionfolder

代码未完,下面会把拷贝的那段放上去的。

配置

配置就是需要在php.ini文件中进行声明,也就是添加下面的这样一条语句。(在Dynamic Extension块下面即可)

extension=XX.dll

 # 针对php.ini文件中的相关的拓展选项进行针对性的添加.采用的具体方式是使用临时文件替换的方法
    def iniAppend(self):
        inipath = self.phppath+str(&#39;php.ini&#39;)
        tmpinipath = self.phppath+str(&#39;php-tmp.ini&#39;)        
        # 要进行替换的新的文件内容
        newcontent = &#39;; Windows Extensions\nextension={}.dll&#39;.format(self.extensionname)
        open(tmpinipath, &#39;w&#39;).write(
            re.sub(r&#39;; Windows Extensions&#39;, newcontent, open(inipath).read()))        
            # 进行更名操作
        os.rename(inipath, self.phppath+str(&#39;php.bak.ini&#39;))
        
        os.rename(tmpinipath, self.phppath+str(&#39;php.ini&#39;))        
        print &#39;Rename Succeed!&#39;


    def configure(self):
        # 打印php拓展目录路径
        extpath = self.getPhpExtPath()+str(&#39;php_{}.dll&#39;.format(self.extensionname))        
        print extpath        
        # 获取到拓展动态链接库及其路径
        extensiondllpath = self.getExtensionDllPath()        
        # 将拓展文件添加到php拓展目录中
        shutil.copyfile(extensiondllpath, extpath)        
        # 在php.ini文件中添加对应的拓展选项
        self.iniAppend()        
        print &#39;{} 拓展已添加,拓展服务将在重启Apache服务器后生效!&#39;.format(self.extensionname)

最后让Apache重启就可以生效啦。

演示

初始状态

PHP expansion-detailed explanation of package management tools (picture)

PHP expansion-detailed explanation of package management tools (picture)

安装与PHP expansion-detailed explanation of package management tools (picture)状态

PHP expansion-detailed explanation of package management tools (picture)

PHP expansion-detailed explanation of package management tools (picture)

激活状态

PHP expansion-detailed explanation of package management tools (picture)

PHP expansion-detailed explanation of package management tools (picture)

总结

最后来总结一下,这个工具主要使用到了Python语言,方便,优雅,快捷。
完成了对PHP拓展的安装与配置,大大简化了操作量。

Actually, I think it is not appropriate to use code to complete the installation and configuration work. However, that's it on Windows. After all, batch command processing is not very easy to use (I have not used PowerShell much, so I have no say.), but it is different on Linux. To do some such tasks, It is most suitable to use Shell to write, and it can also be written very flexibly.

The above is the detailed content of PHP expansion-detailed explanation of package management tools (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool