Table of Contents
背景
原理
下载
获取网页内容
正则与过滤下载链接
下载预期目标
解压
文件路径问题
安装与配置
安装
配置
演示
初始状态
安装与PHP expansion-detailed explanation of package management tools (picture)状态
激活状态
总结
Home Backend Development PHP Tutorial PHP expansion-detailed explanation of package management tools (picture)

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

May 18, 2018 am 10:20 AM

背景

不得不说的是,昨天其实已经是基本上写完了整个工具了的(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()
Copy after login

正则与过滤下载链接

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

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

# 获取指定拓展的所有能用的版本
    def getLinks(self, url, regpattern):
        content = self.urlOpener(targeturl=url)
        reg = re.compile(regpattern)        
        return re.findall(reg, content)
Copy after login
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:]
Copy after login

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

下载预期目标

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

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)
Copy after login

解压

第一个步骤就是下载,下载的结果就是一个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;
Copy after login

安装与配置

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

安装

首先是要将下载好的拓展的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
Copy after login

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

配置

配置就是需要在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)
Copy after login

最后让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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles