Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php exec() in unicode mode?

Tags:

php

utf-8

cmd

exec

I need to execute command line commands and tools that accept ut8 as input or generate an ut8 output. So i use cmd an it works, but when i try this from php with exec it doesn't work. To make it simple i tried simple output redirection.

When i write direct in command prompt:

chcp 65001 > nul && echo цчшщюя-öüäß>utf8.txt

The uft8.txt is created an the content is correct.

цчшщюя-öüäß

When i use the exec function from php:

$cmd = "chcp 65001 > nul && echo цчшщюя-öüäß>utf8.txt";
exec($cmd,$output,$return);
var_dump($cmd,$output,$return);

the content in the utf8.txt is messed up:

¥Å¥Î¥^¥%¥Z¥?-ÇôǬÇÏÇY

I am using Win7,64bit with (Console) Codepage 850.

What should i do to fix that?

Additional Infos: I am trying to overcome some issues with reading and writing of utf8 filenames on windows. PHP file functions fail: glob, scandir, file_exists can't handle utf8 filenames correctly. File are invisible, skipped, names are changed ... Therefore i want to avoid php file functions and i am looking for some php extern filehandling.

like image 366
code_angel Avatar asked Nov 11 '12 15:11

code_angel


1 Answers

Since i couldn't find an easy, fast and reliable internal php solution, i am ending with using that i know it's work. Cmd-Batch-File. I make a small function that generate a cmd batch file in runtime. Its just prepends the the chcp (change the codepage) command in order to switch to unicode. And parse the output.

function uft8_exec($cmd,&$output=null,&$return=null)
{
    //get current work directory
    $cd = getcwd();

    // on multilines commands the line should be ended with "\r\n"
    // otherwise if unicode text is there, parsing errors may occur
    $cmd = "@echo off
    @chcp 65001 > nul
    @cd \"$cd\"
    ".$cmd;


    //create a temporary cmd-batch-file
    //need to be extended with unique generic tempnames
    $tempfile = 'php_exec.bat';
    file_put_contents($tempfile,$cmd);

    //execute the batch
    exec("start /b ".$tempfile,$output,$return);

    // get rid of the last two lin of the output: an empty and a prompt
    array_pop($output);
    array_pop($output);

    //if only one line output, return only the extracted value
    if(count($output) == 1)
    {
        $output = $output[0];
    }

    //delete the batch-tempfile
    unlink($tempfile);

    return $output;

}

Usage: just like php exec():

utf8_exec('echo цчшщюя-öüäß>utf8.txt');

OR

uft8_exec('echo цчшщюя-öüäß',$output,$return);

like image 82
code_angel Avatar answered Oct 24 '22 03:10

code_angel