Using cmd.exe from PHP

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Using cmd.exe from PHP

Post by timvw »

Most people seem to run into trouble when their commands (or command arguments) have special charaters and need quotes..
Here is my simple cmd function that takes care of this:

Code: Select all

<?php
function cmd($command, $arguments = null)
{
        $commandline = ‘’;
        foreach(func_get_args() as $word) {
                $commandline .= ‘"’ . $word . ‘" ‘;
        }
        $commandline = rtrim($commandline, ‘ ‘);
        $commandline = ‘"’ . $commandline . ‘"’;
        return `$commandline`;
}
?>
For some reason the highlighter seems to remove the slashes in my code...

// run blah.exe
cmd(‘blah.exe’);

// run c:\my path\blah.exe with the arguments "foo" and "bar bar"
cmd(‘c:\my path\blah.exe’, ‘foo’, ‘bar bar’);
User avatar
R4000
Forum Contributor
Posts: 168
Joined: Wed Mar 08, 2006 12:50 pm
Location: Cambridge, United Kingdom

Post by R4000 »

Code: Select all

// run blah.exe
cmd(‘blah.exe’);

// run c:\my path\blah.exe with the arguments "foo" and "bar bar"
cmd(‘c:\my path\blah.exe’, ‘foo’, ‘bar bar’);
(i got no errors with slashes :P, might be cause the highlighter was recently upgraded)
User avatar
m0u53m4t
Forum Contributor
Posts: 101
Joined: Wed Apr 19, 2006 7:47 am
Location: Wales

Post by m0u53m4t »

So if i wanted to command telnet through cmd to connect to mx2.hotmail.com on port 25... what would that code be like?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

telnet is an interactive problem, so you would need something like expect.. Or pipe the commands...
Or open a socket and fwrite/fread with native php functions...

Anyway, it is off-topic in here.
Post Reply