Run windows exe from php

How to run abc.exe using php

I want php file to run exe file and display the exe file content when user goes to a particular url. I am trying to run exe file using php function exec(‘abc.exe’);. But I only see blank page.

Anyone know how to solve it or how to run exe file from php file correctly? Many thanks in advance.

5 Answers 5

To access the operating system with php you do the following

The $answer string will contain the information that the abc.exe prints out or returns.

You may need to format it using explode().

You can only run exe files if your php is runnning on a Windows machine. Futhermore, if you are on shared hostig, your hoster may have disabled the exec command.

If you are on a Windows machine, ‘abc.exe’ must be in the current directory or in the PATH.

To capture the output use:

You can use VaccinalBowl code in windows, but for address .exe file, see the following example :

I know this answer might be late but there is a «hack» in php you can use with Task Scheduler in Windows. The following code works and works with all browsers not just IE. However I should warn you that sometimes the program you are accessing may not run at that instant in time sometimes as I’ve noticed sometimes that the scheduled task may be in a «queued» state and not running. But the code does work 100%. it is just a matter of what state the task is in in task scheduler. either its «running» or «queued».

Encountered with permission problem even with 2&>1 (although chmod 777), but workaround by reading the output via saving into a file

See the example, cs_crypto is something to decrypt

«; //$output = shell_exec(«echo ./cs_crypto de aesbase $str»); //$output = shell_exec(«./cs_crypto de aesbase $str 2>&1»); exec(«./cs_crypto de aesbase $str > out»); $output = shell_exec(«tail -1 out»); //exec(‘./cs_crypto de aesbase $str’, $output, $return_var); //echo «»; echo «»; ?>

Run .exe file using PHP on Windows

I need to execute a .exe file located in C:\Program Files\ABC\test.exe on my windows machine using PHP. I have installed WAMPP/XAMPP to run PHP. I have tried the exec() system() shell_exec() but I’m unable to run the file. Can someone help me with the exact code?

    5 Contributors
  • forum 7 Replies 5,052 Views 2 Days Discussion Span
  • comment Latest Post 10 Years Ago Latest Post by chrishea

have you tried passthru() it is similar to the system command. If it does not work then it is probable that these command are disabled by your hosting provider.

Why would you want to run exe on local file system?
Can’t it be accomplished via pure PHP solution?

All 7 Replies

have you tried passthru() it is similar to the system command. If it does not work then it is probable that these command are disabled by your hosting provider.

Can you provide me the exact code of passthru() ?
I am using WAMPP on my local machine to test it. If the commands are disabled, can you help me identify and enable them?

Читайте также:  Wscript shell hide windows

Why would you want to run exe on local file system?
Can’t it be accomplished via pure PHP solution?

I need a execute a windows application from PHP. My whole website will be placed on a web hosting, just one process will run from my local system which will act as a web server and execute the windows application.

$result=passthru(‘dir’);
print $result;

I did some experimenting with Exec.

I had no problem starting a local program with Exec with one exception. If the path name contains a blank, I wasn’t able to get it to work. Even if the actual program name contains a blank, it works. One simple example that worked was:

$output has the display output from the program if it is writing to the current window. If it opens in its own window then you see the output there. An example of getting the output from the current window is as follows:

We’re a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.

Reach out to all the awesome people in our web development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

Создание EXE приложений на PHP

INTRO

Все мы знаем что PHP предназначен для быстрого создания динамических Web страниц. Во всяком случае именно это написано на официальном сайте разработчиков PHP. Однако почему бы не попробовать найти PHP «немного» иное применение, например, попробовать создать полноценное приложение для Windows? Заинтересовал? Тогда понеслась!

Чёрный квадрат

Приложения делятся на консольные и оконные. Начнём с создания первых, так как это проще. Итак, для начала нужно определиться с тем, что мы будем писать… я предлагаю написать простой MD5 & Base64 Encoder — вещь в хозяйстве нужная и полезная, тем более здесь всё достаточно просто. Для запуска PHP скрипта из командной строки и передачи ему нужных параметров используется следующая конструкция:

