Text truncating function that secures both HTML tags and full words

Akshaya K Sahu’s answer to this question at Stack Overflow is a great example of text parsing function that can truncate any HTML-encoded string at given length, taking care of all the needed aspects, i.e.:

  • full words,
  • properly closed HTML tags and
  • respected UTF-8 encoding (double-byte characters!)

I have actually nothing to add to it, so I keep a copy of this code only for my own reference. And only because the original answer lacks some comments.

Read More “Text truncating function that secures both HTML tags and full words”

Fine-tuning CKEditor 4’s toolbar

Forcing CKEditor 4’s toolbars to look exactly as you’d like is a bit hard task. Somewhere in official docs it is said, that you should use config.toolbarGroups configuration settings for this purpose. This is, of course, a complete mistake.

Benefits are weak and you’re actually loosing all the control over which button, in which group and in which line of toolbar should appear. This article will help you design CKEditor 4’s toolbars exactly, as you wish to have them, using old, good config.toolbar-way.

Read More “Fine-tuning CKEditor 4’s toolbar”

Cyclic jobs in Yii and MySQL

When we are talking about some cyclic tasks executed periodically in PHP, most of us automatically thinks about CRON. It is not surprising, since it is very popular, easy to manage (available often even on shared hostings) and easy to code (it simply fires given PHP script).

However, there are four other ways you can achieve exactly the same in Yii/PHP. And many Yii developers may not be aware about some of them.

Read More “Cyclic jobs in Yii and MySQL”

The unlink function returns TRUE on non-existing files!

Is seems, that unlink() returns FALSE only, if file, that is about to be deleted, exists and there was a problem removing it. If file wasn’t there, when unlink tried to remove it, it still does return TRUE. Keep that in mind!

This seems to be reasonable. Logic, that I see here is:

You wanted me to delete that file and… swoosh… it is gone. It doesn’t matter, that I had nothing to do with its deletion, right?

For some this could be surprising — unlink() function returns logic value about whether file, that should be deleted is deleted. It’s return value says nothing about whether actual deletion process occurred.

For me this is not only surprising, but also wrong! Dear PHP, I wanted you to “delete” this file (which you didn’t). Not, to “make sure it is gone” (which, we may agree, that you did).

Upload files via AJAX and fill up other model properties in the same time

There’s a comment to Yii 1.1: XUpload Workflow Wiki article, made by MeDroogie, who asks, how to handle situation, where file is correctly uploaded (via AJAX, in separate layer, handled by upload action), but form submission itself fails, as form processing action stops on some model’s validation errors.

I had the same problem with other AJAX uploader, that I think, I solved gracefully.

Keep in mind, that since solution, that I’m discussing in this article, is part of proprietary project, I cannot share any code. This is purely design or theoretical discussion.

Read More “Upload files via AJAX and fill up other model properties in the same time”

Open phpMyAdmin with preselected database

The correct URL should be like that:

http://[HOST_AND_PATH]/index.php?db=[DB_NAME]#PMAURL-1:db_structure.php?db=[DB_NAME]

I found this path to work in any conditions. After logging-in with this path, user should see phpMyAdmin open with pre-selected database ([DB_NAME]) and should see that database’s tables list, not pMA‘s home screen.

And, as I just verified this, it works even on as old phpMyAdmin as version 2.11.3.

Round functions in PHP still returns float!

When you round any float number to integer, rounding function (for example floor) still returns float type variable! What?

Well… on second thought, this is reasonable (and explained). PHP does it, because “the value range of float is usually bigger than that of integer“.

So, for example, if you would try to round a number bigger, that integer type can handle (> 2 147 483 647), PHP wouldn’t be able to do anything with the result of such rounding, if it would return it as integer.

Two-way encryption in PHP

I found two quite interesting examples at Stack Overflow about two-way encrytion / hashing in PHP. While two-way encryption is never as secure as one-way version (some claim, that two-way encryption methods are not secure at all), it is still a good alternative to not using encryption at all. For certain simple tasks, you may find it quite useful.

Read More “Two-way encryption in PHP”

Never allow users to transfer files with non-Latin characters in name

I have received a PM message at Yii forum asking about possibility of transferring (via HTTP upload) files with non-English characters in filename. In this particular example, a Greek and Chinese (and English), but with option to support all the languages, that exists.

Conclusion: No f*ing way! But, if you wish to read something more about this, follow with this article.

