PHP equivalent to Perl format function - php

Is there an equivalent to Perl's format function in PHP? I have a client that has an old-ass okidata dotmatrix printer, and need a good way to format receipts and bills with this arcane beast.
I remember easily doing this in perl with something like:
format BILLFORMAT =
Name: #>>>>>>>>>>>>>>>>>>>>>> Age: ####
$name, $age
.
write;
Any ideas would be much appreciated, banging my head on the wall with this one. O.o
UPDATE: I cannot install Perl in this environment, otherwise I would simply use Perl's format function directly.

You could use printf to do something similar.
http://www.php.net/manual/en/function.printf.php
printf("Name: %21s Age: %3i\n",$name,$age);
If you wanted the name left aligned, you would just add a -
printf("Name: %-21s Age: %3i\n",$name,$age);
It defaults to right aligned.

If you don't mind using a Perl process to control the printer, you could serialize the data in PHP and pass it to a Perl script.
I've had great luck using PHP::Serialization to handle data serialization and sharing between Perl and PHP. You could also use YAML or JSON for this task.

Sounds like a perfect situation to use heredoc.

Related

how to get html text differences like svn?

I am using PEAR text_diff class to get comparison of text. It works correct for plain text, but when I try to compare text with HTML tags, It gives wrong result
is there any way to compare two HTML blocks and in result display text that pre-serv its HTML and show differences like svn
In my experience, these two are fantastic:
https://github.com/cygri/htmldiff (Python)
http://www.w3.org/People/Bos/#jpegxmp (C, must be compiled)
Yes, none of the programs are written in plain PHP. You just run them via PHP:
// Python script:
$html_diff = shell_exec ('python /path/to/htmldiff version1.html version2.html');
// C program:
$html_diff = shell_exec ('/path/to/htmldiff --start-delete="<span class=\'delete\'>" --end-delete="</span>" --start-insert="<span class=\'insert\'>" --end-insert="</span>" version1.html version2.html');
Since they aren't written in PHP, you can enjoy the incredible high speed :)
I'm not sure which OS you're on, but I always use Meld on Ubuntu for diff:ing non-versioned files. It doesn't have any problems diffing HTML code (or anything else afaik):
http://meldmerge.org/
You can do this right in javascript itself. Check out google-diff-match-patch.
Diff demo here.

Inline PHP (command line)

I would like to make something like tryruby.org. I take a line from the user (e.g., echo __FILE__) and I want to execute it in PHP and return the output back to the client.
I tried to do exec('php -r ' . $command, $output), but $output always contains the PHP help section.
How can I implement this feature?
To make php -r you have to have to put the code you want to execute between ' .. your code .. '
Example:
php -r ' $var = 34; print_r($var); '
It looks like your problem is that you aren't wrapping your code to be executed with ' '. You also need to be wary of ' in the code, special characters, escape sequences, etc.
In fact, if you insist on using exec(), it might be better to do this (to completely avoid having to worry about escaping and the such):
$command = base64_encode($command);
exec("php -r 'eval(base64_decode(\"$command\"));'", $output);
You could use eval() instead of what you're posting above.
The main issue here (both with eval() and your exec() code) is that taking PHP code from user input simply isn't safe:
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
Suggestion
Since you want to return the result of the PHP code, you could potentially do something cool with Ajax, where you pass the PHP code to a script (Base64 encoded, perhaps) as a parameter:
$code = base64_decode($_GET['code']);
// Clean the user input here
eval($code);
Ajax example using jQuery:
// assuming `code` contains the PHP code
var encoded = base64_enc(code);
$.get('execute.php?code=' + encoded, function(data) {
var result = new String(data);
// do something with the result here, such as displaying it
}, dataType='text');
For Base64 encoding in JavaScript, see this.
http://tryruby.org seems have an interactive Ruby shell. That seems to be a good starting point.
Here are two projects that provide such a shell for PHP: php_repl and phpsh.
The other part is the web interface for the interactive shell. For that part, I suggest you have a look at repl.it, which provides this service for many languages (but sadly not PHP). Here's a link to it's source code.
With this combination, you should be able to complete cour project.
Look up 'eval()' and more importantly, why eval() and what you're trying to do is very difficult to achieve in a secure manner. Imaging for example the user who inputs:
echo file_get_contents('/etc/passwd');
You'll need quite a bit of work to make this secure, including watching and filtering all system calls being made from the eval'd process.
Cheers

Extract data from HTML in PHP or Python

