MATLAB with PHP [duplicate] - php

As the title indicates, I have MATLAB code for isolated spoken words recognition, and I want to be able to integrate this project with another one made with PHP for some purpose.
I have not used to deal with such problem before. In other words, it's the first time for me when I need to integrate PHP and MATLAB, so I really don't know where to start and how.
I have read a couple of articles, but I couldn't make it valid.
I have PHP 5.4.9, MATLAB R2012A and Windows 7.
The MATLAB project files can be seen on GitHub.

You have a few options here:
If MATLAB installed on the server where the PHP application would be deployed (not your current development environment), you can invoke it directly just like any other program (matlab -r "...") using whatever is the equivalent of EXECUTE command in PHP. Here are some resources (make sure to also checkout the linked questions as well):
How to call MATLAB from command-line and print to stdout before exiting
Running a cmd file without GUI popping up
Pass Parameters _ Shell Script - Octave Script
Others have commented on how to pass input/output between PHP and your MATLAB script. For example, you could design your MATLAB function to receive the path of WAV file as input, process it and save any resulting image to disk:
function myFunc(filename)
[y,Fs] = audioread(filename);
img = my_process_func(y, FS);
imwrite(img, 'out.png');
end
Which is invoked from PHP as:
% Of course you have to make sure "myFunc" is available on the MATLAB path.
% Think: "addpath(..)" or just "cd(..)" into the directory first
matlab -wait -nodisplay -r "myFunc('audio.wav'); quit;"
You could then read the output image in the PHP application.
If not, what deployment-related toolboxes do you have available? MATLAB Compiler and related toolboxes like MATLAB Builder NE and MATLAB Builder JA.
Those will compile your program into an executable/.NET Assembly/JAR file respectively, and all of them require the freely available MCR Runtime to be installed. In other words, the executables do not need to have a full MATLAB installation on the target machine, only the MCR runtime.
You would run the executable in the same manner as before.
Another product is the MATLAB Coder, which converts your MATLAB code into C++ program. When compiled, it can run without any external requirement.
A new product by MathWorks is MATLAB Production Server. Personally I know nothing about it :)
Yet another option is to use TCP/IP to communicate between PHP and MATLAB. A server would be run on the MATLAB side, using socket programming written as C MEX-file or a Java class. See:
MATLAB Mex Socket Wrapper Library
Writing Java's pw.println(), etc. in MATLAB
The client being your PHP application. The idea is to have MATLAB listening for connections, reading whatever input is given by a client, eval it, and return the result. This is more involved than the other options, as you have to deal with serialization and other things like concurrency. The advantage is that MATLAB can be run on a separate server, even on multiple servers on the cloud (see this post).
So first, decide what approach best suits your project, then it would be easier to answer specific questions... Just always consult the documentation first, MATLAB toolboxes are very well documented and usually include many examples. Here are a couple more resources specific to MATLAB Compiler products family:
Webinar: Application Deployment with MATLAB
PDF File: MATLAB Application Deployment - Web Example Guide
Note that they concentrate on ASP.NET and Java JSP/servlet applications. In your case, the PHP application would communicate with a middle tier running a web service built using one of the above two options (or simply design a CGI-like site running plain executables built using the MATLAB Compiler as explained earlier).

To help the OP with running system commands from a PHP webpage, my post here is relevant (copied below).
We do exactly this all the time. I call them voodoo pages. Here's some working code:
<?php
$command="uptime"; $output; $retval; $errors="";
exec ($command, &$output, &$retval);
echo $output[0] . "\n";
unset($output);
?>
And the output to the webpage served:
13:40:19 up 22 days, 23:14, 0 users, load average: 0.04, 0.02, 0.00
And the additional note I added in the comments below:
Relative vs absolute paths may be a pain... $command might need to be /usr/bin/uptime or another could be /usr/bin/ls /home/chris/ftp. Normally, scripts' working directory is where they live in the file system. MATLAB is a windows program, yes? My experience is you will need absolute paths for the program and any files passed as arguments, example: $command="c:\\matlab\\matlab.exe c:\\www\\somefile.wav" And then single quotes required for silly NTFS names, TAB command line completion works well for examples. Or use proper 8.3 name with the ~ in it.

