8 articles Articles posted in Web Development

Setting up a complete PHP development environment on ubuntu 12.04+

ubuntu

Last week, I had do reinstall my laptop and setup the complete php development environment. This includes the apache2 web server, php5, mysql, phpmyadmin, git, and a good php editor. Thought that this setup could be useful for other php developers who want to use Ubuntu, so I’m sharing a step by step guide here :)

Before going any further, lets get something clear: this is for local / development environments, not for production servers! :)

First things first

Do you already have Ubuntu installed, right? I will not give advice on this, but you may find everything you need do install Ubuntu here: http://www.ubuntu.com/download

I’m currently using the 12.04, the LTS (long-term support) version. I downgraded from 12.10 after getting a lot of weird problems with my audio, and It solved the problem. This instructions will work fine for other Ubuntu recent versions, though.

I don’t like Unity, so I installed Gnome 3 which is amazing for me. Of course everybody has its own tastes, so feel free to use whatever you want as a desktop environment. But if you want to try Gnome 3, installing it is a piece of cake:

sudo add-apt-repository ppa:gnome3-team/gnome3
sudo apt-get update
sudo apt-get install gnome-shell

Web Server

This 3 commands will install the local server, in this order: Apache 2, MySQL*, PHP 5.

sudo apt-get install apache2
sudo apt-get install mysql-server php5-mysql
sudo apt-get install php5 libapache2-mod-php5

Ps* When installing MySQL, you will be prompted to provide a password for the root mysql account.

Now your webserver shall be installed and running. Point your browser to http://localhost and you will get this:

Screenshot from 2013-03-27 20:46:33

 

The Apache’s Document Root, by default, is located at /var/www on Ubuntu. You can easily change this to a directory which best suits your needs. Just edit the file /etc/apache2/sites-enabled/000-default with an editor of your choice (just remember you need to use sudo).

Change all “/var/www” to your desired path – there are 2 places (lines 4 and 9).

Screenshot from 2013-03-27 22:57:56

You will probably want to have URL rewriting enabled, so I recommend you also edit line 11 and change “None” for “All” (AllowOverride All).

After doing this, you need to restart Apache for your changes take effect.

sudo apache2ctl restart

Now, if you reload http://localhost you will get your new document root, which can be a directory structure (easy to navigate between different projects without any extra effort, but may be a problem to some project implementations).

You can also create a VirtualHost for a specific project, so you can access it with a url like this: http://myfakedomain.local. This scenario makes your environment more similar to what you have at production servers, and it’s not hard to set up.

Setting up an Apache VirtualHost

You just need to edit 2 files. First, create an entry inside your /etc/hosts file (use sudo to open the file otherwise you cannot save it). Add your desired fake local domain name, like this:

127.0.0.1        myfakedomain.local

Now, edit the same file you opened before – /etc/apache2/sites-enabled/000-default . You need to add a VirtualHost entry. As we are going to use name-based virtualhost, we also need to add this at the top of the file:

NameVirtualHost *:80

Then, add the VirtualHost section:

<VirtualHost *:80>
 ServerAdmin your@email.com
 DocumentRoot "/path/to/your/project"
 ServerName myfakedomain.local
</VirtualHost>

Now, just restart Apache and try http://myfakedomain.local in your browser.

We have our server running, and now let’s get some extras.

PhpMyAdmin

Installing:

sudo apt-get install phpmyadmin

You will be prompted to choose the web server (apache) and to provide the mysql root password.

After  this, PhpMyAdmin will be available in http://localhost/phpmyadmin , and you will be able to access it directly (without providing password).

GIT

Installing is quite straightforward:

sudo apt-get install git

Now configure your git user:

git config --global user.name "Your Name Here"
git config --global user.email "your_email@example.com"

And run this to have a colored git (like code highlighting – way better to read).

git config --global color.ui true

Sublime Text 2

Sublime is probably the best complete (and lightweight… and awesome) editor available for free nowadays. They gentle ask that you buy a license, but there aren’t any restrictions or limitations in the version we download for free. Sometimes it will show a silent popup to remember you about the license stuff, and that’s all.

sudo add-apt-repository ppa:webupd8team/sublime-text-2
sudo apt-get install sublime-text

Did I forget something?

If you want to suggest something, please leave a comment! Keep in mind that this is a *very* generic starting point for a php development environment, really the basics for getting started.

 

A simple Twig truncate filter – Silex

twig-logoSometimes you can get in trouble when dealing with dynamic data with variable length, such as titles and descriptions, so they can fit well in your layout. With Smarty you have the built-in filter “truncate”, but Twig doesn’t have this filter by default. I know there’s some text extensions available, but I didn’t get it to work with Silex easily and I didn’t want to lose more time on this issue, so I made this simple twig truncate filter and it’s working perfectly for truncating strings in the smarty style.

Just add this to your bootstrap.php (or whatever initialization file you use), after registering the Twig Extension:

Use it like this:

{{ my_big_title|truncate(10) }}

The code below will truncate your title to 10 characters, including a ‘…’ at the end of the string.

Silex and Localization (i18n/L10n): TranslationServiceProvider

15017435-flags-globeI’ve been using Silex* in a large variety of projects in the last year, and I always find something new to make my life easier. Last week, I was dealing with internationalization / localization (i18n / L10n) – a quite relevant topic when talking about web projects aiming a high audience. This post shows how to make an easy structure who automatically loads language files written in YAML, using the TranslationServiceProvider. Although the post is focused on Silex, I believe it’s also compliant with Symfony 2.

If you wanna go directly to the code, there’s a GitHub repo with the whole example (a basic silex application) here: https://github.com/erikaheidi/silex-L10nex

For those of you who didn’t have the opportunity to try Silex before, I have a post here covering the basics, and a Pagodabox quickstart with a Silex barebone using Twitter Bootstrap for front-end. Silex is a micro framework based on Symfony 2.

Structure

Before going any further, let’s talk about project structure. With Silex, you have a quite liberty to choose whatever structure works better for your project. To make things easier, let’s consider the following directory structure and files:

  • src/
    • locale/
      • en/
        • app.yml
      • pt-BR/
        • app.yml
    • templates/
    • app.php
    • bootstrap.php
  • composer.json
  • composer.phar
  • www/
  • vendor/

You can see it better here: https://github.com/erikaheidi/silex-L10nex (without the vendor directory, which is installed when you hit composer install ) .

The YAML translation files

The basic usage of the TranslationServiceProvider loads the language strings via arrays, but of course this is impracticable (unless you only want to translate a really small amount of strings). We’re going to use YAML translation files, making an automatic loader which reads a directory. For accomplishing that, we’re going to need 2 more components provided by Symfony: Config e Yaml.

This is the content inside the app.yaml translation file, inside the pt-BR folder:

locale_lang: Português
Welcome: Bem Vindo
msg_example: Esse é um exemplo de texto traduzido.

Registering the ServiceProviders

First of all, you need to update your composer.json with the new dependencies. We will be working also with Twig and Sessions:

Heads Up: to use the trans filter on Twig templates, you need the TwigBridge component as well.

For registering the SP, this code shall go in your bootstrap.php (or wathever place you use for the app initialization):

Loading the languages

Now we need to load the language files. You could load everything on bootstrap.php, but this would cause an unnecessary load, since we just need one language each time the page is loaded. Of course this must be done at the beginning of the application code.

Changing the current language

Now lets create a route to actually change the current language. You could also do this automatically after checking request/browser headers.

Using on twig templates

Its incredibly easy to use the translation strings on twig templates. As said before, just make sure you also include TwigBridge as a dependency in your composer.json. You just need to use the trans filter.

Just like this:

{{ ‘Welcome’|trans }}

See the template code here: https://github.com/erikaheidi/silex-L10nex/blob/master/src/templates/index.twig.html

The example app is available here: https://github.com/erikaheidi/silex-L10nex

If you are cloning the repo, don’t forget to run

php composer.phar install

to install the dependencies (vendor directory).

Why you, regular developer, should consider moving to a PaaS solution right now