Что касается содержания самого скрипта, то количество переданных параметров хранится в переменной $argc, а сами параметры хранятся в массиве $argv. На этом краткий инструктаж по консольным приложениям закончен и пришла пора приступить к активным действиям.

Чтобы не утруждать Вас написанием скрипта, я решил написать его за Вас. Вот что у меня
получилось:

Скрипт написан и теперь самое интересное — компиляция в EXE приложение. Для компиляции консольных приложений я использую Roadsend Compiler Studio. Его можно скачать на сайте www.roadsend.com после бесплатной регистрации. Скачали? Теперь открываем Roadsend IDE, создаём новый проект (Project -> New), прописываем необходимые параметры (наш скрипт рекомендую кинуть именно в директорию проекта), жмём «OK» и наконец даём заветное Project -> Build. Теперь направляемся в папку с проектом и если Вы всё правильно сделали — в ней Вы найдёте готовый EXE. Это всё? Да. Всё просто, если знать некоторые нюансы. Единственное что я рекомендовал бы — иногда полезно пошаманить с подключаемыми библиотеками, а так же можно упаковать наш EXE UPX`м, хотя эту тему я затрону чуть ниже. Теперь перейдём к оконным приложениям…

Окошки

Как Вы наверное уже догадались — при создании оконных приложений штатными средствами PHP уже не обойтись, поэтому для начала нужно выбрать инструмент для разработки нашего окошка. Среди всех инструментов больше всего выделяются два — это достаточно раскрученый PHP-GTK (www.gtk.php.net) и менее раскрученный, но не менее функциональный WinBlider (www.winbinder.org). Здесь как раз тот случай, когда более раскрученный и известный оказывается не так уж и хорош (это моё имхо), поэтому для разработки нашей первой форточки на PHP мы будем использовать WinBlinder. Для начала его нужно скачать. Готово? Окей, двигаемся дальше…

Читайте также:  Basic linux privilege escalation

Винблиндер имеет свой собственный формат данных — phpw, который Вы можете сразу смело привязывать к вашему любимому редактору кода. По умолчанию при запуске phpw файла открывается содержащийся в нём PHP скрипт и прогоняется через интерпретатор с уже подключеными библиотеками блиндера. Как Вы наверное поняли — учится программировать на этой балалайке Вам придётся самим, однако в это нет ничего сложного, особенно человеку хоть немного знакомому с ООП в PHP. Однако даже незнакомый тоже сможет на нём кодить, так как по сути блиндер (в отличии от PHP-GTK) поддерживает и процедурное программирование. Кроме того WinBlinder весьма неплохо документирован, а инсталл архив уже содержит в себе несколько весьма любопытных примеров (особое внимание прошу обратить на редактор форм). У блиндера есть ещё куча фишек, функций и интересностей, но рамки данной статьи не позволяют мне на них останавливаться. Теперь пожалуй самое подходящее время вспомнить о нашем кодере. Чтобы не перегружать всё кодом я решил написать лишь MD5 Encoder:

bambalam -w -c C:\PHP_Projects\MD5_Hash_Generator\ md5.phpw md5.exe

Если всё сделано правильно, то в директории с компилятором будет лежать свежесколоченое оконное приложение. Всё. Добавлю лишь, что все приложения я ещё рекомендовал бы упаковывать UPX`ом (который идёт сразу с Bamcompile).

Волшебный ларец

Все вышесказанное конечно весьма интересне и познавательно, однако бывают моменты когда нужных инструментов под рукой нет… Что делать тогда? Специально для такого случая есть один весьма любопытный приём получения EXE через шаманство в опциях SFX архива WinRAR. В качестве примера я буду использовать наш первый скрипт для консоли. Для начала помещаем наш скрипт в отдельную папку, туда же копируем php.exe и php*ts.dll. Далее создаём в этой же папке run.bat следующего содержания:

Теперь нам необходимо это добро упаковать, для этого выделяем все файлы, жмём правой кнопкой и выбираем «Add to archive. ».