My answer would be in two parts:
How do I run a MATLAB script from the terminal?
I will give some example about running a MATLAB script from the terminal:
matlab -nojvm -nodesktop -r "run <the-script>.m"
matlab -nojvm -nodesktop -r "<the-script>"
matlab -nojvm -nodesktop -r "run <the/path>/<the-script>.m"
matlab in Windows must be in your environment path. How-to.
If you need to compile your script to Java:
java -jar yourjarfile.jar
How do I execute the terminal command from PHP?
I think the previous answers are good, and there isn't any need to repeat them.
More notes:
Watch for your security. You might be XSS'ed easily.
Abstract your code and improve it to save parameters and output to the database. Run your code in
Parallels or queue manager. You might create a REST service.
Unit test.
Use Linux. It's much more powerful.

One quick hack would be to compile your MATLAB code into an executable file then use PHP's shell_exec().
The difficult part would be adapting your MATLAB code (sorry, I didn't read it) in such a way that:
It will receive its input in command-line-interface style (as char strings);
It will output its results as text to standard output (file id #1 in MATLAB).
Then all it takes is to parse the MATLAB output back into PHP...

Related

PHP compile string to bytecode without evaling it

Python (CPython and Jython at least, possibly all Pythons) have a function called compile that can be used to compile a file into a string into or a bytecode object.
# foo.py
a = compile("""
print(47)
""", filename="testfile", mode="exec")
exec(a)
Running foo.py produces:
$ python foo.py
47
Does PHP (Zend specifically, any version) expose its bytecode compiler to user code in a similar way? More specifically, can you dynamically compile strings without executing them like eval does.
i don't know but what you show me it's very familiar to this alternative you can improvise:
foo.php
<?php
print(47);
?>
index.php
<?php
include('foo.php');
?>
eg: so in php cli under windows cmd:
in any folder you have index.php and foo.php with xampp from apachefriends.org installed in c:\xampp create runme.bat
#echo off
set parameter=%1
set PHP_BIN="c:\xampp\php\php.exe"
%PHP_BIN% %parameter%
so from cmd you can call very easy cli interpretation of index.php :
runme index.php
also runme foo.php had the same results ,the only reason i put there index.php is to use it as a "proxy" between a somehow array list i store in and to include not only foo.php but manny others and in this way could became a kind of "controller" with not much modifies(if the question is pointing to sort of code executions in any order ordered by a kind of controller)
47
If you want to know whether PHP has the compile builtin function to compile the PHP code, there is no. PHP is a interpreted language, PHP code need interpreter to run it, and the interpreter has the executing environment for it.
But if you want to realize your requirement, here is some way to achieve it:
PHC
phc is an open source compiler for PHP with support for plugins. In addition, it can be used to pretty-print or obfuscate PHP code, as a framework for developing applications that process PHP scripts, or to convert PHP into XML and back, enabling processing of PHP scripts using XML tools.
bcompiler
To encode entire script in a proprietary PHP application
To encode some classes and/or functions in a proprietary PHP application
To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
To do the feasibility study for a PHP to C converter
3.Project Zero
It supports the PHP compile.

Running a C program executable in a server with LAMP - what modifications to the C code?

I am planning on putting the executable of a C program in a server and running it using a PHP script - as a Web API: e.g. echo exec("myscript.exe")
Currently the myscript runs on command prompt - it takes two input files and return an integer or float number. Currently the code takes the input files on the command prompt.
What modifications are needed to the existing program - I heard about HTTP bridge and daemon but not sure what I need, if any?
Update:
Currently the only other dependency is libsndfile - that is available on Linux. The C program was developed on Linux.
The answer actually depends on the APIs the C application is using. If the C application is using just the Standard C library, then you just need to recompile the application on the target system and invoke the name of the executable. However if you depend on any Windows based APIs such as COM, WinINET, etc you will need to run the executable on another system and have some sort of IPC mechanism between them.
Quick and simple (assuming your ouptut is a single text line on stdout:
exec("yourprog.exe file1 file2",$res);
echo "result is " . $res[0];

How to import custom bash functions to be used in PHP exec/system/etc?

I'm writing a command-line application that will substitute a bunch of bash functions and manual work made by a team of developers. Currently, half of what we usually do is inside a ~/.functions file that is sourced in the ~/.bash_profile of each developer.
My command-line application is written in PHP, and for a while I would need to run some of those functions from inside my application. However, the following code would not work, the output says it cannot find the given function:
exec('bash my_legacy_functions.sh');
exec('my_custom_legacy_function param1 param2');
I may be wrong, but I could understand that every exec() call runs a command in a separate process, meaning the functions would not be available for subsequents exec() calls. Is this right, and if yes, would it be possible to override this behaviour without having to bundle everything into one call?
In the end it turns out the default shell was not bash, and on top of that source is not a common command in bash. I found by this other question's answer that the solution is something like:
function run($cmd) {
exec("bash -c 'source my_legacy_functions.sh; $cmd'");
}

How to open an application via php and perl?

I am trying to print generated forms / receipts through PHP (the printers will be installed on the server, I am not attempting to print to a user's local printer). I have decided to try the following methodology:
IN PHP:
Generate a PDF file and save it on the server.
Call a perl script to print said PDF file.
IN perl:
Use system() to "open" Reader and print the given PDF silently.
What works:
I can generate PDFs in PHP.
I can call a perl script.
If the script has errors, they report to the browser window. ie: If I purposely change file paths it fails, and reports the appropriate reason.
functions such as printf seem to work fine as the output displays in the browser.
The exact same perl script (with the "non-functioning" line mentioned below) works properly when executed from the command line or the IDE.
What doesn't work:
In perl: system('"C:\\Program Files (x86)\\Adobe\\Reader 10.0\\Reader\\AcroRd32.exe" /N /T "C:\\test.pdf" 0-XEROX');
What happens:
NOTHING! I get no errors. It just flat out refuses to open Adobe Reader. All code below this line seems to run fine. It's like the function is being ignored. I am at a loss as to why, but I did try a few things.
What I've tried:
Changed permissions of the AcroRd32.exe to Everyone - Full Control.
Output the $? after the system() call. It is 1, but I don't know what 1 means in this case.
Verified that there are no disable_functions listed in php (though I think this is unrelated as shell_exec seems to be working, since some of the perl code is ran).
Various other configurations that at least got me to the point where I can confirm that PHP is in fact calling the perl script, it just isn't running the system() call.
Other info:
Apache 2.2.1.7
PHP 5.35
Perl 5.12.3 built for MSWin32-x86-multi-thread
WampServer 2.1
I'm at a loss here, and while it seems like this is an Apache / permissions problem, I cannot be sure. My experience with Apache is limited, and most of what I find online is linux commands that don't work in my environment.
Try this:
my #args = ('C:/Program Files (x86)/Adobe/Reader 10.0/Reader/AcroRd32.exe');
if (system(#args) != 0) {
# Can't run acroread. Oh Noes!!!
die "Unable to launch acrobat reader!\n";
}
The thing about system() is that it does two different things
depending on the number and type(s) of argument it gets. If the
argument is an array or if there are multiple arguments, Perl assumes
the first is the program to run with the rest as its arguments and it
launches the program itself.
If, however it's just one string, Perl handles it differently. It
runs your command-line interpreter (typically CMD.EXE on Windows) on
the string and lets it do what it wants with it. This becomes
problematic pretty quickly.
Firstly, both Perl and the shell do various kinds of interpolation on
the string (e.g. replace '//' with '/', tokenize by space, etc.) and
it gets very easy to lose track of what does what. I'm not at all
surprised that your command doesn't work--there are just so many
things that can go wrong.
Secondly, it's hard to know for sure what shell actually gets run on
Windows or what changes Perl makes to it first. On Unix, it usually doesn't matter--every shell does more or
less the same with simple commands. But on Windows, you could be
running raw CMD.EXE, GNU Bash or some intermediate program that
provides Unix-shell-like behaviour. And since there are several
different ports of Perl to Windows, it could well change if you
switch.
But if you use the array form, it all stays in Perl and nothing else
happens under the hood.
By the way, the documentation for system() and $? can be found here and here. It's well worth reading.

link PHP with Octave or Matlab

Suppose I have a lot of math calculations which are quite tedious to implement in php. Is it possible to somehow link PHP and Octave on the server in such a way, that php sends parameters to Octave and receives answers back.
Has anyone tried anything similar?
Another solution is to use octave-daemon, which was written specifically for this purpose. Works on Linux, don't know about Windows.
You can use matlab compiler to make an executable matlab application, that you can call from php.
GNU Octave can be called from PHP using the Linux command line, using commands like exec() or passthru(). Anyway, their appropriate use depends on what you are trying to do (there are no details of your problem).
One way to do it, in Windows, is to compile Matlab as a DLL and include it ona web app (a WFC service, for example). At that point you have a functional "matlab service" and then you can access that service from PHP or any other language.
It is also possible to create a .NET component using Matlab Builder NE, and deploy it using SilverLight on the web.

Categories