Tag Archives: PHP

Quick tip: How to run php script like application

It’s really quick tip:
Sometimes you need to make a shell script which need to be executed either on regular basis, or like infinite loop.

You always can run it by:

/usr/bin/php /path/to/script.php

but if you add a shebang line, the script can be run as standalone application.

Example:

#!/usr/bin/php -q
<?php
//Your php code goes there
?>

Then you can run it like:

/path/to/script.php

Hope this helps

How to check your php project (many files in a folder) for parse errors

Hey hadn’t wrote anything for a while here, but this is so brilliand and convenient, so I couldn’t resist to share it.

It’s about to check your project for obvious errors before releasing the changes on the production server. I found this answer in StackOverflow, but the solution is for SVN repository and while currently I am working with snv it suits me, but looking forward to migrate to Git, I was thinking “Wasn’t it nice to check the all php files within a folder?”

So here is the solution:

for i in $(find . -iname \*.php ) ; do php -l $i ; done | grep "Parse error"

This should be executed in terminal (at least in Ubuntu it is straight forward) and it print all files which had Parse errors within the folder. I think it’s a must for any php developer who release their code in production server. I already put it as alias in my .bashrc, but I will add it in my “build” script too.

Probably it could be optimized, but for me is pretty much enough.

Detecting if the cookies are enabled with PHP

For my current project I need a detection if the cookies are enabled or not in the user’s browser.

The easiest way to do this is by using this code:

<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
    header('Location:/info.php?cookies=true');
}
if(count($_COOKIE) > 0){
    echo "Cookies are yummy!";
} else {
    echo "You didn't bring any cookies here. We are hungry!";
}
?>

The CakePHP way is almost similar:

<?php
$this->Cookie->write('test', 1);
if(!isset($_GET['cookies'])){
    header('Location:/info.php?cookies=true');
}
if(count($_COOKIE) > 0){
    echo "Cookies are yummy!";
} else {
    echo "You didn't bring any cookies here. We are hungry!";
}
?>

Ok, it’s not rocket science, but it helps ๐Ÿ™‚

Autoload your javascript and css in CakePHP

Have you ever wanted to have all your css or javascripts files loaded automatically once they are on place under /webroot/js and webroot/css folders? Well this is the solution.

What is all about

I’ve build a quick helper which will include all files under the js/ and css/ directories. So once the javascripts and css are there, they will be loaded automatically.

How to use it?

Using it is really easy. It’s like a normal helper:
1. add the file autoload.php under your /app/views/helpers
2. add it in the $helpers var in the controller
3. add the following snippet in your layout file. It should be under /app/views/layouts:

<?php echo $autoload->javascript();?>

This will include all files under /webroot/js

<?php echo $autoload->css();?>

This will include all files under /webroot/css

<?php echo $autoload->all();?>

This will include all files under /webroot/js and /webroot/css

Key features:

1. The helper includes all files recursively.
2. The helper includes also files under /root/vendors/js and /root/app/vendors/js too (same apply to css). Vendors are loaded first. (Thanks to suggestion from Juan Basso)
3. The order of the files in one directory is based on the name, so now you can control the order as well. (Thanks to suggestion from Juan Basso)
4. Files starting with . (dot) are not included, files under directories starting with . are not included as well, so you can exclude some files
5. if you want to load some files after other use directories. For example if you want to include plugins after the main lib (jQuery), place them in plugins directory like:
js/plugins/plugin_one.js
js/plugins/plugin_another.js
js/.hidden/plugin_third.js
js/jquery.js
the result will be:

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/plugins/plugin_one.js"></script>
<script type="text/javascript" src="js/plugins/plugin_another.js"></script>

(same apply to css as well)

Warning: I’ve noticed that this helper doesn’t work properly with scriptaculous, because the script tries to load the additional plugins and they fail, but for jQuery there is not a problem at all.

Finally here is the code of the helper:
Continue reading

Blast from the past

Hey guys,

last week I’ve worked on a project which I finished somewhere in spring of 2007 and I decided to share my experience with this post. I don’t know did you had such experience, but for me it was interesting, because working on old code is always challenge.

