从Windows7中的php命令行脚本复制到剪贴板



我有一个php(5.5)脚本,在Windows7中从命令行运行。类似这样的东西:

C:php-5.5.5php.exe C:scriptsputString.php

我的问题是,是否可以从脚本中将某些内容复制到windows剪贴板?我希望用户在从命令行运行此脚本后,在剪贴板中有一些可用的文本。如何做到这一点?

如果您想将一些中间结果添加到剪贴板,而不是整个脚本的输出

//...your script...
$someVar="value";
shell_exec("echo " . escapeshellarg($someVar) . " | clip");
//rest of script...

使用剪辑:

C:php-5.5.5php.exe C:scriptsputString.php | clip

首先我想指出@chiliNUT的解决方案是不安全的,它很容易受到shell注入的影响,例如

$someVar="foo | del /S C:windowssystem123";
shell_exec("echo $someVar | clip");

将尝试删除您的C:\windows\system123文件夹,因为命令变为

echo foo | del /S C:windowssystem123 | clip

这是一个可移植的函数,应该在Windows7+(PowerShell 2+)、基于X.org的linux系统和MacOS:上运行

function getClipboard():string{
    if(PHP_OS_FAMILY==="Windows"){
    // works on windows 7 + (PowerShell v2 + )
    // TODO: is it -1 or -2 bytes? i think it was -2 on win7 and -1 on win10?
        return substr(shell_exec('powershell -sta "add-type -as System.Windows.Forms; [windows.forms.clipboard]::GetText()"'),0,-1);
    }elseif(PHP_OS_FAMILY==="Linux"){
        // untested! but should work on X.org-based linux GUI's
        return substr(shell_exec('xclip -out -selection primary'),0,-1);
    }elseif(PHP_OS_FAMILY==="Darwin"){
        // untested! 
        return substr(shell_exec('pbpaste'),0,-1);
    }else{
        throw new Exception("running on unsupported OS: ".PHP_OS_FAMILY." - only Windows, Linux, and MacOS supported.");
    }
}

至于写入剪贴板:

function setClipboard(string $new):bool{
    if(PHP_OS_FAMILY==="Windows"){
        // works on windows 7 +
        $clip=popen("clip","wb");
    }elseif(PHP_OS_FAMILY==="Linux"){
        // tested, works on ArchLinux
        $clip=popen('xclip -selection clipboard','wb');
    }elseif(PHP_OS_FAMILY==="Darwin"){
        // untested! 
        $clip=popen('pbcopy','wb');
    }else{
        throw new Exception("running on unsupported OS: ".PHP_OS_FAMILY." - only Windows, Linux, and MacOS supported.");
    }
    $written=fwrite($clip,$new);
    return (pclose($clip)===0 && strlen($new)===$written);
}

相关内容

  • 没有找到相关文章

最新更新