I need to extract this data and display a simple graph out of it.
Something like Equity Share Capital -> array (30.36, 17, 17 .... etc) would help.
<html:tr>
<html:td>Equity Share Capital</html:td>
<html:td class="numericalColumn">30.36</html:td>
<html:td class="numericalColumn">17.17</html:td>
<html:td class="numericalColumn">15.22</html:td>
<html:td class="numericalColumn">9.82</html:td>
<html:td class="numericalColumn">9.82</html:td>
</html:tr>
How do I go about this task in PHP or Python?
A good place to start looking would be the python module BeautifulSoup which extracts the text and places it into a table.
Assuming you've loaded the data into a variable called raw:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(raw)
for x in soup.findAll("html:td"):
if x.string == "Equity share capital":
VALS = [y.string for y in x.parent.findAll() if y.has_key("class")]
print VALS
This gives:
[u'30.36', u'17.17', u'15.22', u'9.82', u'9.82']
Which you'll note is a list of unicode strings, make sure to convert them to whatever type you desire before processing.
There are many ways to do this via BeautifulSoup. The nice thing I've found however is the quick hack is often good enough (TM) to get the job done!
BeautifulSoup
Don't forget lxml in Python. It also works well to extract data. It's harder to install but faster. http://pypi.python.org/pypi/lxml/2.2.8

Am I breaking any "php good practice" in the following php array which deals with 3 (human) languages?

This is the most optimal way of dealing with a multilingual website I can think of, right now (not sure) which doesn't involve gettext, zend_translate or any php plugin or framework.
I think its pretty straight forward: I have 3 languages and I write their "content" in different files (in form of arrays), and later, I call that content to my index.php like you can appreciate in the following picture:
alt text http://img31.imageshack.us/img31/1471/codew.png
I just started with php and I would like to know if I'm breaking php good practices, if the code is vulnerable to XSS attack or if I'm writing more code than necessary.
EDIT: I posted a picture so that you can see the files tree (I'm not being lazy)
EDIT2: I'm using Vim with the theme ir_black and NERDTree.
Looks all right to me, although I personally prefer creating and using a dictionary helper function:
<?php echo dictionary("showcase_li2"); ?>
that would enable you to easily switch methods later, and gives you generally more control over your dictionary. Also with an array, you will have the problem of scope - you will have to import it into every function using global $language; very annoying.
You will probably also reach the point when you have to insert values into an internationalized string:
You have %1 votes left in the next %2 hours.
Sie haben %1 stimmen übrig für die nächsten %2 stunden.
Sinulla on %1 ääntä jäljellä seuraavan %2 tunnin ajassa.
that is something a helper function can be very useful for:
<?php echo dictionary("xyz", $value1, $value2 ); ?>
$value1 and $value2 would be inserted into %1 and %2 in the dictionary string.
Such a helper function can easily be built with an unlimited number of parameters using func_get_args().
It's OK generally. For instance, punBB's localization works this way. It is very fast. Faster than calling a function or an object's method or property. But I see a problem with this approach, since it doesn't support language fallbacks easily. I mean, if you don't have a string for Chinese, let it be displayed in English.
This problem is topical when you upgrade your system and you don't have time to translate everything in every language.
I'd better use something like
lang.en.php
$langs['en'] = array(
...
);
lang.cn.php
$langs['cn'] = array(
...
);
[prepend].php (some common lib)
define('DEFAULT_LANG', 'en');
include_once('lang.' . DEFAULT_LANG '.php');
include_once('lang.' . $user->lang . '.php');
$lang = array_merge($langs[DEFAULT_LANG], $langs[$user->lang]);
Looks all right to me also, but:
Seems that you have localization for multiple modules/sites, so why not break it down to multidimensional array?
$localization = array(
'module' => (object)array(
'heading' => 'oh, no!',
'perex' => 'oh, yes!'
)
);
I personally like to creat stdClass out of arrays with
$localization = (object)$localization;
so you can use
$localization->module->heading;
:) my 2 cents
The only way that this could be xss is if you have register_globals=On and you don't set $lang['showcase_lil'] or other $lang's. But I don't think you have to worry about this. So I think your in the clear.
as an xss test:
http://127.0.0.1/whatever.php?lang[showcase_lil]=alert(/xss/)
Wouldn't it have been better to post code and briefly explain this issue to us?
Anyway, putting each language in its own file and loading it through some sort of language component seems okay. I'd prefer using some sort of gettext, but this is okay too, I guess.
You should make a function for calling the language keys rather than relying on an array, something like
<?php echo lang('yourKey'); ?>
One thing to watch for is interpolation; that's really the only place XSS could sneak in if your server settings are sensible. If you at any point need to do something along the lines of translating "$project->name has $project->member_count members", you'll have to make sure you escape all HTML that goes in there.
But other than that, you should be fine.

Can a PHP script unserialize a Storable file created with Perl?

Can a PHP script unserialize a Storable file created with Perl?
No, but you can dump PHP-readable data from Perl with PHP::Serialization. You also might want to pick something more standard, like YAML or JSON. Pretty much any language can understand those.
You could use JSON as a lingua-franca between the two languages, I suggest JSON::XS on the Perl side (with subroutines implemented in C/C++) for performances, then you can read back (in PHP) the JSON with this extension.
PHP being Turing-complete and all, the answer isn't really "no" so much as "not natively or with any well-known public module".
As chaos points out, you asked for Storable specifically, and so switching to YAML (or JSON) may be possible, but it may not. This might work to get it into YAML (or even JSON):
$output_format = 'YAML';
popen( "perl -MStorable -M${output_format}::Syck=Dump -e 'print Dump( retrieve( q{$storable_file_path} ))'", "r" );

Categories