Basically, the project was really small one, which uses 80% of scaffolding, so really nothing complicated. Now the client wanted some extensions to the core functionality /like adding few more look-up tables and some basic reports/ and because I was the only one developer who worked on it, they ask me to do this and I agreed.

My first thought was to upgrade the core CakePHP lib to the last version, but after thinking I decided not to, because if something goes wrong /like some deprecated functions/, I need to do more work in debugging rather than focusing on the real tasks.

What I noticed while I coded?

The major one – Improvement of the console script. In the past it was in the /cake/scripts/. In the folder there were acl.php, bake.php and bake2.php, extract.php for label extraction and master bake which I never used. Now, the console script is more advanced and provide more functions. Still I am not big expert on it and I still using it for basic operations :).

Fully translated labels – it’s related to the previous one – when the code was generated with old bake script, some of the labels weren’t wrapped with __() function and especially for me it was biggest pain. Someone could tell me that there was ability to modify the templates, but I personally never did it.

The truth is that CakePHP in fact is improved a lot since then. Hopefully it will continue in this direction in the future as well.

Anyway, it was really interesting experience for me.

The dummy mistake while coding

No body is insured from stupid mistakes while writing code. I am not insured, but subscribed for such things. ๐Ÿ™‚

Here is the story:
Yesterday, while I was working for a small project I lost 1 hour to detect the stupidest mistake I ever made. Here I will explain what happened and how dummy I fee after that.

I am writing an application where users insert records into the database, and after that on every show of the record, there is a counter field which need to add up the number in it. Simple and easy situation.

While I was working I noticed that only one record /from 5 in the database/ got updates on his counter fields. All other had 0, while I was petty much sure that I’ve seen all these records on the screen. Well, I forced showing the 0 rows but the result was the same. Then I start investigating what could be the problem, but in the database everything was just fine. I deleted all records and started inserting texts /because there are some text fields important in this story/ one by one. Strangely, but again some of the records got update, some not. Finally /by accident/ I noticed, that counter changes when there is a space before or in the end of the value of the text I entered.
Continue reading

Using more than one database connection in CakePHP

Probably is pretty obvious for most of the advanced users, but when I started my experience with CakePHP I read a lot of configuring a database, but not multiple ones. There are articles how to use database for development and for production without changing anything but rewriting a function in DATABASE_CONFIG class.

These days we need to choose way of splitting the functionality and we have to decide: Shall we use different databases or shall we put a prefix for every table. So far we choose to use prefix, but I dig into this and I realized that every model could be attached to different database.

Here is the example how to do this:
Continue reading

Security Issue in CakePHP

I notice this recently when we start creating the security component of a project. The best way to explain the issue is to give an example:

Imagine that in your application you create an action “edit profile” where each user can change his personal details for the account. If course there will be fields for changing user’s real name, password, email etc., but the username field should be readonly.

The direct approach to create such page is to reuse “edit” action of the user’s controller, but instead of getting the ID from the url, it need to be fetched from the session’s auth variable. The second thing which you have to do is to remove “username” field from the view and you are done. ๐Ÿ™‚ Well, fast and easy, but not very secured…
Continue reading

htmlSQL class – quite nice way of parsing html

Today I found a class written in PHP which implement the idea of using SQL syntax while parsing HTML documents – htmlSQL. The idea of the author – Jonas David John – is quite simple. If you want to parse a HTML document, let’s way you want to parse all divs with class “row”,the syntax will look like normal SQL:

SELECT * FROM div WHERE $class == "row"

Looking familiar isn’t it? There is also function connect() /which define the html source/ and fetch_array() which contain the results after the query.

There are few examples included in the library package and here is the simplest one:
Continue reading

CakePHP and Layout – secret of data passing through

In my current project I need to deal with the Layout more than adding some header, static menu and footer in it. I need to have dynamic menu loaded from the database plus additional blocks which will contain some data related to the main content. For example YouTube.com /and many other sites/ has some blocks which appear all over the site like related movies block from the right depending from the tags related to the main movie. There are a lot examples.

Well, searching in the CakePHP Manual, CakePHP Google Group or Bakery doesn’t satisfy my understanding how to solve the case. Apart from $anything_for_layout: Making HTML from the View available to the layout article I didnt find anything on this topic. And this one sounds like a hack rather than a complex solution.
Continue reading