How do I configure emacs for proper PHP development? - php

My current setup in emacs for PHP development has a variety of shortcomings. I often use a mixed mode of html and php. I want the mode to be able to recognize what context I'm in and format appropriately. I am especially interested in appropriate tabbing. This is the most important feature for me. Correct coloring would be nice, but if it messes up once in a while that's ok.
I am currently using multi-web-mode and the default php-mode in Emacs 24.3 on MacOS X.
One of the most frustrating problems is incorporating the heredoc syntax: echo <<< My current system doesn't recognize that this syntax needs to be NOT tabbed. I typically get warnings like this:
Indentation fails badly with mixed HTML/PHP in the HTML part in
plaín `php-mode'. To get indentation to work you must use an
Emacs library that supports 'multiple major modes' in a buffer.
Parts of the buffer will then be in `php-mode' and parts in for
example `html-mode'. Known such libraries are:
mumamo, mmm-mode, multi-mode
You have these available in your `load-path':
mumamo
I've already tried using mumao/nxhtml but that didn't give me the results I wanted. In some ways it was worse. I'd really appreciate any tips people have for getting a working php development environment setup for emacs.

I use web-mode (http://web-mode.org/) for mixed HTML/PHP files and php-mode for pure PHP files. The latest version of php-mode also recommended web-mode for mixed HTML/PHP files: https://github.com/ejmr/php-mode#avoid-html-template-compatibility.
Unlike other modes like mmm-mode, mumamo or multi-web-mode that try to apply different behaviors to different parts of a buffer, web-mode is aware of all the available syntax/template that can be mixed with HTML. You can also use web-mode for mixed HTML files/templates such as Twig, Django, ERB... In fact I use web-mode for anything involve HTML.
There is a catch for PHP template though: Other template systems has different file extension so it is easy to switch the mode automatically, but PHP templates usually use the same .php extension; so I have to make it switch by folders or sometimes manually invoke M-x web-mode. Here's my current configuration:
(defun add-auto-mode (mode &rest patterns)
(mapc (lambda (pattern)
(add-to-list 'auto-mode-alist (cons pattern mode)))
patterns))
(add-auto-mode 'web-mode
"*html*" "*twig*" "*tmpl*" "\\.erb" "\\.rhtml$" "\\.ejs$" "\\.hbs$"
"\\.ctp$" "\\.tpl$" "/\\(views\\|html\\|templates\\)/.*\\.php$")
BTW, try to separate your PHP files and templates and keep the mixed HTML/PHP file as simple as possible (refactor long PHP blocks into functions in a pure file). The code will be easier to read/follow.

Related

PSR-2, Line Wrapping for long argument listsl and Netbeans

According to the PSR-2 Standard on long argument lists:
Argument lists MAY be split across multiple lines, where each subsequent >line is indented once. When doing so, the first item in the list MUST be >on the next line, and there MUST be only one argument per line.
And that would look like this:
<?php
$foo->bar(
$longArgument,
$longerArgument,
$muchLongerArgument
);
However, in netbeans, while I have PSR-2 installed into the formatter, when I allow it to autoformat, I get:
$foo->bar($longArgument, $longerArgument, $muchLongerArgument);
I can change it to look like this:
$foo->bar(
$longArgument
, $longerArgument
, $muchLongerArgument
);
But this violates the standard. I can also set it to always line-break with a method call, but then I get:
$foo->bar($longArgument,
$longerArgument,
$muchLongerArgument);
Which also does not conform to the standard. It also automatically changes all method calls, while I want to only change method calls that I deem too long, and I want them to break as described above.
Is there a way to force netbeans to either break in the described way automatically when the line becomes too long ("Wrapping" set to "Too long" doesn't do it), and if not, is there a way I can prevent it from automatically putting my reformatted back onto one line without resorting to a different editor, or turning autoformat off?
Netbeans hasn't good code formatting tools for PHP PSR standards and it's difficult to force it to do. Much more better options is use external tool.
That's look fine:
NetBeans PHP CS Fixer Plugin
You should just configure you setting and done.

How to convert HTML into XHTML [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
PHP library for converting HTML4 to XHTML?
Is there any ready made function in PHP to achieve this? Basically I'm taking HTML data from Smarty template and want to convert it into XHTML through coding.
$filename = 'template.php'; // filepath to file
// All options : http://tidy.sourceforge.net/docs/quickref.html
$options = array('output-xhtml' => true, 'clean' => true, 'wrap-php' => true);
$tidy = new tidy(); // create new instance of Tidy
$tidy->parseFile($filename, $options); // open file
$tidy->cleanRepair(); // process with specified options
copy($filename, $filename . '.bak'); // backup current file
file_put_contents($filename, $tidy); // overwrite current file with XHTML version
I don't have a Smarty template file to test this on, but give it a try and see if it works correctly in converting one. Backup your files as always when running something of this nature. Test out on sample files first.
The problem is that you do not have an html file to work with. You have a php template written in the programming language "smarty" that is not markup, even though it contains blocks of markup. You're looking for a magic wand and no such wand exists.
If it was purely html, then you could probably use Domdocument to read the files into a Dom structure and generate xhtml, but that is simply not going to work with the pure source files, although you could potentially write a parser to read the smarty tpl files, look for the html snippets and try and load them into Domdocument objects.
With that said, I have to ask first -- why you really want to convert to xhtml when xhtml is basically a failed standard that is obsolete at this point in time, and secondarily, if you have some legitimate reason for wanting to forge ahead, why you can't use some regex search and replace snippets that change the doctypes and some regex based searches to look for tags that lack the end tags, and the other relatively minor tweaks needed. The differences between html and xhtml can be boiled down to a handful of rules that are pretty easy to understand.
In answer to your original question: sort of. Core PHP -> DOM, SimpleXML, SPL = templating engine. That's why (and how) templating engines such as Smarty exist.
Re: installing Tidy as suggested in comments,
Tidy has a prerequisite lib. If you don't already have it:
http://php.net/manual/en/tidy.installation.php
To use Tidy, you will need libtidy installed, available on the tidy homepage »
http://tidy.sourceforge.net/.
To enable, you will need to recompile PHP and include it in your config flags:
"This extension is bundled with PHP 5 and greater, and is installed
using the --with-tidy configure option."
So, get your existing config flags:
php -i | grep config
and add --with-tidy.
However, this is probably the wrong approach. It does not solve your actual problem (outputting XHTML instead of HTML) - it fixes Smarty's problem. Recompiling PHP to add an extension so you can use it to fix a templating engine's doctype shortcomings probably means you should consider using a different templating engine, if possible. That's sort of drastic (and adds a lot of overhead for what you get, which amounts to for a hacky non-solution bandaid workaround retroactively repairing broken output.)
PEAR's HTML_Template_PHPTAL is probably the best solution to your problem, and the closest answer to your original question.
And if PHPTAL doesn't quite cut it, there are at least 5 others available as PEAR libs to choose from.
pear install http://phptal.org/latest.tar.gz
Or it's been ported to Git:
git clone git://github.com/pornel/PHPTAL
A cursory google search: http://webification.com/best-php-template-engines
HTH

What is the difference between the PHP open tags “<?=” and “<?php”/“<?”?

Sorry for the silly question, but I ran across code that used:
<?=$MAP_OBJECT->printOnLoad();?>
<?=$MAP_OBJECT->printMap();?>
<?=$MAP_OBJECT->printSidebar();?>
Is there anything special about <?= over <?php or just plain <??
They are shorthand of <?php echo .... ?> known as short tags. You should avoid using them because:
They seem to be turned off on some servers
They can get you in trouble in terms of security
They can create conflict with processing instructions like <?xml ... ?>
Therefore you should never use them again, also have a look at:
PHP Short Open Tag: Convenient Shortcut or Short Changing Security?
Rather than talking about whether short_open_tags is deprecated or not we should talk about the advantages and disadvantages when using short open tags:
Advantages
Using the short open tags <? along with <?= is shorter and probably easier to write than the standard opening tags <?php and <?php echo respectively. That’s quite handy when using PHP directly in a template. (That’s probably also the reason why PHP has an alternative syntax for control structures.)
Disadvantages
Requires a specific configuration
When using short open tags you are required to have short_open_tags enabled. If you or your web hosting provider decides to disable short_open_tags, your application probably won’t work any more and you can have some serious security issues. Because if short_open_tags is disabled, only the standard opening tags <?php are recognized and everything inside short opening tags is treated as plain text. (See also the blog post referenced in Sarfraz Ahmed’s answer.)
This requirement makes your PHP application less portable if you aim to write applications that are not just for you. That’a also why many recommend not to use short open tags (including the PHP manual):
Note: Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.
As of PHP 5.4 <?= is always available, regardless of the short_open_tags option. <? on the other hand requires the option to be enabled.
Conflicts with XML processing instructions
Another issue is when using XML processing instructions like <?xml … ?>. When short_open_tags is enabled you cannot use them directly in your code but need to use PHP to output it:
If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>.
Otherwise PHP will choke on the xml in <?xml.
Now some last words about the deprecation: Currently short_open_tags is not deprecated. Otherwise the manual would state that explicitly. Additionally, Rasmus Lerdorf, inventor of PHP, wrote in a reply on the question “Is it true that short_open_tag is deprecated in PHP 6?” on the internals mailing list that there were several reasons not to remove short_open_tags in PHP 6:
Which is one of the reasons we decided not to remove them in PHP 6.
<?= is a short tag that is pretty much equivalent to:
<?php echo
As of PHP 5.4, this syntax is always available, but in earlier versions of PHP, it needs short_open_tag enabled. As for how to search for it on Stack Overflow, try code:"<?=".
It's a shorthand for <?php echo $MAP_OBJECT->printOnLoad(); ?>. Simpler way to write it when you're making PHP-based templates and things.
Be careful, though. My understanding (though I've never run into it myself) is that the shorthand version can be disabled on some servers.
<?= is not one thing. It's actually <? and then = . As #derekerdmann has mentioned, this is an unrecommended configuration.
Give the following a look:
Are PHP short tags acceptable to use?
PHP echo vs PHP short tags
Just to correct all these misguiding answers:
short open tags are not going to be removed or deprecated.
Inside short tag you cannot write like this .
<?=
$number = "5";
$sum = 15 + "5";
?>
because it will print only the first output as 5.
Inside open tag you can write like this .
<?php
echo $number ="5";
echo $sum = 15+"5";
?>
It will print both 5 and 20
its all about syntax.
adding this due to duplicate questions
aka shortags is an alternative tag for php but works only on servers that have it enabled.
It allows you to write echo like this
However it is not recommended to use them and have been suggested to be removed or deprecated in php5.4+ along with register globals, safe mode and magic quotes etc.
So though you might use them, they are not recommended.
1. They are not portable since servers must have them enabled.
2. They can lead to spaghetti code easily since you can easily integrate html in your file.
3. Special methods have to be used when mixing them with xml declaration
They are however great for making templates along with other shorthand notations for loops and conditional checks.

"Safe" markdown processor for PHP?

Is there a PHP implementation of markdown suitable for using in public comments?
Basically it should only allow a subset of the markdown syntax (bold, italic, links, block-quotes, code-blocks and lists), and strip out all inline HTML (or possibly escape it?)
I guess one option is to use the normal markdown parser, and run the output through an HTML sanitiser, but is there a better way of doing this..?
We're using PHP markdown Extra for the rest of the site, so we'd already have to use a secondary parser (the non-"Extra" version, since things like footnote support is unnecessary).. It also seems nicer parsing only the *bold* text and having everything escaped to <a href="etc">, than generating <b>bold</b> text and trying to strip the bits we don't want..
Also, on a related note, we're using the WMD control for the "main" site, but for comments, what other options are there? WMD's javascript preview is nice, but it would need the same "neutering" as the PHP markdown processor (it can't display images and so on, otherwise someone will submit and their working markdown will "break")
Currently my plan is to use the PHP-markdown -> HTML santiser method, and edit WMD to remove the image/heading syntax from showdown.js - but it seems like this has been done countless times before..
Basically:
Is there a "safe" markdown implementation in PHP?
Is there a HTML/javascript markdown editor which could have the same options easily disabled?
Update: I ended up simply running the markdown() output through HTML Purifier.
This way the Markdown rendering was separate from output sanitisation, which is much simpler (two mostly-unmodified code bases) more secure (you're not trying to do both rendering and sanitisation at once), and more flexible (you can have multiple sanitisation levels, say a more lax configuration for trusted content, and a much more stringent version for public comments)
PHP Markdown has a sanitizer option, but it doesn't appear to be advertised anywhere. Take a look at the top of the Markdown_Parser class in markdown.php (starts on line 191 in version 1.0.1m). We're interested in lines 209-211:
# Change to `true` to disallow markup or entities.
var $no_markup = false;
var $no_entities = false;
If you change those to true, markup and entities, respectively, should be escaped rather than inserted verbatim. There doesn't appear to be any built-in way to change those (e.g., via the constructor), but you can always add one:
function do_markdown($text, $safe=false) {
$parser = new Markdown_Parser;
if ($safe) {
$parser->no_markup = true;
$parser->no_entities = true;
}
return $parser->transform($text);
}
Note that the above function creates a new parser on every run rather than caching it like the provided Markdown function (lines 43-56) does, so it might be a bit on the slow side.
JavaScript Markdown Editor Hypothesis:
Use a JavaScript-driven Markdown Editor, e.g., based on showdown
Remove all icons and visual clues from the Toolbar for unwanted items
Set up a JavaScript filter to clean-up unwanted markup on submission
Test and harden all JavaScript changes and filters locally on your computer
Mirror those filters in the PHP submission script, to catch same on the server-side.
Remove all references to unwanted items from Help/Tutorials
I've created a Markdown editor in JavaScript, but it has enhanced features. That took a big chunk of time and SVN revisions. But I don't think it would be that tough to alter a Markdown editor to limit the HTML allowed.
How about running htmlspecialchars on the user entered input, before processing it through markdown? It should escape anything dangerous, but leave everything that markdown understands.
I'm trying to think of a case where this wouldn't work but can't think of anything off hand.

What is the shortest way of inserting a variable into text with PHP?

I'm wondering if there is a shorter way of inserting text in PHP than
<?php
$city = "London";
?>
This website is a funky guide to <?php print $city; ?>!!!
For example, using ruby on rails, I could set
city = 'London'
somewhere in the code, and in my .erb file I could do
This website is a funky guide to <%= city %>!!!
I did read somewhere that {$city} could be used, but I tried it and it didn't. So is there a shorter form than <?php print $var; ?> ?
You could use short_open_tag, which have to be enabled in your configuration, but that's not considered as a good practice, as it only works if those are enabled -- and they are not always (maybe not even by default)
Using long tags and echo/print might be longer, yes... But I would recommend using those, and not short tags.
Also note that you might need to escape your data, when it comes from an un-trusted source and/or might contain HTML you don't want to get injected in the page, to avoid injections of HTML/JS (see htmlspecialchars) :
EDIT after the comments, to add couple of things about short_open_tag :
Why are short open tags considered (at least by me ^^ ) bad practice ?
First of all, after some checking, they are not enabled by default :
For PHP 5.3 :
squale#shark:~/temp/php/php-5.3.0
$ grep 'short_open_tag' php.ini-development
; short_open_tag
short_open_tag = Off
squale#shark:~/temp/php/php-5.3.0
$ grep 'short_open_tag' php.ini-production
; short_open_tag
short_open_tag = Off
Disabled by default in either "development" or "production" settings.
For PHP 5.2.10 (most recent version of PHP 5.2) :
squale#shark:~/temp/php/php-5.2.10
$ grep 'short_open_tag' php.ini-dist
short_open_tag = On
squale#shark:~/temp/php/php-5.2.10
$ grep 'short_open_tag' php.ini-recommended
; - short_open_tag = Off [Portability]
short_open_tag = Off
Disabled by default in the "recommended" settings
Considering these default settings are sometimes (often ?) kept by hosting services, it is dangerous to rely on short_open_tag being activated.
(I have myself run into problem with those being disabled... And when you are not admin of the server and don't have required privilegies to modify that, it's not fun ^^ )
If you want some numbers, you can take a look at Quick survery: short_open_tag support on or off by default?
(Not a scientific proof -- but show it could be dangerous to use those for an application you'd release to the public)
Like you said, those, when activated, conflict with XML declaration -- means you have to use something like this :
<?php echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?>
Considering short open tags exists, and might be activated on the server you'll use, you should probable not use <?xml ever, though ; too bad :-(
Actually, reading through the php.ini-recommended of PHP 5.2.10 :
; Allow the <? tag. Otherwise, only <?php and <script> tags are recognized.
; NOTE: Using short tags should be avoided when developing applications or
; libraries that are meant for redistribution, or deployment on PHP
; servers which are not under your control, because short tags may not
; be supported on the target server. For portable, redistributable code,
; be sure not to use short tags.
The one from PHP 6 is even more interesting :
; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It's been
; recommended for several years that you not use the short tag "short cut" and
; instead to use the full <?php and ?> tag combination. With the wide spread use
; of XML and use of these tags by other languages, the server can become easily
; confused and end up parsing the wrong code in the wrong context. But because
; this short cut has been a feature for such a long time, it's currently still
; supported for backwards compatibility, but we recommend you don't use them.
(Might be the same in PHP 5.3 ; didn't check)
There have been rumors short open tags could be removed from PHP 6 ; considering the portion of php.ini I just posted, it probably won't... but, still...
To give an argument pointing to the other direction (I've gotta be honest, after all) : using short open tags for template files (only) is something that is often done in Zend Framework's examples that use template files :
In our examples and documentation, we
make use of PHP short tags:
That said, many developers prefer to
use full tags for purposes of
validation or portability. For
instance, short_open_tag is disabled
in the php.ini.recommended file, and
if you template XML in view scripts,
short open tags will cause the
templates to fail validation.
(source)
On the contrary, for .php files :
Short tags are never allowed. For
files containing only PHP code, the
closing tag must always be omitted
(source)
I hope those informations are useful, and bring some kind of answer to your comment :-)
If you switch out of PHP mode, then the only way to print the variable is to switch back into it and print it like you have above. You could stay in PHP mode and use the {} construction you tried:
<?php
$city = "London";
echo "This website is a funky guide to {$city}!!!";
?>
I did read somewhere that {$city} could be used
If you go for a templating engine such as Smarty you can do this. That might be useful if you're developing in a team and some of them don't know PHP.
Otherwise, the shortest you will get is the following, assuming you have short tags enabled:
<?=$city?>
If you don't, or you're creating an app to redistribute to others, then use this:
<?php echo $city ?>
Just extend your PHP block and do this:
<?php
$city = 'London';
echo 'This website is a funky guide to ',$city,' !!!';
?>
Alternatively, you can use " " instead of ' ' and replace ',$city,' with $city, but it takes more CPU time to parse for variables.

Categories