cartoon_clouds_1So, you just finished your kick-ass web application and it’s ready for deploy. If you did it before, you are probably aware of all the headaches a “simple” deploy can bring to you – sometimes things just don’t go as expected. And if you are still going to buy a hosting package for your app, you know it will take some time – days – for your environment to be ready for deploy. Is this familiar for you?

But this is not the worst part. Lets suppose you bought a cheap hosting (of course, you are just starting in the business!) for your app. Then, suddenly, it starts to grow unexpectedly – your app is a huge success, and you must be super happy, right? Wrong, because your app is offline – your hosting provider thought that it was “stealing” too much memory from the shared server, so they decided to put it offline.

What are your options now? Buy more memory, change to another company?

Well, I had this experience quite a lot in the last years, and it’s not funny at all. I switched from shared to dedicated server, then to another (better) dedicated server (because the one I was using before was getting really too expensive), then to another one, and another one… all these changes were very stressful, and they costed me a lot of money and time.

CloudComputingCartoonSince the social networks boom, everybody talks about “the cloud” as a magical solution for everything.  And they even say it’s cheaper than dedicated hosting. But my first attempt to get something “in the cloud”, with Amazon (3 years ago), was just horrible. I got so confused with the interface and all their product names, and it was really expensive comparing to what I was paying in that time for my dedicated server. I ended up with an “OK” meme face an the idea that these ~things~ are only for companies and really big projects.

Now it’s 2013 and the PaaS (platform as a service) topic came up again. But now we have more options, new companies and new technologies – wouldn’t it be great if you could deploy your application with Git? And what if you could change the whole app (which is, in fact, a website) to a previous commit, right before that demonic bug appeared? This is already a reality with PagodaBox and other new-generation PaaS.

The best thing is: you can try it for free. The majority of PaaS offers a starter free “package”, so you can try it with no strings attached. Some applications don’t need any more resources than what they offer for free – sounds perfect, right? And its REALLY simple to get your application running.

That’s why I strongly encourage you to try it. When I said “regular developer” at the post title, I was meaning a develop who may think that the cloud is a bit too much for its small to medium projects (this was me yesterday). Even if it’s only for learning purposes, or to test your application before deciding how you will make it available. Because this is the future of web servers.

I’m using Pagoda Box now with this WordPress blog, and I have to say that it’s amazing. I plan to write a Pagoda Box tutorial in the next days, so if you are interested please come back later =)

Getting started with Silex – the php micro framework based on Symfony 2

SilexThis post aims to show the basics, and how to get started with the php micro framework Silex- which, by the way, is my favorite php framework nowadays. It’s based on Symfony 2, but focused on smaller applications. It has a really comprehensive and intelligent schema for url rewriting (so-called “Routes”) that brings to PHP one of the great things you can find in Django. It’s concise, extensible – using Pimple and Composer for dependency management – and secure. Oh, almost forgot: it’s practical, easy to learn and super versatile – according to my own experience with the framework so far.

So, lets write some code! These instructions are focused on Linux (Ubuntu) environments. Another important thing to note is that Silex requires PHP 5.3 or higher.

First things first: install Silex via Composer

Let’s start by installing Composer*, so we can download the last version of Silex. This is the best way for maintaining your project and manage dependencies, its really easy to install and update everything! Open the terminal and go to your project folder. Then:

curl -s http://getcomposer.org/installer | php

Now, you must create a composer.json file containing instructions about which packages you are going to use in your project. The basic composer.json file for Silex is bellow:

Now you can actually install everything:

php composer.phar install

You will get something like this: Screenshot-from-2012-11-06-104546 Note: if you get a json error when installing composer, try to edit the file and trim the whitespaces. *Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you. If you are not using Linux or have some trouble using Composer, you can also download Silex in the old-fashioned way – just go to http://silex.sensiolabs.org/download and follow the instructions.

Hello Worlding

Now that you have Silex installed, have a look at the directory tree. You will find a folder named “vendor” – that’s where Composer installs all dependencies defined at composer.json . Let’s create an index.php file at the root directory of your project and make some “Hello World” stuff. You can organize things better later. Let’s start with the basics.

This will give you a basic “Hello World” output, as you can imagine. But let’s see what happens if you remove the route definition part from the script:

Screenshot-from-2012-11-06-105859

Want to get more information about this error? Set the debug mode in your application to true. The code will be like this:
And you will get this: Screenshot-from-2012-11-06-110957 Gorgeous! Now you can debug everything – just remember to unset this option when your project is in production.

Working with Routes

Now that you are familiar with the basics, let’s take a deeper look at the Silex Routes. What if I want to get some parameters along with the request? No problem at all – there’s a quite awesome way to accomplish this:

Got it? Heads up: when somebody hits the /hello path, the app will throw an error, since the only defined route is /hello/something. You can use the value modifier to set a default value for {name}, so you don’t need to define another route for /hello. Just like this:

Note that until now we only worked with GET routes. The POST routes are very similar, though. The only difference is that you shall work with a Request object to get the post variables – then you must include the Request class from Symfony HttpFoundation. Like this:

If you don’t want to specify the method (GET, POST, PUT or DELETE) you can use the “match” method. This is useful for getting generic requests like you would do with the $_REQUEST global var in plain PHP. For example – if you want to match GET and POST for the same route and var:

Last, but not least: the order in which you define your routes is significant. The first route matched will be used – so place the more generic routes (like ‘/’ ) at the bottom.

For a complete reference about Silex Routes (there’s a lot of other options, including filters and requirements using regex for matching the request variables), take a look at the the documentation: http://silex.sensiolabs.org/doc/usage.html#routing

The purpose of this post was to give a brief introduction to Silex. If you liked what you saw, I strongly recommend you to read the official documentation, so you can take advantage of everything this microframework has to offer to increase your productivity when creating not-that-big projects. Here are some links for getting started:

Silex Website - http://silex.sensiolabs.org

Official Documentation: http://silex.sensiolabs.org/documentation

Matthias Noback’s blog about silex and symfony2 – useful posts and how to’s: http://php-and-symfony.matthiasnoback.nl/category/silex/

How to selectively show content for followers on Facebook Page Tabs

like.us_.on_.facebookIn this post, you will learn how to selectively show content on your Facebook Page Tabs – you can show a special content for users who liked your fan page, for example – without the need to request any kind of user authorization / permission. This is extremely useful if you have high-value content to share , or if you want to create some kind of giveaway only for your followers (and gather a bunch of new followers as a consequence).

If you are not familiar with Facebook page tab applications, you should take a look at this post: How to Create a Facebook Tab App for your Fan Page - which has a step-by-step guide on creating a tab app from scratch.

First of all, prepare and set up your tab application.

How it Works

When a user reaches your application tab, he will send you a signed request. This signed request contains a piece of (public) information about this user and the relationship between him and your page – if he likes it or not. This data is signed using your App Secret (that’s why is so important to keep it secret: only you and Facebook shall know it). The process to decode this data is quite easy, though. These two functions (which was shameless copied from the Facebook Developers Documentation) below will do all the hard work for you. At the end you can see the usage in a working code parsing the request.

Below, you can see an example of a signed_request array taken from the print_r above (I just removed the OAuth token from it).

Array ( 
   [algorithm] => HMAC-SHA256
   [expires] => 1348675200 
   [issued_at] => 1348669677 
   [oauth_token] => (user oauth token suppressed)
   [page] => Array (
       [id] => 462041577153253 
       [liked] => 1 
       [admin] => 1 
    ) 
   [user] => Array ( 
      [country] => br 
      [locale] => en_GB 
      [age] => Array ( [min] => 21 ) 
    ) 
   [user_id] => 707860628 
)

Take a look at the “page” sub array – there you can find out if the user liked or not the page. Also, you can check if the user is an admin of that page. This is useful if you want to show some administrative information / action to perform only for page admins.

You may have noticed that we don’t get much information about the user at all. This is expected, since you didn’t asked the user for it – if you want any other information about the user, such as its name, you need to request authorization (and this will be left for another post).

*I don’t have any coupon codes to give, the image is only representative :D

How to create a Facebook Tab App for your Fanpage – step by step guide