В появившемся окне выбираем формат архива RAR, выставляем максимальное сжатие и ставим галочку «Create SFX archive».

После этого переходим во складку «Advanced -> SFX Options», там выставляем переключатель на «Create in curent folder» и в «Run after extraction» прописываем «run.bat», а так же во вкладке «Modes» выставляем галочку «Unpack to temporary folder», а так же выставляем переключатели «Hide all» и «Overwrite all files».

По вкусу можете прилепить свою иконку в соответвующей вкладке. Теперь подтверждаем создание архива и на выходе получаем EXE без всяких компиляторов.

OUTRO

Итак, сегодня я показал Вам, как легко и просто можно раздвинуть границы использования PHP. Конечно кто-то всё это назовёт бредом, скажет мол размер у приложений большой, и память у них течет, и муторно всё это. Пусть говорят, однако никто не призывает Вас писать все оконные приложения на PHP, а данная статья лишь неплохое подспорье для пхп кодеров и всех интересующихся. На сим я закончу. Удачи.

How do I run a PHP script using windows schedule task?

I have installed localhost/server in my machine and I need to run a php script using windows schedule task. how do I add path in «Actions» tab in schedule task / cofigure the script to run for particular period?

Читайте также:  Команда set windows 10

12 Answers 12

Locate the php.exe executable on your system and pass it the name of the script file using the -f parameter.

Here’s how did it.

Windows scheduler -> create a new task -> action tab -> Edit

At least I tried out some suggestions but it doesn’t work so I tried this.

Use a bat file and schedule to execute that bat file.

For example in the bat file executephp.bat, write this

c:\xampp\php\php.exe -f c:\xampp\htdocs\do_something.php

save that bat file that contains that line.

Go to windows scheduler and create a new task and in action tab, browse to point that executephp.bat and for start in -> direct to the directory u have that executephp.bat.

For example if u save the file under C:\xampp\htdocs put that C:\xampp\htdocs in the start in.

Remember to invoke the script even when the user is not logged on.

Everything is set and it will execute without problem.

You can use PHP Command Line to execute it rather then trying to load it through the browser.

Under the actions tab, create a new action and:

  • Program/Script: Point to your PHP.exe file
  • Add Arguments: -f /path/to/php/file.php

Optionally you can make it start in the script’s directory as well.

I just wanted to leave what i had to do to get this working for server 2012. Which was what has previously been said but with added quotes and using the ‘Add arguments’ box. So in Task Scheduler->Actions->Edit Action.

(I had to use ‘start in’ as i referred to class’s within the script)

Hope this helps.

create Schedule task Scheduler->Actions->Edit Action

if you have php file

if you have MVC/CMS URL

Here’s how I did it.

In the Run box: c:\location_of_my_php_installation\php.exe -f c:\location_of_my_php_file\php_file.php

In the Start in box: c:\location_of_my_php_installation\php.exe

you can directly call your local host url by using

If the answer given by Pekka does not work ( C:\Xampp\php\php.exe -f C:\Xampp\htdocs\my_script.php ), make sure that you have the correct PHP extensions enabled as well as the correct php.ini file being used for the PHP version you are using.

I ran into this issue recently and resolved it. I was using PHP v5.4 to run my script.php that was nested within the top level PHP folder (v5.3). When I ran the script.php , from within the v5.4 folder, it was using the v5.3 php.ini file with different extensions, which caused the script.php to fail.

To fix this, here is what I did within the Task Scheduler : Actions tab

«C:\Program Files (x86)\PHP\v5.4\php.exe»

-c «C:\Program Files (x86)\PHP\v5.4\php.ini» -f «C:\Xampp\htdocs\script.php»

Using the -c option, you can specify which php.ini file should be used (stackflow answer).

I verified which php was in use by following this stackflow answer.

In command line, type php -m to check which extensions are enabled. Then, use php —ini to check which .ini file(s) is/are being read by PHP.

You may not be using the correct ini file for the PHP version you are using if you have multiple versions installed.

Оцените статью