Keyboard input in PHP - php

I am trying to control stuff with PHP from keyboard input. The way I am currently detecting keystrokes is with:
function read() {
$fp1=fopen("/dev/stdin", "r");
$input=fgets($fp1, 255);
fclose($fp1);
return $input;
}
print("What is your first name? ");
$first_name = read();
The problem is that it is not reading the keystrokes 'live'. I don't know if this is possible using this method, and I would imagine that this isn't the most effective way to do it either. My question is 1) if this is a good way to do it, then how can I get it to work so that as you type on the page, it will capture the keystrokes, and 2) if this is a bad way of doing it, how can I implement it better (maybe using ajax or something)?
edit: I am using PHP as a webpage, not command line.

I'm assuming that you're using PHP as a web-scripting language (not from the command line)...
From what I've seen, you'll want to use Javascript on the client side to read key inputs. Once the server delivers the page to the client, there's no PHP interaction. So using AJAX to read client key inputs and make calls back to the server is the way to go.
There's some more info on Javascript and detecting key presses here and some info on how to use AJAX here.
A neat option for jQuery is to use something like delayedObserver

If you are writing a CLI application (as opposed to a web application), you can use ncurses' getch() function to get a single key stroke. Good luck!
If you're not writing a CLI application, I would suggest following Andrew's answer.

Try readline:
http://us3.php.net/manual/en/function.readline.php

Related

Need to run a php program inside a rails produced page

