从PHP脚本执行centos命令

时间:2011-11-03 04:53:07

标签: php scripting exec centos

我正在使用centos服务器而且我必须以tbz格式从不同的服务器下载数据到centos服务器,然后我必须提取它并在完成提取后我必须将数据从它导入到mysql数据库表

我正在做的是 从服务器获取大小约为700MB的数据,但是当我执行命令来提取数据时,其他任何事情都没有发生。

$files =   array('20111101.tbz', '20111101.tbz.md5' ,'20111102.tbz' ,'20111102.tbz.md5') ;

    //folder names of the folders formed
    $folder1 = "20111101";
    $folder3 = "20111102";

    //command to extract all the downloaded .tbz files
    $command1 = "cd /var/www/html/mywork1/mywork2/mywork3/";
    exec($command1." 2>&1", $output);
    $command2 = "tar -xjf ".$files[0];
    exec($command2." 2>&1", $output);
    $command4 = "tar -xjf ".$files[2];
    exec($command4." 2>&1", $output);

    //command to populate the data into the database
    $command6 = "cd /var/www/html/mywork1/mywork2/mywork3/mywork4";
    exec($command6." 2>&1", $output);
    $command7 = "./runit.py /var/www/html/mywork1/mywork2/mywork3/$folder1";
    exec($command7." 2>&1", $output);
    $command9 = "./runit.py /var/www/html/mywork1/mywork2/mywork3/$folder3";
    exec($command9." 2>&1", $output);

    //command to remove the folders created after population of data
    $command10 = "rm -rf $folder1";
    exec($command10." 2>&1", $output);
    $command11 = "rm -rf $folder3";
    exec($command11." 2>&1", $output);

    foreach ($files as $file) 
    {
        //command to remove all .tbz files downloaded.
        $command12 = "rm -rf $file";
        exec($command12." 2>&1", $output);
    }

我只是执行命令,但它没有做任何事情。但是当我在服务器上手动尝试所有这些命令时,它们工作正常。任何人都可以指导我吗?这样做的正确方法应该是什么?

1 个答案:

答案 0 :(得分:1)

你不能exec("cd /some/dir");,因为这会启动一个shell,它会转到这个目录,然后退出。对于你的PHP程序,它什么都不做 - 工作目录不会改变。

您需要chdir('/some/dir') or die("Cannot change directory");