PHP Extensions-Package management tools in a detailed

Source: Internet
Author: User
Tags php website

Background

What I have to say is that yesterday was basically finished with the entire tool (the shell script on Linux didn't add to it). At the end of the day, I made a super-big stupid mistake.

That is to forget the anti-election, hehe. The source code was deleted at a sudden. wtf!!! Later, some data recovery software was used, and it was not successfully recovered.

So I had to rewrite it again today and just finished the adaptation on the Windows platform. Linux on the expansion of management, the first not to write, there is time to improve.

Principle

The expansion of installing PHP on Windows is a very simple and easy thing to do.

Download and expand the DLL dynamic link library, then modify the php.ini file, and finally restart the Apache server.

Yes, it's that simple.

Let's talk about the utility of this tool:

    • Crawl the link of the target extension, after the filtering process, the list can be downloaded to expand the library connection.

    • Unzip the downloaded zip archive and return to the location where the dynamic link library exists.

    • Find the local PHP environment variable, find the location of the extension folder, copy the dynamic link library and modify the contents of the php.ini file.

    • Restart the Apache server. can take effect (this does not add automatic processing, because I think the manual way will be more rational).

All we need to do is to specify the name of the extension to install, manually choose the version to install, it is so simple. The next step is to analyze it.

Download

This tool relies on the extension directory provided by the PHP website,

Of course, you can also use the manual download installation method, this tool is to automate the process.

Get Web page Content

In order to prevent the Web site from doing anti-reptile processing, we use the simulation browser to get the content.

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 ()

Regular and filtered download links

Download a page, the content is still a lot of. What we need is just the desired download link in the Web page. So we have to do regular matching to filter out the data we want.

And the regular has a certain degree of flexibility, so we have to be based on the specific situation of the collective analysis, so I encapsulated a function.

# get all usable versions of the specified extension    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), ' <a href=" (/do Wnloads/pecl/releases/{}/.*?) "                                       > '. Format (self.extensionname)) for index, item in enumerate (versionlinks): Print "{}: {}". Format (Index, item) choice = Int (raw_input (' Choose the Special V Ersion want by number!\n ')) return Versionlinks[choice] def gettargeturl (self): Userchoice = "Http://windows.php.net" +str (Self.getdownloadlinks ()) print userchoice Regpattern = ' <a href= ' (/.                *?/php_.*?\.zip) ">.*?<\/A> targeturls = Self.getlinks (Url=userchoice, Regpattern=regpattern) # because the regular match is not well written, the first link does not match properly, so the first invalid link return targeturls[1 is removed by means of a break:] 

Many of the things in the code are not generic, because the tool itself relies on this site instead. So there's no concrete refactoring, and that's already enough.

Download the expected target

From the above you can get a download link that is selected by the user, and then we will be able to download a specific version of the extension package accordingly.

def foldermaker (self): if not os.path.exists (R './packages/{} '. Format (self.extensionname)): Os.mkdir (R './                packages/{} '. Format (self.extensionname)) def download (self): choices = Self.gettargeturl () For index, item in enumerate (choices): print "{}: {}". Format (Index, item) choice = Int (ra W_input (' Choose the special version which suitable for your operation system "you want by number!\n ')) Userch        Oice = Choices[choice] # to provide friendly user prompt information, optimize the time by adding a progress bar form to show the print ' downloading, please wait ... '                # Enable download mode for code optimization when you can use multithreading to accelerate data = Self.urlopener (targeturl= "Http://windows.php.net" +str (Userchoice))                # Store downloaded resources to the local repository (before the folder exists or not) filename = userchoice.split ('/') [-1] self.foldermaker ()                   With open (R './packages/{}/{} '. Format (self.extensionname, filename), ' WB ') as File:file.write (data) print ' {} downloadEd! '. Format (filename)

Extract

The first step is to download, the result of the download is a zip compression package, so we also need to deal with this compression package in order to be used by us.

File path Issues

Because it is made for Windows, the file path delimiter is followed by Windows (it can be used to make the code more elegant and os.sep compatible with different operating systems).

Extract

def foldermaker (self, foldername):        if not os.path.exists (R './packages/{}/{} '. Format (Self.extensionname, FolderName):            Os.mkdir (R './packages/{}/{} '. Format (Self.extensionname, foldername))                        print ' Created folder { } succeed! '. Format (foldername)                def unzip (self):        filelists = [item for item in Os.listdir (R './packages/{}/'. Format ( Self.extensionname)) if Item.endswith ('. zip ')]        filezip = ZipFile. ZipFile (R './packages/{}/{} '. Format (Self.extensionname, filelists[0]))        foldername = Filelists[0].split ('. ') [0]        Self.foldermaker (foldername=foldername)                print ' uncompressing files, please wait ... ' for        file in Filezip.namelist ():            filezip.extract (file, R './packages/{}/{}/{} '. Format (self.extensionname, foldername, file ))        filezip.close ()                print ' uncompress files succeed! '

Installation and Configuration

Installation and configuration are actually two topics.

Installation

The first is to put the downloaded extension dll files into the PHP installation directory of the expansion folder, this process involves the search for PHP to expand the directory of the problem. Then there is the issue of file copy.

def getphpextpath (self):        # There is only one PHP version in the default system        Rawpath = [item for item in OS.GETENV (' path '). Split (';') If item.__ contains__ (' php ')][0]        Self.phppath = Rawpath                return rawpath+str (' ext\\ ')            def getextensiondllpath (self) : For            root, dirs, files in Os.walk (R './packages/{}/'. Format (self.extensionname)):                Extensionfolder = Root.split (' \ \ ') [-1]                                if extensionfolder.__contains__ (' dll '):                                    return root.split (' \ \ ') [0] + '/' + extensionfolder+ '/' +extensionfolder

The code is not finished, the copy of the paragraph will be put up.

Configuration

The configuration is required to be declared in the php.ini file, which is to add one of the following statements. (Below the dynamic extension block)

Extension=xx.dll

 # targeted additions to the relevant extension options in the php.ini file. The specific method used is to replace the temporary file with Def iniappend (self): IniPath = self.phppath+str (' php.ini ') Tmpinipath = Self.phppath+str (' Php-tmp.ini ') # The new file content to be replaced newcontent = ';  Windows extensions\nextension={}.dll '. Format (self.extensionname) open (Tmpinipath, ' W '). Write (Re.sub (R '; Windows Extensions ', newcontent, open (IniPath). read ()) # Rename Operation Os.rename (IniPath, Self.phppat H+str (' Php.bak.ini ')) Os.rename (Tmpinipath, Self.phppath+str (' php.ini ')) print ' Rename Succe    ed! ' def configure (self): # print PHP extension directory path Extpath = Self.getphpextpath () +str (' Php_{}.dll '. Format (self.extensionname                ) Print Extpath # Get to expand the dynamic link library and its path Extensiondllpath = Self.getextensiondllpath ()        # Add extension files to PHP extension directory shutil.copyfile (Extensiondllpath, Extpath) # Add the corresponding expansion options in the php.ini file                Self.iniappend ()The print ' {} extension has been added and the extension service will take effect after restarting the Apache server! '. Format (self.extensionname)

Finally, the Apache restart will be effective.

Demonstrate

Initial state

Installation and Configuration complete status

Activation status

Summarize

Finally, to summarize, this tool is mainly used in the Python language, convenient, elegant, fast.
The installation and configuration of PHP extension has been completed, which greatly simplifies the operation.

In fact, I think it is not appropriate to use the code to complete the installation and configuration work. On Windows, however, the batch commands are not very easy to handle (PowerShell I haven't used so much, so I have no say.) ), and if it's not the same on Linux, do some of these tasks, using the shell to write is the most suitable, but also can write very flexible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.