search
HomeBackend DevelopmentPHP Tutorialphp上传apk后自动提取apk包信息的使用(示例下载)_php实例

进入公司第一个项目就是做market市场。所以后台要上传APK软件之类。为了方便,上传APK后由系统自动提取APK文件的相关信息,比如:apk包名、产品名称、版本信息、APK Code、程序大小、ICON等。起初处理方式

通过命令:java -jar AXMLPrinter2.jar AndroidManifest.xml > cmdAfter.xml
得到cmdAfter.xml文件,然后分析cmdAfter.xml文件获取相关信息。

但是遗憾的是,从这文件中可以得到apk包名,但无法得到ico图标文件名及其它相关信息。如下图所示

上图中,比如label、icon等都是标志值,无法直接得到需要的结果。曾经分析该值与APK文件内部文件的关系,但不同的APK构造不同,实现过于麻烦。事实上,网上一些安桌市场等网站,当你上传APK时,除了提取出APK包名外,还包括ICON图标、大小等信息。因此,即然别人可以实现,我想肯定有办法来解决这个事情。于是经过研究,得到预期结果。在此将方法做个记录,欢迎交流。

核心提取APK信息代码
复制代码 代码如下:

  /***
   * 分析已上传的APK文件,提取所需要的数据
   */
  function upAPK(){
    global $_config_product_apktool_count;//使用apktool.jar解压的次数,原因下面有说明。
    if($this->msg!='')return;//如果有错误,返回
    $dir=$this->upload_path;//上传路径
    $stringsXML_exists=false;
    if(file_exists($dir.'package/res/values/strings.xml'))unlink($dir.'package/res/values/strings.xml');
    for($i=0;$i      //针对UC的APK包或其类似的APK包,解压一次并不能完全得到strings.xml文件或相关文件。目前只有采用这个办法了。
      //在系统cmd下直接使用java -jar ...执行解压,有时可以得到strings.xml文件,有时也得不到,不知道是不是jar包的问题。
      exec('java -jar ../apktool.jar d -f '.$this->tmpFile.' '.$dir.'package');//注释:解压完毕再往下执行
      $stringsXML_exists=file_exists($dir.'package/res/values/strings.xml');
    }
    //检查AndroidManifest.xml文件是否存在,如果不存在,则不是合法的APK文件
    if(!file_exists($dir.'package/AndroidManifest.xml')){$this->msg='不是合法的APK文件,请重新上传!';return;}
    $AndroidManifestXML=file_get_contents($dir.'package/AndroidManifest.xml');//读取AndroidManifest.xml

    if(preg_match('/package=\"([^\"]*)\"/i',$AndroidManifestXML,$package))$returnVal['package']=$package[1];//如果有包名,返回到数组

    //增加versionCode
    if(preg_match('/versionCode=\"([^\"]*)\"/i',$AndroidManifestXML,$versionCode))$returnVal['versionCode']=$versionCode[1];//如果有版本代码,返回到数组

    //检测到包名后判断数据库中是否已经存在。
    if($this->id==0){//添加新产品时检测,修改产品不检测
      if($returnVal['package']!=''){
        $sql='select id from product where package='.SqlEncode($package[1]);
        $result=mysql_query($sql);
        if(mysql_num_rows($result)>0){
          $this->msg='该APK已经存在,请更换!';
          return;
        }
      }else{
        $this->msg='系统无法检测该APK信息,请联系管理员!';
        return;
      }
    }

    if($stringsXML_exists)$stringXML=file_get_contents($dir.'package/res/values/strings.xml');//如果有strings.xml则读取strings.xml文件
    if(preg_match('/versionName=\"([^\"]*)\"/i',$AndroidManifestXML,$ver))$returnVal['ver']=$ver[1];//如果有版本号,返回到数组
    //版本号的情况目前发现有两种:1、版本号在AndroidManifest.xml中直接列出;通过以上正则即可提取
    //2、版本号同label一样,放到strings.xml文件中
    //2011-11-23 add
    if($stringXML!='' && strstr($ver[1],'@')){
      if(preg_match('/^@string\/(.*)/i',$ver[1],$findVer)){
        if(preg_match('/([^/',$stringXML,$a))$returnVal['ver']=$a[1];
      }
    }
    ////////////////////////////////////////////
    if(preg_match('/    if($stringsXML_exists && preg_match('/      if(preg_match('/([^/',$stringXML,$name)){
        $returnVal['name']=$name[1];//如果有产品名称,返回到数组
        /**
        百度:strings.xml
        特殊情况1:"  掌上百度  "
        */
        $returnVal['name']=preg_replace('/\s|"/','',$returnVal['name']);
      }
    }
    //$this->msg=$returnVal['package'].'--'.$returnVal['ver'].'--'.$returnVal['thumbimg'].'--'.$returnVal['name'];
    if($this->oldAPK!=''){//重新上传则删除原apk文件和icon.png图片
      unlink($dir.$this->oldAPK);
      unlink($dir.$this->oldAPK.'.png');
    }
    //遍历package/res目录下的目录[drawable|drawable-hdpi|drawable-nodpi|drawable-ldpi|drawable-mdpi]
    //系统取icon尺寸最大的图标
    $tmpArr[0]=0;$tmpArr[1]=0;$tmpArr[2]='drawable';
    $dirs=opendir($dir.'package/res');
    while(($file=readdir($dirs))){
      preg_match('/(drawable(-.*?dpi)?)/i',$file,$drawable_folder);
      $iconPath=$dir.'package/res/'.$drawable_folder[1].'/'.$returnVal['thumbimg'].'.png';
      if(file_exists($iconPath)){
        $iconInfo=getimagesize($iconPath);
        if($iconInfo[0]>$tmpArr[0] && $iconInfo[1]>$tmpArr[1]){
          $tmpArr[0]=$iconInfo[0];$tmpArr[1]=$iconInfo[1];$tmpArr[2]=$drawable_folder[1];
        }
      }
    }
    //$this->msg=$iconInfo[0].'---'.$iconInfo[1];
    closedir($dirs);
    if(rename($dir.'package/res/'.$tmpArr[2].'/'.$returnVal['thumbimg'].'.png',$dir.$this->iframe_key.'.apk.png')){//找到目录并成功移动
      $returnVal['thumbimg']=$this->iframe_key.'.apk.png';
    }
    if(!move_uploaded_file($this->tmpFile,$dir.$this->iframe_key.'.apk')){$this->msg='上传失败!';return;}//转移apk文件
    $returnVal['filename']=$this->iframe_key.'.apk';
    $returnVal['size']=$this->size;
    $this->result=$returnVal;
  }   


提取信息流程

1、首先,通过apktool.jar命令提取apk文件中package/res/values/string.xml文件。不知为什么原因,释放apk文件时,有时并不一定得到string.xml文件。所以,后台增加:$_config_product_apktool_count参数,来控制释放的最大次数。

2、读取释放根目录下的AndroidManifest.xml文件。从该文件中可以获取到APK包名、版本信息。

3、检测,如果是新上传的APK,则其包名在数据库中是否存在。就是禁止上传相同包名的APK。修改时不检测。

4、通过正则获取所需要的信息。

这里为什么要提取string.xml文件?

因为并不是所有信息,都在AndroidManifest.xml中。有的信息在AndroidManifest.xml中只是做为一个“引用”,真实记录是在string.xml中的。比如

AndroidManifest.xml中关于Label和icon的值。

上图中:label="@string/app_name" 表明在string.xml中string的name属性为app_name的值,即为该APK的“软件名称”,这里是“Market市场”,如下图所示:

@drawable/quickflick_icon,表示quickflick_icon为ICON的文件名。

由于特殊需要,我需要找到最大的ICON图标,见下面代码:

复制代码 代码如下:

     //遍历package/res目录下的目录[drawable|drawable-hdpi|drawable-nodpi|drawable-ldpi|drawable-mdpi]
    //系统取icon尺寸最大的图标
    $tmpArr[0]=0;$tmpArr[1]=0;$tmpArr[2]='drawable';
    $dirs=opendir($dir.'package/res');
    while(($file=readdir($dirs))){
      preg_match('/(drawable(-.*?dpi)?)/i',$file,$drawable_folder);
      $iconPath=$dir.'package/res/'.$drawable_folder[1].'/'.$returnVal['thumbimg'].'.png';
      if(file_exists($iconPath)){
        $iconInfo=getimagesize($iconPath);
        if($iconInfo[0]>$tmpArr[0] && $iconInfo[1]>$tmpArr[1]){
          $tmpArr[0]=$iconInfo[0];$tmpArr[1]=$iconInfo[1];$tmpArr[2]=$drawable_folder[1];
        }
      }
    }
    //$this->msg=$iconInfo[0].'---'.$iconInfo[1];
    closedir($dirs);
 

经过分析,一般APK中存放ICON图标在以下几个目录:drawable|drawable-hdpi|drawable-nodpi|drawable-ldpi|drawable-mdpi,通过遍历比较的方式获取最大ICON图标,并移到临时目录。

将所有需要提取的信息,存到一个数组中,并通过javascript写到表单中。如下图所示:

提取APK信息总结

上面的代码,目前为止,在提取上传的APK中,能能正常提取信息,未发现错误。在上面代码的注释中也看到,关于“掌上百度”这款APK,提取不了信息,是由于他的特殊处理方式,即:"  掌上百度  ",他在名称中加上了双引号,这算是一个特例了吧。更多的特例我目前还未发现,所以,有可能会有特例出现,这需要分析APK的数据,并在程序中做特殊处理。

在实现这个APK提取功能中,关键是要找到APK包的组织规律,只有找到规律,程序实现就是在自然不过的事。

释放APK文件注意内容

exec('java -jar ../apktool.jar d -f '.$this->tmpFile.' '.$dir.'package');

能顺利执行上面的语句,要符合下面条件:

1、安装java包,对java目录,users用户组的权限有:读取和运行、列出文件夹目录、读取

2、cmd.exe文件,users用户组的权限有:读取和运行、读取

3、PHP允许调用exec

4、上传目录要确保有写入文件的权限

如果有更好的提取方式,欢迎交流,相互学习。

PHP提取APK信息DEMO演示下载

下载地址:http://xiazai.php.net/201304/yuanma/php_apk_phpnet.rar

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

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.