Read More “Never allow users to transfer files with non-Latin characters in name”

Downloading large files with PHP

First define, what do you mean, by “large” and “huge”? In this post I present the quickest solution of using file chunking. It works fine (tested!) for files of size up to 2 GB. If this is enough for you, fine — go ahead. If you need to download something bigger, consider using mod-xsendfile (only on Apache — more here and here).

Chunking files is the fastest / simplest method in PHP, if you can’t or don’t want to make use of something a bit more professional like cURL, mod-xsendfile on Apache or some dedicated script.

Read More “Downloading large files with PHP”

Common hashing functions are unsuitable for passwords

According to PHP team, common hashing functions such as md5() and sha1() are unsuitable for passwords. Why? They’re to fast and by this, not so secure and open to brute-force decrypt. No matter, what you think about this, we must admit, that md5() function is listed among “Text Functions” in PHP’s docs, so it doesn’t even touch “Encryption” or “Security” parts in documentation.

Mcrypt seems to be good alternative to those. And mcrypt-module-open function contains good example on both crypting and decrypting with mcrypt. See mentioned article for more details and other alternatives.

Get first character of a string… fast!

Strings can be used as arrays of characters in PHP, which allows to use the [] to get character at particular position. Whenever you know exact position of the character you’re looking for, you should use $str[n], instead of substr($str, n, 1), where n is character position. This is much faster method. More here.

“Class SQLiteDatabase not found” error after upgrading SQLite

Class SQLiteDatabase is an object from sqlite library, which support was dropped in PHP 5.4, but on various systems and configuration could be disabled in an earlier releases, as this library was long time marked as going to be deprecated.

Library php_sqlite.dll (Windows) or php_sqlite.so (Linux) is no longer supported in newer versions of PHP and was replaced with php_sqlite3.dll or php_sqlite3.so respectively.

Read More ““Class SQLiteDatabase not found” error after upgrading SQLite”

Example of using cURL for converting a webpage to a pure text

The preg-replace function takes a URL and returns a plain-text version of the page. It uses cURL to retrieve the page and a combination of regular expressions to strip all unwanted whitespace.

This function will even strip the text from <style> and <script> tags, which are ignored by PHP functions such as strip_tags (which strips only tags, leaving the text in the middle intact).

Read More “Example of using cURL for converting a webpage to a pure text”

Using Twitter Bootstrap’s popups like real menu items

Twitter Bootstrap framework is fabulous and thanks to many Yii extensions supporting it (Yii-Boostrap, Yii-Booster, Yiistrap, YiiWheels and more) using it in own application is like snapping with fingers.

One of the best features of Bootstrap is a very easy way of creating menus and adding popup menus to elements (like buttons). However, in default implementation popups are oriented toward working just like a fancy links — i.e. redirecting browser to destination URL. In this article, you’ll find how force them to work as real menu items — i.e. capturing their onclick event and doing something with content.

Read More “Using Twitter Bootstrap’s popups like real menu items”

Convert string into key-value array

I was looking for a function or solution, that would convert a string into associative array, i.e. respecting both keys and values. To be successfull, such function would have to operate on two delimiters. One for separating each key-value pair from surronding one. And second — for spliting keys from values. Which is, where PHP’s build-in explode function fails. Lucky I am, my two favorite uncles — Uncle Google and Uncle Stack Overflow — helped me in this case as well.

Read More “Convert string into key-value array”

Application works fine on localhost but fails on web server

If you ever run into situation, that your application works fine on localhost (or one of webhosting) but fails completely on webhost (or another server) then first thing, you should look for, is to check, if you don’t have an extra XHTML line in on of your files that you’re loading using include or require.

Meaning, that your loading and PHP-parsing these files. Because problem doesn’t exist, if you’re loading this files as simple text files, using file_get_contents for example.

Situation, I’m talking about most times causes a PHP syntax error saying, that there is an unexpected T_STRING in first line of one of the files used in an application.

Read More “Application works fine on localhost but fails on web server”

Simple page rendering class

I have created a simple CPage class, which I use in my non-Yii projects for easily rendering views, templates and whole pages using object-oriented approach. This class can render given contents into given view and embeded it in a selected layout file. These are very limited versions of Yii framework’s view and layout rendering mechanisms. I have also added a simple alerting system, this time taken from Twitter Bootstrap.

Read More “Simple page rendering class”