开发者

Creating UNIX safe test in PHP from windows

I'm trying to use PHP to create a shell script on Windows. It's part of some larger functionality.

Here's my script:

$contents_str = ''.
'#!/bin/bash
yes | apt-get update
yes | apt-get upgrade
useradd sudoer -g sudo -s /bin/bash -m
echo "sudoer:sudoerpass" | chpasswd';

However, when this file gets on the server, I get a "bad interpreter - no such file or directory" error. I know it's because I have some hidden windows characters in the file.

Is there a function or script I can use to remove hidden windows characters in PHP? Alternatively, is there a single bash command I can use to do this on the server?

I've used dos2unix on the file and it works after I do this, but I'd rather not use dos2unix because it's something I'd have to install on the server and I need something I can use right out of the Ubuntu box.

Thanks.

EDIT:

I just found a way to clean up the string using preg_replace.

Here's the code (of course, continuing from the code I already posted above):

$contents_nixsafe_str = preg_replace('/(\r\n|\r|\n)/s', "\n" , $contents_st开发者_如何学Gor);

This worked without any issues for me.

Thanks for all the responses


I assume you are using an editor that outputs line-ending (EOL) characters in Windows's CRLF format. Depending on the editor, you may be able to tell it to use UNIX line endings (LF) instead.

Alternatively, you can concatenate the lines together and manually append the EOL character:

$contents_str = ''
  .'#!/bin/bash'."\n"
  .'yes | apt-get update'."\n"
  .'yes | apt-get upgrade'."\n"
  .'useradd sudoer -g sudo -s /bin/bash -m'."\n"
  .'echo "sudoer:sudoerpass" | chpasswd';

It's ugly, but gets the job done.


try replacing newlines with the system newline constant

$contents_str = str_replace("\r\n", PHP_EOL, $contents_str);

Also, you may want to look at heredoc syntax for creating multiline strings, where you start and end a string with a special identifier (in this example STR):

$contents_str = <<<STR
#!/bin/bash
yes | apt-get update
yes | apt-get upgrade
useradd sudoer -g sudo -s /bin/bash -m
echo "sudoer:sudoerpass" | chpasswd
STR;


$contents_arr = array
(
    '#!/bin/bash',
    'yes | apt-get update',
    'yes | apt-get upgrade',
    'useradd sudoer -g sudo -s /bin/bash -m',
    'echo "sudoer:sudoerpass" | chpasswd'
);

$contents_str = implode("\n", $contents_arr);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