In this post, I will show you how to create a Facebook Tab App from scratch. If you are a web developer, you can do all the job by yourself, but if you don’t have at least some basic knowledge about web development ,you’ll probably need someone else to help you.

You can find a Portuguese (pt-BR) version of this post, also written by me, here: Tutorial: como criar abas customizadas (timeline apps) para sua fanpage no Facebook .

Fist of all: you’ll need to be a Facebook developer in order to create applications, but it’s quite easy to accomplish that. You just need to register yourself (you need to log-in with a valid Facebook account) at http://developers.facebook.com .

Before you Start

Before creating your application, you need to prepare your content. It must be accessible via http, since Facebook applications work with iframes. When a user reaches your application, in fact he will be accessing your url via an iframe inside Facebook. You can manage to only show content for users who liked your fanpage, or to show an specific content for these users (and another one for the non-followers). Later we’ll talk more about this.

For learning purposes, we’ll be using a simple static html page as content, with a “Hello Facebook” text inside it. This content is online at this url: http://entrebits.com.br/helloface.html . Remember you can use any content you want, as long as it’s publicly accessible via http. It should fits on 810px wide.

Create the App

Access https://developers.facebook.com/apps and click on the “Create New App” button. You will be prompted to fill in the form with basic information about your app:

p01

Give a name to your app in the first field. In the second field, you must provide a unique name as a namespace. Then click on the “Continue” button. A Captcha window will appear. After filling the captcha, you will be redirected to an “edit” page where you can customize your application.

p02

In the header you will find important information about your recently created application. Here you can also upload an image and an icon to your app (just click on the images and a form will pop up).

The App ID identifies your application. As well as the App Secret, the ID must be provided when you need to make requests to the Facebook API through your application. For the first part of this tutorial, we won’t make any requests because our app is just a simple static html page with a “Hello World”.

Configure your app settings

Now you have to configure the application settings, and specify the url of your content. Select the “Page Tab” option and fill in the form with your app information, as shown below.

p03

The app name will be shown as the Tab Name in your fan page (right bellow the Tab Image thumbnail), and also in the header of the application inside Facebook. However, you can change the Tab Name and the Tab Thumbnail directly at the Fan Page, there’s no need to edit the app settings for this.

Don’t forget to check the “Wide (810px)” option for the Page Tab Width.

Note about https (secure page tab url)

It’s not mandatory for your app to have a secure url – if you skip this, your app will run as expected for all users accessing Facebook via normal http – the usual way. But users who are accessing FB via https (secure browsing) will not be able to access your application.

Now, if your web server has ssl enabled and https is working fine (just try to access the same url using https instead of http), you can set this field (secure page tab url) to https://whateverisyourappurl . However, if you don’t own an SSL certificate issued by a reliable entity, users will get something like this when trying to access your application / page tab:

error_chrome

Note that this is not Facebook’s fault. It’s a “security care” from browsers.

I couldn’t find any research about how many users are accessing Facebook via https nowadays. So, if you want to create a big app or some “serious stuff”, I recommend you to buy an SSL certificate. After creating your application, you can try a 90-day trial ssl certificate from Comodo for free, and check if it suits your needs. I recently bought a really cheap ssl certificate (for only one subdomain) also from Comodo and its working pretty good.

Now let’s move on to the next step – add the application to your FanPage. Now we’ll need that App ID we talked about after creating the app.

You just need the link bellow – changing, of course, “YOUR_APP_ID” to whatever is your App ID, and “YOUR_URL” to your page tab app url (the same you entered when setting up the application).

http://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_URL

For our example app, the url is: http://www.facebook.com/dialog/pagetab?app_id=280648832010374&next=http://entrebits.com.br/helloface.html

When accessing this url, you will be prompted to choose in which FanPage you want to add the application as a Tab. You must be one of the FanPage’s administrators to do so.

After choosing, access your FanPage to see the result:

beabc9c35d20120330095922

If you want to show selective content only for followers on your fanpage, you should see this post: How to selectively show content for followers on Facebook Page Tabs

Url Rewriting – user friendly and professional url structure for your website

Its not only a SEO and user friendly functionality; Url Rewriting techniques are also a good approach to make your website safer. By using Url Rewriting, you will be hiding your script extensions and website paths, avoiding sql injection hacks.

