I have a Python script that interfaces with an API. The script is started from a PHP page. I wrote both scripts, so I can change the code in either as appropriate.
The Python script needs a username and password to interface with the API. My first inclination is to pass them to Python as CLI arguments:
<?php
exec('python someScript.py AzureDiamond hunter2');
?>
However, anybody can then see the credentials via ps:
$ ps | grep someScript
1000 23295 2.0 0.2 116852 9252 pts/0 S+ 15:47 0:00 python someScript.py AzureDiamond hunter2
Alternatives that I am considering are to write the data to a text file or sqlite database, then to delete them. Are there any better ideas? A constraint with the sqlite approach is that this needs to run in a rather portable fashion (phpFox Plugin) and most budget webhosts don't support the sqlite3 module.
You could use environment variables which you set in PHP and read in the Python script.
The proposed methods are a security problem waiting to happen. MyProxy is a secure way to handle private keys or certificates. MyProxy might not be the particular solution you need, but these types of solutions are what you need to be looking at.
http://grid.ncsa.illinois.edu/myproxy/
You could use stdin in the python process to read the parameters, and open the process like this from php:
<?php
$handle = popen("/bin/python /var/www/someScript.py", "w");
// write username and password to $handle (e.g. newline separated)
?>
I don't know how secure this is against other processes running as the same user (could it by hijacked from /proc/nn/fd/0 ?), but it certainly makes it harder than just looking at the process list.
Looking at the problem from another angle, it could be solved if you hide the plain characters being passed to exec(). Have you considered using any cryptograhic lib to hide plain text from the sender and decrypt in the receiver? Just a thought.
Related
I'm trying to read specific div-elements of a website with a script either written in php or perl.
Unfortunately, the page requests a login before those specific site can be read. As I can see, it's ssl-protected. I'm not looking for a complete solution, I just need a hint regarding the best way to tell the script the informations needed for logging in (user+password), before reading parts of the sourcecode of the page that comes afterwards.
I'm not quite sure if it's better to do this with PERL or PHP, so i have tagged this question with both of these languages.
Mojo::UserAgent (see cookbook) has a built-in cookie jar and can do SSL if you have IO::Socket::SSL installed. It has a DOM parser which can easily use CSS3 selectors to traverse the returned result. And if that wasn't good enough, the whole thing can be used non-blocking (if that's something you need).
Mojo::UserAgent and the other tools listed above are parts of the Mojolicious suite of tools. It's a Perl library, and I would certainly recommend Perl for this task since it is a more general purpose language than PHP is.
Here is a very simplistic example to get the text from all the links that are inside a div with a class myclass
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
$ua->post( 'http://mysite.com/login' => form => { ... } );
my #link_text =
$ua->get( 'http://mysite.com/protected/page' )
->res
->dom('div.myclass a')
->text
->each;
In fact, running this shell command may be enough to get you started (depending on permissions)
curl -L cpanmin.us | perl - -n Mojolicious IO::Socket::SSL
I'm not entirely sure the wording for the title is correct, but what I'm attempting to do is run and execute PHP files from within the Lift framework.
I'm not after any url queries to a PHP file residing on a server, more interested in somehow getting the PHP runtime working through my Scala/Lift app.
Use case: I have my app packaged into a .war file, I host this via a cloud provider. I upload code snippets to said app which then runs the php file and does whatever necessary.
I've seen various posts regarding Bianca but am hoping to keep this setup light and require only the PHP binary itself and a little code to get it flying.
Thanks in advance, please let me know if you need me to elaborate :)
“Never say never, because limits, like fears, are often just an
illusion.”
― Michael Jordan
What you really need is an open source (GPL), embeddable, full PHP 5 implementation, written entirely in Java!
Caucho's Quercus PHP Java runtime is just that, and it will let you run PHP within a Java app without external libraries or native code.
Below is a Quercus-PHP-in-Java code sample I found in this answer
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
String phpCode = "<?php $foo = strlen('abc'); print $foo; return 'yikes'; ?>"; //PHP Code as String
Object o = engine.eval(phpCode);
System.out.println(o);
It should be little effort to convert this code to idiomatic Scala. Obviously, the 'phpCode' variable could be constructed from external PHP file contents etc.
Let us know how you get on ;-)
That's a bit of an odd requirement, but if it's what you need to do, you can use a ProcessBuilder to execute and interact with your PHP script from the command line.
I'm building a service, which has a few cronjobs running, written in Python. However, this is my first Python-project ever, so I'm still a very beginner.
What I'm doing now, is that I have my database-connection handled on every file, so basically if I wanted to change the host, I would need to go through all the files. I'm now looking into a PHP-include() similar method for Python, so that I could include some general stuff instead of copy-pasting.
Also, the Python-files are ran in cronjob, so the method should work on cronjobs too :)
If it's really just a couple of settings for a single database connection, just put it in a Python module and import it in all of your files. Why add any complexity you don't need?
If it's more complicated, use ConfigParser as #AdamMatan suggested.
# dbconfig.py
host = '127.0.0.1'
user = 'stack'
password = 'overflow'
# db.py
import dbconfig
print dbconfig.host
print dbconfig.user
print dbconfig.password
Use an external configuration file, with your db connection (host, name, password, db, ...) in it, and read the configuration file from within the Python script.
This makes changes easy (even for non-programmers) and nicely complies with the Single Choice Principle.
Example:
db.cfg
[db]
host=127.0.0.1
user=stack
password=overflow
db.py
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('db.cfg'))
print config.get('db', 'host')
Execution result:
127.0.0.1
If you need to call __import__(), you are doing it wrong.
You need to refactor your code so that you no longer have the database connection routines scattered throughout your codebase. Yes, it would be even nicer to have these details in a configuration file (+1 #Adam Matan), but first you need to eliminate the duplication. This will save you a world of pain in the long run.
I primarily work in PHP and prefer to do so since there seem to be more jobs in this language, at least in my area (and I'm still fairly new to it so I want to continue to learn the language better).. but for some things I want to do I need to use the WWW Mechanize library that doesn't work with PHP but does with Ruby (yes I know PHP has some alternatives but I have tried them and they don't work for me so I need to do this), so I'd like to write most of my app in PHP and then just call Ruby when I need to use this library, then pass the info back to PHP, yes I know this would be "slow" but thats not an issue in this case as this isn't a public web app, its just for business use..
I'm wondering what the best way would be to pass info between the 2 languages.. I have thought of using http POST (like with Curl in PHP) to do this but not sure if this is the most efficient way any.. any info is appreciated, thanks
There are two different ways that I would do this:
\1. In ruby, set up a non-HTTP server that only listens on '::' (or 127.0.0.1 if you don't like ipv6). Then, every time your PHP script needs to do something, it can connect to the server and pass data to it. This would be the fastest solution because the ruby script doesn't need to start up every time PHP needs to do something.
Example Ruby:
require 'mechanize'
require 'socket'
def do_mechanize_stuff(command, *args)
case command
when 'search_google'
# search google with args.join(' ')
when 'answer_questions_on_stackoverflow'
# answer questions on stackoverflow
# with mechanize
end
'the result to pass to PHP'
end
srv = TCPServer.new '::', 3000
loop do
Thread.new(srv.accept) do |sock|
sock.write(
do_mechanize_stuff *sock.gets.split(' ')
)
sock.close
end
end
Example Ruby client: (you will need to translate this to PHP)
require 'socket'
# This is a script that searches google
# and writes the results to stdout.
s = TCPSocket.new 'localhost', 3000
s.puts 'search_google how to use a keyboard'
until (r = s.gets).nil?
print r # a search result.
end
You could use process watching tools like http://god.rubyforge.org/ to keep the server running.
\2. Make the ruby script a command line utility, and use exec in PHP to call it.
An example command line script:
require 'mechanize'
def do_mechanize_stuff(command, *args)
# ... from previous example
end
do_mechanize_stuff ARGV.shift, ARGV
I would suggest following a Software as a Service Architectire (SOA) and running a Ruby/Rails application as a separate process. You'll have to develop an API between the two (a very simple one will work): using POST/GET as you first thought is a right way to go here.
i have two pages one in php(index.php) and another one in Perl(dbcon.pl).
basically i want my php file to show only the UI and all the data operations would be done in Perl file.
i have tried
in index.pl
<?php include("dbcon.pl");?>
<html>
<br/>PHP</br>
</html>
and dbcon.pl has
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use CGI::Simple;
my $cgi = CGI::Simple->new;
my $dsn = sprintf('DBI:mysql:database=%s;host=%s','dbname','localhost');
my $dbh = DBI->connect($dsn,root =>'',{AutoCommit => 0,RaisError=> 0});
my $sql= "SELECT * FROM products";
my $sth =$dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (my #row = $sth->fetchrow_array){
print $cgi->header, <<html;
<div> #row[0] #row[1] #row[2] #row[3] #row[4]</div>
html
}
but when i run index.php in browser it prints all the code in dbcon.pl file instead of executing it
how to overcome this problem?
note: i am running this in windows environment
is there any other way to do this?
May I ask what the problem really is? I don't see anything "special" in the Perl code, so you either:
a) Don't know how to access your DB from PHP (i.e. you don't know PHP) or
b) Don't know what Perl is doing (i.e. you don't know Perl) or
c) possibly your environment is set up so that you can use Perl DBI but you can't do the same from PHP.
This link should give you pointers to do what you are doing in Perl directly from PHP. You will easily find dozens of examples for various PHP/DB combinations.
The only other way would be to do what another poster suggests: invoke the Perl script and parse the result (printed to standard out).
This is rubygoldbergsque, brittle and unacceptable as a solution unless you are absolutely desperate to use something that is available only as a Perl module (which is not the case from the example you posted).
In general if you want to have something done in a language and use it from some other language the best way would be to make the (in your case) Perl run as a sort of "server", i.e. a seperate process - and make it expose services using XML-RPC or some other lightweight protocol.
INVOKING PROGRAMS WITH exec() OR SIMILAR CONSTRUCTS IS EXTREMELY BAD PRACTICE.
What you are trying is not possible that easy. You will have to execute the perl script with PHP, capture the output and print it like:
<?php echo exec('perl dbcon.pl'); ?>
As mentioned that is not a good thing to do. For a good separation between backend and user interface you should have a look at existing PHP frameworks.
There is Perl PECL package to integrate Perl into PHP.
P.S. IMHO it is better to use templating system like Template Toolkit in Perl. You can even use Perl inside templates.
If you're using Catalyst you could us Catalyst::View::PHP I suspect it will give you more clues on how to use php as your templating system. It also mentions PHP::Interpreter