I plan to use Spree for a shopping site but at some point need to sign some data with a PHP program provided by a bank. The only alternative I can think of is to link to somePage.php that runs PHP program and come back to Spree. Is there any easier way like a sending to some PHP shell inside Ruby? or changing for the view to have php extension?
Any help would be appreciated.
Well, first I would check for a native Ruby way of signing your data in Ruby. Have a look at Spree documentation first, or at your bank specs (they usually are very bad, take how bankers write contracts, they can't be any good at writing software specs).
As a second alternative, if you have the PHP program you should try and translate it in Ruby.
If that is not an option for you then you can play with open4 like this:
status = Open4::popen4("/path/to/php bank_code.php #{data_to_sign}") do |pid, stdin, stdout, stderr|
out_msg = stdout.read
err_msg = stderr.read
logger.error "out_msg #{out_msg}"
logger.error "err_msg #{err_msg}"
end
handle_error_case if status.existatus != 0
Cheers,

Sharing access restrictions between php and javascript

The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>

Post into a textarea and then get the result from another textarea

Let say I have this JS code:
function plus2(){
print (2+2);
};
So I want to post this code into textarea#input at http://dean.edwards.name/packer/ and then get the result back from textarea#output.
Can use PHP Curl, Shell Curl or JQuery to do the job?
P.S.: By the way, there is bug in PHP Packer port and that's whay I am not using it.
PHP implementation of JSMin works well for me. Also, if you have server-side JS interpreter you can use UglifyJS, it's fast and provides a good compression.
Not really, no. It would need to be passed to a JavaScript engine at some point, so PHP/cURL is not going to be enough.
I recommend using an alternative server-side implementation of packer, or perhaps even YUI Compressor.

Scraping Library for PHP - phpQuery?

I'm looking for a PHP library that allows me to scrap webpages and takes care about all the cookies and prefilling the forms with the default values, that's what annoys me the most.
I'm tired of having to match every single input element with xpath and I would love if something better existed. I've come across phpQuery but the manual isn't much clear and I can't find out how to make POST requests.
Can someone help me? Thanks.
#Jonathan Fingland:
In the example provided by the manual for browserGet() we have:
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://google.com/', 'success1');
function success1($browser)
{
$browser->WebBrowser('success2')
->find('input[name=q]')->val('search phrase')
->parents('form')
->submit();
}
function success2($browser)
{
echo $browser;
}
I suppose all the other fields are scrapped and send back in the GET request, I want to do the same with the phpQuery::browserPost() method but I don't know how to do it. The form I'm trying to scrape has a input token and I would love if phpQuery could be smart enough to scrape the token and just let me change the other fields (in this case username and password), submiting via POST everything.
PS: Rest assured, this is not going to be used for spamming.
See http://code.google.com/p/phpquery/wiki/Ajax and in particular:
phpQuery::post($url, $data, $callback, $type)
and
# data Object, String which defines the data parameter as being either an Object or a String. POST requests should be possible using query string format, e.g.:
$data = "username=Jon&password=123456";
$url = "http://www.mysite.com/login.php";
phpQuery::post($url, $data, $callback, $type)
as phpQuery is a jQuery port the method signature is the same (the docs link directly to the jquery site -- http://docs.jquery.com/Ajax/jQuery.post)
Edit
Two things:
There is also a phpQuery::browserPost function which might meet your needs better.
However, also note that the success2 callback is only called on the submit() or click() methods so you can fill in all of the form fields prior to that.
e.g.
require_once('phpQuery/phpQuery.php');
phpQuery::browserGet('http://www.mysite.com/login.php', 'success1');
function success1($browser) {
$handle = $browser
->WebBrowser('success2');
$handle
->find('input[name=username]')
->val('Jon');
$handle
->find('input[name=password]')
->val('123456');
->parents('form')
->submit();
}
function success2($browser) {
print $browser;
}
(Note that this has not been tested, but should work)
I've used SimpleTest's ScriptableBrowser for such stuff in the past. It's part of the SimpleTest testing framework, but you can use it stand-alone.
I would use a dedicated library for parsing HTML files and a dedicated library for processing HTTP requests. Using the same library for both seems like a bad idea, IMO.
For processing HTTP requests, check out eg. Httpful, Unirest, Requests or Guzzle. Guzzle is especially popular these days, but in the end, whichever library works best for you is still a matter of personal taste.
For parsing HTML files I would recommend a library that I wrote myself : DOM-Query. It allows you to (1) load an HTML file and then (2) select or change parts of your HTML pretty much the same way you'd do it if you'd be using jQuery in a frontend app.

Run PHP class from JavaScript

I need to fire a php class from a javascript function.
code:
<input type="button" name="Submit" value="Submit" class="opinionbox"
onclick="verifyControl('<?=$control_no?>')"/>
function verifyControl(rNo) {
Cont_no=document.getElementById("ContNo").value;
if(rNo==Cont_no) {
frames['frame1'].print();
showPage('payment');
}
else if(rNo!=Cont_no) {
alert("invalid control no");
}
}
i need to run the code
$data = $obj_com -> getSelectedData('tbl',
'control_no', $contno);
$control_no = $contno;
$obj_com -> recordPay('tbl',$contno);
inside the verifyControl() how can I do this?
You cannot "call" a PHP class from Javascript because Javascript is run on the client side (ie, the browser) while PHP is run on the server. What you can do, however, is call a PHP script asynchronously, get its output, and do fun stuff with javascript. This is known as AJAX. If you're going to go down this road, you are highly advised to use a library like jQuery and learn from there. Here are a few questions to get you started (check out the answers):
How to dynamically call a php function in javascript
Javascript and PHP functions
To call PHP code from Javascript, given that PHP is executing on the server and Javascript is executing on the client, you will need to set up some sort of interface at the server that can be accessed remotely.
You may also want to be aware of the security implications of doing so. In particular, if you want to ensure that only your users will be calling your server in this way - that is, if a malicious user calling this code could do damage, you will need some sort of authentication.
You will also need to decide on a protocol for communicating between the client and server.
Protocols such as SOAP and XML-RPC define everything you need to remotely call procedures on the server. Or you can roll your own, just by calling a certain URL and receiving a certain result, in a certain format (JSON can help) from the server.
you can use Brent Ashley jsrsClient.js or $.ajax of jQuery Javascript lib.

Categories