As we are talking about PHP here, this is implemented with the mod_rewrite directive on Apache. This extension is available by default in almost any hosting service, ready for you to use it in your website.

WordPress and other CMS’s are ready to use url rewriting, and you just need to enable the option on control panel. But when you are dealing with a custom CMS, for example, you will need to make your own url rewriting structure. There are two paths for accomplishing that: using a rule on .htaccess for every single url on your website – which is impracticable, but sometimes needed for some inherited urls and scripts that you can’t change; and by using a generic rule with an intelligent website structure, as used in WordPress CMS.

On this post you will learn a practical way for implementing url rewriting on your website with this generic single-rule model.

mod_rewrite and .htaccess

Before going any further, you need to understand how url rewriting schema works. We need to establish rules on the .htaccess file, which is situated on the www directory root (you can also use a separated .htaccess file in any subdirectory, establishing rules specific for that directory).  The rules are defined using regular expressions. The image below explains how the request is processed by Apache and PHP. The first request doesn’t uses rewriting, and just by looking at the url you will say “I see what you did here, developer…”. The second request uses url rewriting, letting you think that its just a regular html file.

url-rewriting

Now lets see a functional example. Lets assume we have a directory structure like this on our www folder: “abc/def/ghi” (accessing it via http, the url would be http://mysite.com/abc/def/ghi ). So we would like that the files on this folder could be accessed in a simpler path: /xyz . In other words, rather than using the url http://mysite.com/abc/def/file.html, I want to use: http://mysite.com/xyz/file.html (and this “xyz” directory actually doesn’t exists).

Our .htaccess file would be like this:

RewriteEngine On

RewriteBase   /

RewriteRule  ^/xyz(.*) /abc/def/ghi$1

For more details about all the possible rules, and what each item means, its good to have a look on the Apache’s mod_rewrite documentation:   http://httpd.apache.org/docs/current/mod/mod_rewrite.html . This link also has good basic tips: http://php.refulz.com/201105/url-rewriting-with-apache/ .

First Step – .htaccess

As we talked before, we can use use a lot of rules in our htaccess, but the simplest and most elegant way for working with url rewriting is by using a generic rule and a controller (php) which will manage the requests and grab the right page for that request. The content bellow is the .htaccess file used by WordPress, the same we will be using for our example:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Basically, this .htaccess specifies that: every request, having “/” as base, which is not a existing file or directory, shall be passed to /index.php file. This file will be responsible for treating all requests, any way it wants. A controller.

Remember two things:

  • Existing directories will not be affected. Example: If you have a “blog” directory you will not be able to have a rewriting like “/blog” for a script.
  • You have to take care of 404 errors, because as you are getting all requests for files and dirs that don’t exist, the “404″ error will not happen anymore. Everything will come to index.php and you have to deal with “not found” requests on your controller – just like WordPress does.

Step 2 – PHP Controller and Directory Structure

The file bellow will be our controller, responsible for taking care of all requests. On this example, will make this through includes.

As you can see, the logic is very simple. A request to “/contact” , for example, will check if there’s a module called contact – this is done by checking if there’s a “modules/contato/index.php” or “modules/contato.php” file.

It’s important to check if the file exists before including it – only this way is possible to know if we must send the user to a “404″ error.

For adding a new page on your website, you will need to create a file (or directory, and then an index.php file inside it) inside the “modules” directory,  and the script will be immediately accessible via http://yoursite.com/yournewmodule - easy as that. A folder with “yournewmodule” cannot exists on the root directory, worth remembering.

That “modules/yournewmodule.php” file will be a controller in an MVC environment. You can do your stuff there and show a template file, for example.

If you want submodules, like “mysite.com/about/company”, you shall check for that $path array, which will contains all the “pieces” of the request. Just make a switch and you are ready to go. Its important to make this $path variable available on all script scope.

Bellow is how our directory structure would be:

/
/includes
   /includes/config.php
/modules
   /contato.php
   /404.php
/.htaccess
/index.php

Starting from here, you can construct a good framework for your php web applications. Good luck ;)