For my open source file sync software Syncany, I have integrated the automatic plugin build process (we provide plugin repository and an easy plugin API to download plugins) with an upload to the Syncany API server. Plugins (JAR files) are uploaded by Travis (example: Samba plugin) to the Syncany server. To serve meta data on through the plugin API, I need to parse the plugins’ MANIFEST.MF files and store them in a database.
This tiny blog post shows you how to read a ZIP/JAR file entry with PHP, and parse JAR manifest (MANIFEST.MF) file. That’s it. Nothing fancy.
1. Read JAR/ZIP file entry
First, we need to read the MANIFEST.MF file from the JAR file. Since a JAR file is nothing more than a ZIP file, PHP’s zip_* functions can be used.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function readZipFileEntry($zipFileName, $searchEntryName) { $zip = zip_open($zipFileName); if ($zip) { while ($zipEntry = zip_read($zip)) { $entryName = zip_entry_name($zipEntry); if ($entryName == $searchEntryName) { if (zip_entry_open($zip, $zipEntry, "r")) { $searchFileContents = zip_entry_read($zipEntry, zip_entry_filesize($zipEntry)); zip_entry_close($zipEntry); zip_close($zip); return $searchFileContents; } } } zip_close($zip); } return false; } |
2. Parse JAR file manifest (MANIFEST.MF)
Once this is done, the MANIFEST.MF needs to be parsed. Manifest files have a very easy key-value format, with a colon (:) as a delimiter. This piece of code does the parsing for us:
1 2 3 4 5 6 7 8 9 10 11 12 |
function parseJarManifest($manifestFileContents) { $manifest = array(); $lines = explode("\n", $manifestFileContents); foreach ($lines as $line) { if (preg_match("/^([^:]+):\s*(.+)$/", $line, $m)) { $manifest[$m[1]] = trim($m[2]); } } return $manifest; } |
3. Using the functions
Combining these two functions, we can read the contents of a ZIP file entry with readZipFileEntry() and parse the JAR file manifest with parseJarManifest():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$manifestFileContents = readZipFileEntry("syncany-plugin-samba-0.4.0-alpha.jar", "META-INF/MANIFEST.MF"); $manifest = parseJarManifest($manifestFileContents); print_r($manifest); /* Array ( [Manifest-Version] => 1.0 [Plugin-Id] => samba [Plugin-Name] => Samba [Plugin-Version] => 0.4.0-alpha [Plugin-Operating-System] => all [Plugin-Architecture] => all [Plugin-Date] => Sun Dec 28 16:37:19 UTC 2014 [Plugin-App-Min-Version] => 0.4.0-alpha [Plugin-Release] => true [Plugin-Conflicts-With] => ) */ |
A. About this post
I’m trying a new section for my blog. I call it Code Snippets. It’ll be very short, code-focused posts of things I recently discovered or find fascinating or helpful. I hope this helps
Recent Comments