首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从php-cli访问剪贴板?

从php-cli访问剪贴板?
EN

Stack Overflow用户
提问于 2018-10-22 09:21:29
回答 2查看 1.3K关注 0票数 2

有什么方法从php-cli访问剪贴板吗?对于Windows,我特别需要它,但是跨平台的解决方案也很好。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-22 11:03:49

应该在Windows 7+ (PowerShell 2+)、基于x.org的linux系统和MacOS上工作的可移植功能:

代码语言:javascript
复制
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.");
    }
}

至于写信给剪贴板:

代码语言:javascript
复制
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);
}
票数 2
EN

Stack Overflow用户

发布于 2018-10-23 08:08:08

$someVar=“值”;

Shell_exec(“回波$someVar片段”);

参考文献:Copy to clipboard from php command line script in Windows 7

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52926026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档