Monday, January 29, 2024

[SOLVED] How to send commands to command prompt using php

Issue

$exec = exec("net use LPT1: \\XXXXXX\PRINTER1 \\PERSISTENT:YES");
    $exec = exec("E:");
    $exec = exec("COPY OUT.TXT LPT1");

tried shell_exec

 $exec = shell_exec("net use LPT1: \\XXXXXX\PRINTER1 \\PERSISTENT:YES");
$exec = shell_exec("E:");
$exec = shell_exec("COPY OUT.TXT LPT1");

tried popen

 $exec = popen("net use LPT1: \\XXXXXX\PRINTER1 \\PERSISTENT:YES", "r");
$exec = popen("E:", "r");
$exec = popen("COPY OUT.TXT LPT1", "r");

I have tried all this in my code,but i am not able to execute it.. can anyone give a solution


Solution

exec() will not show you any error messages that your calls may produce.

To debug the problem, you need to make those messages visible. Stealing from this question:

exec('(your command here) 2>&1',$output,$return_val);
if($return_val !== 0) {
    echo 'Error<br>';
    print_r($output);   
}

Also, I'm not sure whether executing E: will actually change the working directory for the following command(s). You're probably better off using absolute paths:

 exec("COPY E:\OUT.TXT LPT1");


Answered By - Pekka
Answer Checked By - Clifford M. (WPSolving Volunteer)