简体   繁体   中英

Copy to clipboard from php command line script in Windows 7

I have a php (5.5) script which I run from the command line in Windows 7. Something like this:

C:\php-5.5.5\php.exe C:\scripts\putString.php

My question is, is it possible to copy something to windows clipboard from the script? I want users to have some text available in the clipboard after running this script from the command line. How can it be done?

If you want to add some intermediate result to the clipboard, instead of the output of the entire script

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

使用剪辑:

C:\php-5.5.5\php.exe C:\scripts\putString.php | clip

first i'd like to point out that @chiliNUT's solution is NOT safe, it's vulnerable to shell injection, for example

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

will try to delete your C:\\windows\\system123 folder, as the command becomes

echo foo | del /S C:\windows\system123 | clip

...

here is a portable function that should work on Windows 7+ (PowerShell 2+), X.org-based linux systems, and 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.");
    }
}

as for writing TO the clipboard:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM