I'm going to be doing some PHP editing for my job this summer, and am looking for an effective Emacs setup for editing it. I'm already heavily invested in Emacs, so switching to another editor is not worthwhile.
Right now, I have nXhtml-mode, which provides a PHP mode with syntax highlighting (there are at least three different ones in the wild) as well as MuMaMo for editing PHP embedded in HTML. I just started using Auto-Complete and Anything for programming and general Emacs stuff, respectively.
What I'm really looking for is an effective way to get Emacs to really understand the project, beyond just highlighting. Etags looks like a good option, but it looks like the process for generating new tags is kind of arduous and manual (or at least not invisible). The nice thing about Etags is that they integrate well with Anything and Auto-Complete. Other potential options are gtags (though I'm hesitant to install non-elisp files, just for the complexity), vtags, or Semantic, which I've messed with before and seems complicated to set up, plus it doesn't look like it has support for PHP.
Another option is Imenu, but it only works for the current buffer, and I would like to be able to jump to function definitions in other files (preferably using Anything for completion of the name).
The projects I will be working on are not that big (about 30,000 lines total), so the overhead of Etags probably won't be that big of an issue, but I'd rather not use it if there is a better solution.
So what is your preferred PHP editing system?
In addition to features you are already familiar with, I suggest you the followings.
ETags
I do not use ETags, but there is a question already on SO How to programmatically create/update a TAGS file with emacs. No good answer was posted, though, but it may be a good entry point to get an idea.
Debugging
Flymake is a mode to get on the fly syntax checking. It has support for PHP as well. It hints at syntax errors immediately as you type. The Flymake version shipped with Emacs 23 contains PHP support. If you have previous version, check Sacha Chua's post on Emacs and PHP: On-the-fly syntax checking with Flymake.
Another useful package is Geben that allows you to debug your scripts interactively. For PHP, you can use XDebug. There is a detailed tutorial on how to do that, see Debug php in emacs with geben.
Documentation lookup
PHP Mode has a nice feature to lookup the function's definition in PHP's manual in your web browser (M-x php-search-documentation or C-c C-f). You can combine it with Emacs-W3M to get the relevant manual page without leaving Emacs.
web-model.el (available on web-mode.org) handles pretty well php blocks embedded in an html document. This major mode will also highlight js and css parts.
As an alternative to ETags, consider GNU Global, aka "GTags". Global is a lot smarter about finding tags tables, and is fairly fast to update. Emacs-fu has a nice post about doing this on-the-fly.
BTW, if you're using the Windows port of GNU Global with a Windows Emacs build, use the DJGPP ("DOS") version. The MinGW ("Win32") build seems to have a problem with path names.
In addition to the answer given on May 28 '09, I think I can add some packages to it which enhanced my PHP experience on Emacs.
Auto-completion
ac-php is in my opinion a good additions to Etags. All references to a tag will be found with etags, but the definition with ac-php. ac-php is also configurable to which directories should be included. For example, while developing a wordpress plugin, you can add a reference to the directory containing the wordpress files in .ac-php-conf.json (which resides in the project root) and it will auto-complete, jump to reference, etc. This package supports company-mode and auto-complete.
Here's an example configuration of ac-php:
(use-package ac-php
:ensure t
:bind (:map
php-mode-map
("M-+" . ac-php-find-symbol-at-point)
("M-]" . ac-php-location-stack-back)
("<menu> r" . ac-php-remake-tags)
("<menu> R" . ac-php-remake-tags-all)))
Another option would be to use phpactor, but the Emacs interface is at the time of writing still in alpha stage, with which I also hardly have any experience - except for the constructor completion, which works pretty well.
Error checking
In addition to syntax errors, Flycheck supports phpMessDetector and phpCodeSniffer out of the box. This enables you to have more enhanced notice/warning/error reporting based on supported coding standard and best practices.
Another package I like for static analysis is PHPStan Emacs interface, which reports potential errors in your code (including incorrect type hints).
Additional formatting
I also use phpcbf (which apparantly is archived). This package formats the buffer into the wanted coding standard.
Semantic
For anyone in the dark, Semantic is a built-in Emacs package and provides IDE like features. Here's an example how to include semantic for php-mode:
(add-hook 'php-mode-hook (lambda ()
(require 'semantic/symref/grep)
(add-to-list 'semantic-symref-filepattern-alist '(php-mode "*.php" "*.inc"))
(semantic-mode)))
Imenu
For including imenu jumping to definitions, another example configuration:
This is the sidebar for jumping to in-file methods and functions.
(use-package imenu-list
:ensure t
:config
(setq imenu-list-focus-after-activation t)
:bind (:map php-map
("<menu> \\" . imenu-list-smart-toggle)))
Example config for helm support in jumping to definitions in all project files:
(use-package imenu-anywhere
:ensure t
:after helm
:bind (:map php-map
("<menu> |" . helm-imenu-anywhere)))
Additional debugging
Besides geben, I like to use psysh, which by dropping in eval(\Psy\sh()); gives a repl on that line of code and gives access to all definitions and whatever else one would have access to (ofcourse, after requiring it in composer).
More generally handy packages
Snippets
Maybe a bit obvious for everyone already experienced with Emacs, but yasnippet is also very handy for writing your own templates. There are also packages that include a lot of predefined templates for all sorts of languages, but I write my own to keep Emacs a little less bloated than my set-up already is, it also helps me remember them more easily.
Project management
Excuse the obviousness again, but Projectile is also a very good package which by default includes git support for scoping the project.
Offline documentation
If you use Zeal for offline documentation browsing, there's also zeal-at-point. Example configuration, if you use, lets say: PHP, CodeIgniter and WordPress:
(use-package zeal-at-point
:ensure t
:bind (("<menu> z" . zeal-at-point))
:config
(add-to-list 'zeal-at-point-mode-alist '(php-mode . ("codeigniter" "wordpress" "php"))))
Related
If I would like to distribute PHP application with installer(package system of OS) how should I proceed? I don't want PHP files to be there, just working application, so when I type 'app' into console, it ends up being launching application, without need to install PHP on system(no php installation on host required). I would also like the application to have patch-able byte-code, so it's in parts, loaded when needed and only part needs to be replaced on update.
What I would do now is following:
->Compile PHP with extensions for specific platform.
->Make binary application which launches '/full/php app' when app is launched.
->Pack it in installer in a way, that there would be binary added to path when added, launching specific installation of PHP which is alongside the app with argument of start point->App would be running.
Problem is:
Maybe I don't want my PHP files to be exposed(in application, there will be available source anyway) is there some ready made stuff to do this? Is there some better way than I proposed?
Alternative: Modifying OP Cache to work with "packing" application to deliver byte codes to modified OP Cache which just reads the cache.
My suggestion would be a tiny tool I just finished, for almost exactly the same problem. (Oh yes I tried all the others but they're old and rusty, sometimes they're stuck with 4.x syntax, have no support, have no proper documentation, etc)
So here's RapidEXE:
http://deneskellner.com/sw/rapidexe
In the classical way, it's not a really-real compiler, just a glorified packer, but does exactly what you need: the output exe will be standalone, carrying everything with it and transparently building an ad-hoc runtime environment. Don't worry, it all happens very fast.
It uses PHP 7.2 / Win64 by default but has 5.x too, for XP compatibility.
It's freeware, obviously. (MIT License.)
(Just telling this because I don't want anyone to think I'm advertising or something. I just took a few minutes to read the guidelines about own-product answers and I'm trying to stay within the Code of the Jedi here.)
However...
I would also like the application to have patch-able byte-code, so it's in parts, loaded when needed and only part needs to be replaced on update.
It's easier to recompile the exe. You can extract the payload pieces of course but the source pack is one big zip; there seems to be no real advantage of handling it separately. Recompiling a project is just one command.
Maybe I don't want my PHP files to be exposed(in application, there will be available source anyway)
In this case, the exe contains your source compressed but eventually they get extracted into a temp folder. They're deleted immediately after run but, well, this is no protection whatsoever. Obfuscation seems to be the only viable option.
If something goes wrong, feel free to comment or drop me a line on developer-at-deneskellner-dot-com. (I mean, I just finished it, it's brand new, it may misbehave so consider it something like a beta for now.)
Happy compiling!
PHP doesn't do that natively, but here are a few ideas:
Self-extracting archive
Many archival programs allow you to create a self-extracting archive and some even allow to run a program after extraction. Configure it so that it extracts php.exe and all your code to a temp folder and then runs ir from there; deleting after the script has complete.
Transpilers/compilers
There's the old HPHC which translates PHP code to C++, and its wikipedia age also contains links to other, similar projects. Perhaps you can take advantage of those.
Modified PHP
PHP itself is opensource. You should be able to modify it withot too much difficulty to take the source code from another location, like some resource compiled directly inside the php.exe.
Use Zend Guard tool that compiles and converts the plain-text PHP scripts into a platform-independent binary format known as a 'Zend Intermediate Code' file. These encoded binary files can then be distributed instead of the plain text PHP. Zend Guard loaders are available for Windows and Linux platform that enables PHP to run the scripts encoded by Zend Guard.
Refer to http://www.zend.com/en/products/zend-guard
I would like to add another answer for anyone who might be Googling for answers.
Peach Pie compiler/runtime
There is an alternative method to run (and build apps from) .php source codes, without using the standard php.exe runtime. The solution is based on C#/.NET and is actually able to compile php source files to .NET bytecode.
This allows you to distribute your program without exposing its source code.
You can learn more about the project at:
https://www.peachpie.io/
You've got 3 overlapping questions.
1. Can I create a stand-alone executable from a PHP application?
Answered in this question. TL;DR: yes, but it's tricky, and many of the tools you might use are semi-abandoned.
2. Can I package my executable for distribution on client machines?
Yes, though it depends on how you answer question 1. If you use the .Net compiler, your options are different to the C++ option.
3. Can I protect my source code once I've created the application?
Again, depends on how you answer question 1. Many compilers include an "obfuscator" option which makes it hard to make sense of any information you get from decompiling the app. However, a determined attacker can probably get through that (this is why software piracy is possible).
Problem
I have a legacy codebase I need to analyze and determine dependencies. Particularly the dependencies on classes (internal/external) and extensions (Memcache, PDO, etc).
What I've Tried
I have reviewed the tools listed in Is there a static code analyzer for PHP files?. Unfortunately, this post is dated and most of the promising tools like phpCallGraph no longer work.
My thought was to analyze the code lexically and look for class tokens. Reviewing a list of these would at least allow me to visually determine dependencies. However finding OtherClass in the following code may be complex:
$classname = 'OtherClass';
echo $classname::doubleColon();
In the end, I doubt I'm the first to need this. I'm sure a tool or combination of tools exist to provide what I need. So I'm asking the SO community before writing this myself.
Update
Ideally this tool will analyze multiple files with complete code coverage. As such, tools like Xdebug, while great, are not solutions to this exact problem.
Instead of phpCallGraph you could use Gopal Vijayaraghavan's inclued extension which in combination with Graphviz gives you a nice looking graph of all included files for a certain execution path.
Example:
Moreover, I'd recommend Xdebug (a PHP debugger) which offers a profiler that outputs data consumable by Valgrind. Use the debugger with a compatible IDE to follow the execution path (which helped me a lot to wade thru e.g. Drupal's massive call-stack).
Combine both and you should get a fairly thourough overview.
EDIT
Searched the web and found nWire for PHP - an eclipse plugin that looks like it could be the right tool for you (30 day free trial which should be enough to give you a head start).
I think PhpCodeAnalyzer is exactly what you're looking for - https://github.com/wapmorgan/PhpCodeAnalyzer
It print list of all used external extensions in code base.
Setting up the multi language site I now need to decide which option I need to use for static text on the site. Let me explain my site setup and then if you can help me decide which solution to use.
The site is a CMS system that allows multiple domains to point to the same directory and serves content based on the domain name. So all domains share the same code. On the site I created blocks of code, called modules, that do specific jobs. So I might have a module that all it does is display the latest news from the database. I then can decide what page that module can display on and what site it will display on. So my question is, would gettext work for multiple domains that may have different modules showing up on different pages? Or should I just create a language file for each module that contains an array which has the language conversation for that specific module? So if I had 10 modules, each module would have its own language file and whatever page each module shows up it just refers to the array in the language file for that module to decide what text to show? Hope this makes sense, I read a lot about gettext and using the array version, but cant decide which one is better for this type of site setup.
A lot of CMS uses the array version. I have seen GetText as well for scalable applications. The array version is simpler especially when you want to manage the translation from a web interface.
It is a matter of preference of course.
In my opinion PHP gettext is the way to go. In all my projects I use the wordpress style for translation. http://codex.wordpress.org/Translating_WordPress and using the same functions naming convention:
__('message') // Return the translation
_e('message') // echo's the translation
_n('singular_message', 'plural_message', count ) // return singular or plural
I use poedit http://www.poedit.net/ to extract translatable strings from the PHP source and translate them to other languages. Storing and compiling the files in the required PHP gettext directory structure like this:
en_US/LC_MESSAGES/default.mo
nl_NL/LC_MESSAGES/default.mo
de_DE/LC_MESSAGES/default.mo
Note that .mo files are cached by PHP and changes in your .mo file are non existing until you restart the webserver. Pulling my hair out while developing I came across this very helpfull solution: http://blog.ghost3k.net/articles/php/11/gettext-caching-in-php
The whole gettext thing took me a while to work it out, but is was worth it. Once in place it saved me a great deal of time and allowed my clients to do the translation for their projects themselves.
If you want to activate a community for translating your project have a look at the web based translation tool Pootle.
In my experience, raw gettext isn't terribly well suited for a web site context where content changes over time and usually outside of a formal release cycle.
I'd recommend that you take a look at Zend_Translate (and Zend_Locale, if you want to localize dates, numbers, etc). Zend_Translate is a higher-level library that has adapters for various underlying methods (including gettext and arrays).
It's fairly well documented, and can be used as a standalone component.
In fact, I find gettext easier:
You can just echo / print _("your text"); and translate later
It is easy to be helped with getext editors
To generate the boostrap po file (iirc, the /source/ file), you can use etags that will make a kind of grep on your files. So you'll just have to translate tokens later.
So basically, everything works since the beginning of the project, it is then easier to start, and more convenient for upscale.
I would recommend using gettext. It's a well-established set of tools. There is a tool to automatically extract text strings from your source code (xgettext) and there are other tools that help you with translating your localization files, for example, poedit ( http://www.poedit.net/ ).
If you are running PHP 5.3 and/or have the intl extension installed, there's another option, too: messageformatter:
http://php.net/manual/en/class.messageformatter.php
This is very powerful, but it lacks -- in my opinion -- a little bit of documentation and might be overkill for your purpose. You can find some more information about this at the ICU project's page:
http://userguide.icu-project.org/formatparse/messages
Is it possible to convert a PHP file to binary and deploy it on a webserver?
Since PHP is a (relatively)portable language, compiling PHP source to bytecode instead of binary code is more preferable. For this purpose there is an experimental project called bcompiler.
Some months ago I searched for it (php code protection or script protection) and my results were:
I provide some description but try to google them and pardon me.
Be careful with your search because you may encounter to php compressors instead and compressors are just about GZIP and other http transfer compression mechanisms.
The most important issues with php script protecting tools are:
How much speed of php runtime performance will get low(down)(how much speed down)
Will we need an extra environment or installed tools on the php server?
Easy handling
You will find about whole description and comparison on: http://www.seocompany.ca/software/free-encryption-software.html
Obfuscators
A lot of obfuscators you will find on the web but there's no guarantee for your codes to work.
Even I found a mixed way with Visual C++ and MSVS for obfuscating php and because also I'm experienced with asp.net I tested it however didn't work.
Converters and Lockers
ion protector (http://www.ioncube.com/): Oh not free but I heard many about his famous name
phc (php compiler): free and was a good case but "Brendan Long" said the truth because phc has a painful install way. However result is magic and has famous name such as ion
php locker: I got it and test it. It had error with compiled code and it's released for lower than php5. Absolutely not free and for who thinking about ccr-ac*ks finding it for php locker is impossible.
Zend Guard: A perfect way to guard but it's harder than phc or ion because you need Zend runtime environment (ZRE) on your server and Zend Guard is absolutely non-free however if you are a Zend guy (zend framework+zend IDE+zend Guard) you should know Zend Guard is compatible with zend IDE and code blocking process will be so easy. I'm not a Zend guy because either of zend framework and zend guard get down runtime speed obviously. I love php speeded runtime.
php -> C/C++ compiling (YES IT'S POSSIBLE) (BEST PERFORMANCE THROUGH THE WORLD): It's not so famous so it's normal if no one talked about.
facebook hiphop: This tool is using by facebook to compile php files on c++/c for getting a better performance however finally we have unreadable compiled codes. I don't remeber but I think it needs a good familiarity to linux or about php recompile mechanism on Microsoft Visual C++. (However DON'T TRUST to my weak memory and google it) (AND FOR LEARNING ABOUT PHP RECOMPILE WAY PLZ REFER TO latest release of php_manual.chm)
Finally I made my self simple php obfuscator using regular expressions which worked on php 5.3 and my complex scripts so I moved on OpenSSL and different encryption mechanisms and got a review on php secure development.
Wishing you be successful.
This is way overdue but should do what you want.
Make your own custom extension with the zend engine as they compile to a c++ dll. Add that dll to your ext location in the php directory. After that you can call your own php scripts as php functions. Keep in mind that php is server side only so no one can get your scripts unless they are copied from the server and handed out.
Download the php source library for the version that you have. [windows.php.net] The zend stuff you need will be included.
Step 1. Create a new project and select "General" under Visual C++ and the empty project option.
Give it a name and Click ok. Mine is Project1 so I will be using that.
Step 2. Right click the solution name and select properties. Select Dynamic Library (.dll) Under Project Defaults/Configuration Type in the Configuration Properties/General item. Be sure that you are changing the Debug config as Release is not used.
Step 3. Under VC++ Directiories add the following under the Include libraries:
C:\php-7.1.8-src\Zend
C:\php-7.1.8-src\win32
C:\php-7.1.8-src\TSRM
C:\php-7.1.8-src\main
C:\php-7.1.8-src
Libraries:
C:\php-7.1.8\dev
Step 4. Under C/C++ Preprocessor add ZEND_DEBUG=0;ZTS=1;ZEND_WIN32;PHP_WIN32 to Preprocessor Definitions
Step 5. Under Linker Input add php7ts.lib. This needs to match the lib for your version of php
Click ok to save the Property settings for your solution.
Now lets add a code file for your function (Project1)
Under the source files folder right click and add Code. I called mine Project1.cpp and here is the source. You'll need to rename config.w32.h.in to config.w32.h and copy it to the directories where it is needed. Intellisense should tell you where it's looking and config.w32.h.in is in the C:\php-7.1.8-src\win32 directory.
// this needs to match the compiler version that php was compiled with
#define _CRT_SECURE_NO_WARNINGS
#define PHP_COMPILER_ID "VC14"
#pragma once
/* You must include config.w32.h first */
#include "win32/config.w32.h"
#include "php.h"
ZEND_FUNCTION(ReturnString);
zend_function_entry Project1_functions[] =
{
ZEND_FE(ReturnString, NULL)
{
NULL, NULL, NULL
}
};
zend_module_entry Project1_module_entry =
{
STANDARD_MODULE_HEADER,
"Project1 Module",
Project1_functions,
NULL, NULL, NULL, NULL, NULL,
NO_VERSION_YET, STANDARD_MODULE_PROPERTIES
};
ZEND_GET_MODULE(Project1)
ZEND_FUNCTION(ReturnString)
{
zval* value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE)
{
RETURN_FALSE;
}
convert_to_string(value);
RETURN_STRING(Z_STRVAL_P(value), true);
}
Press F7 to compile and it should create Project1\Debug\Project1.dll. Copy Project1 to your ext directory C:\php-7.1.8\ext and add an extension=Project1.dll to your php.ini and you should be good to go. If it doesn't work double check your properties to make sure you didn't miss something.
The script is quite simple:
<?php
echo ReturnString("The Returning String");
?>
If the web server is Linux based, you can create a package like .deb or .rpm (depending on the Linux distribution) and easily distribute/deploy it.
BR,
Dawid.
It depends on what you mean by "binary".
If you want to compile (or just obfuscate) your PHP code to keep someone else from modifying then use a bytecode compiler. One example are the tools from Zend, among others. (I prefer Zend's tools because they the primary company behind PHP and fully QA all their tools against all the versions of PHP).
If you want to compile your PHP code and link the PHP runtime to it and then deploy it (like C\C++), then no. Maybe in theory that would be possible but it would be a mess. (Not practical or feasible and don't think anyone has put anything together to try and the output would also be tied to a particular architecture).
I've inherited a PHP application that has "versions" of pages (viewacct.php, viewacct2.php, viewacct_rcw.php, etc). I want to discover which of these pages are called from other pages in the application and which are not. Is there a tool available that will help with that?
Using whatever tools you would like (Find/Grep/Sed on Linux, I use Visual Studio on windows), it is just a matter of crawling your source tree for references of the filenames in each file.
Similar to FlySwat's answer: any good text editor or IDE with multi-file search should be able to help you find the orphan pages. On Mac OS X I would suggest TextWrangler(free), TextMate($), or BBEdit($$). I've had good success with each of these tools, but your mileage may vary.
If you wish to find out what pages are called by other pages, you need to look at where stuff is being called. Obviously in php code, you can only reference other files via includes or requires and the singular versions of those functions.
So if I were you I would grep your code for include and then require and attempt to make some kind of map showing what is calling what. Eventually you should end up with a pretty clear map of how the php files talk to each other. Then you will need to work out how the various points of the application talk to each other from there via HTML/AJAX etc.
Good luck. I have done it before, it takes a while, but you'll get there, just make sure you document what you find out.
You may want to try out nWire for PHP.
nWire for PHP is an innovative Eclipse plugin (works with Eclipse PDT & Zend Studio 7) which accelerates PHP development by helping developers navigate through their code and better understand the architecture of their application. nWire offers unique tools for real time code visualization, navigation and search.
nWire analyzes all the components and associations in your project. While opening a file you can immediately see where (and if) it is being used.