Reboot iPhone when it freezes

Some time ago, my iPhone crashed, freeze and I couldn’t make it reboot. Besides, in the iPhone isn’t easy to remove the battery.

After searching for a solution I found that there is a way to reboot the iPhone, just using a combination. To do it, we need to press two buttons at the same time. One is the awake / sleep button, that can be found on the top left corner and the other one is the front button. After pressing these buttons the iPhone shuts down and then shows the apple.

I hope we don’t have to use the trick many times, but keep it in mind just for the cause it happen.

If you need other troubleshooting for the iPhone visit

Reiniciar o iPhone [pt]

Aparentemente não há forma de forçar um iPhone a reiniciar (reboot). Acontece que, tal como em todos os equipamentos electrónicos, por vezes estes param e deixam de dar resposta aos inputs do exterior (crash).

Na realidade é possível fazer o iPhone reiniciar através da pressão de dois botões ao mesmo tempo. Para reiniciar o iPhone pressione o botão de acordado/suspenso localizado no canto superior direito e o botão de inicio presente no centro do equipamento ao mesmo tempo. Verá o ecrã a ficar branco e quando surgir a maça pode largar os botões.

Bom é não haver a necessidade de usar esta técnica, mas fica aqui a nota para o caso de ser necessário.

Se necessitar de outros truques para o iPhone visite

Using META TAG Refresh to redirect

There are several ways to do a page refresh or redirect it to a new one. It can be done in the client side, with HTML or a script language, or in the server side with PHP or in the server configuration directly. The most simple way is using the HTML to tell to the browser what to do, using a meta tag. Besides, the are many simple hosting services that don’t support server side scripting or don’t let clients to change the servers configuration (in apache this can be done with an .htaccess file).

This feature can be very helpful, besides it’s very easy to use. Imagine that we have a website with several languages organized in a folder structure with the language codes. We’ll need to redirect the visitor to the default language. This can easily be done with meta tag refresh.

META tag syntax

The syntax of the refresh META tag is very simple.

<META http-equiv=”refresh” content=”<time>[;URL=<new url>”]>

  • The time, in seconds, represents the time that the browser will wait before refresh the page or redirect it to another one. If you set it to 0 (zero), the browser will redirect to the page without waiting. This use disable the back button of the browser, it behave like there is no initial page and only the one that we redirect the visitors to;
  • The url is an optional parameter. With this parameter we can define the URL of the page that will be loaded by the browser, this is the page that you want the visitor to redirect;


  1. Using the META tag to refresh or reload the site every one minute (60 seconds)
    <meta http-equiv=”refresh” content=”60″>
  2. Using the META tag to redirect to a new page without waiting.
    <meta http-equiv=”refresh” content=”0;url=en/index.html”>
  3.  Using the META tag to redirect to a new page after 2 minutes (120 seconds).
    <meta http-equiv=”refresh” content=”120;url=en/index.html”>

Things you must be aware

This META tag is an easy way of doing a refresh or a redirect. However, it has some disadvantages.

  • Using this method to redirect a page to another the crawlers, like Google bot, won’t keep your page rank in the new page. To do that you need to send a 301 redirect either with server script or the server configuration;
  • If the time defined in the META tag refresh is too small, some old browser with a slower connection can disable the browsers back button, even if you don’t define 0;
  • The use of the META tag refresh to reload or redirect a page should be done carefully in terms of usability. Some visitors may think that your site can be a security threat or simply be hungry about seeing the page reloads while he is reading it.

If you are developing a website according to the standard XHTML 1.0 you’ve to use the tag like following:

<META http-equiv=”refresh” content=”<time>[;URL=<new url>”] />

Making site backup on Linux

Last week i had to make backup’s of some websites through the Linux shell. I usually don’t have to make server administration and i don’t remember all the linux commands that I needed to do the job, then i decided to make this post for future task guide.

When I say backup a site, i mean backup all files, even the ones that were uploaded or changed by the users, and the database.

My projects are under a version control using subversion, but there are some files that are uploaded or changed by site users and aren’t under version control. So, i need to start by cleaning the site folders removing the folder ‘.svn’ from the folders that are under version control.

First of all, i have to know how to remove a folder and all its contents. To do this i can use the “rm” command:

rm -Rf <folder name>

This command remove the folder and all its contents without asking. To achieve this behavior i set “-R” to remove recursively and “-f” to force the action and to don’t ask anything.

After know how to remove a folder, i need to find the folders to remove, this is all the “.svn”. To do this, i use the find command:

find . -follow -name “.svn” -exec rm -Rf {} \;

With the line above i search the current folder “.” and its subfolders for the folder by its name “-name ‘.svn’”, then i want to remove it ‘-exec rm -Rf {} \;’.

The “-name” is a test option for find that allow us search by the files or folders name with a pattern. This way we can search using something like “-name ‘*.jpg’“. There are several other test options that can search for files by its size, its modification date, by its permission configuration, and other. When using pattern matching it can be used with the following special chars:
*                  Matches 0 or more characters.
?                  Matches 1 character.
[AaBbCc]      Example: matches any 1 char from the list.
[^RGB]          Example: matches any 1 char not in the list.
[a-g]            Example: matches any 1 char from this range.

The “-exec” is an action option that allow the execution of other commands during the search. The command ends when the character ‘;’ is found. The “{}” means he file name that mach the condition defined by the options. The chars might have to be escaped with ‘\’ to protect them from expansion by the shell.

The find command is very complex and have many options. If you want more information check the link below.

Now i have my site folder cleaned and ready to backup. Its time to compress it and turn it in one file. To do this i ZIP the whole folder, e.q. to all its content, files and subfolders:

zip -9 -r <zip file> <folder name>

The option “-9” is used to compress more and the “-r” to do it recursively.

To finish the job i make a backup of the database (see the post Import and export a database in MySQL using Linux shell). If the export file isn’t in the sites folder it can be moved there and zipped with the other files.

mv <file path> <destination path>

Remember that the <destination path> includes the file name, even if it will be the same.

Useful links:

Import and export MySQL database using Linux shell

Usually i use phpMyAdmin to configure, change and import/export my databases. However, recently, one of my databases went so big that it i have some problems to export or import it. The solutions is doing it with the Linux shell.

Linux shell can be very painful but can be the solution either. Using it to import or export MySQL databases can be a better and easier way. With shell we can backup all our databases and download only one file, or we can set up a cron job that do backup according to a defined schedule. Another major advantage is the possibility of import large SQL dump files (the phpMyAdmin has a limit).

In this post i’ll explain out to import or export MySQL databases using mysql and mysqldump respectively.

Import MySQL database

Like i said, using the shell we can import larger files, making easier to restore a database or import it from another MySQL server (easy server migration).

First we have to put the file on the server where it will be accessed. This can be done throw FTP or other method.

When the file is in server, run the following command (replace the italic words by your values):

mysql -u username -ppassword database_name < file_name.sql


mysql -u username -p database_name < file_name.sql

In both ways we define the user, the database and the file that has the data. In the second command, instead of define the password in the command, the password will be prompt later.

Export MySQL database

To export a MySQL database is almost the same. This command can be very helpful for schedule database backups. Use the following command (replace the italic words by your values):

mysqldump -u username -ppassword database_name > file_name.sql

The result of this execution is a file_name.sql file that holds your database information. This backup can them be compressed to be smaller, downloaded or stored somewhere else.

Use Regular Expression in JavaScript

What are Regular Expressions?

Regular Expressions are a powerful and effective way to do searches and replaces in a String. With this feature we can do complex validations in only a few lines of code. However, when dealing with really complex expressions it can be harder to use, specially when we code in different languages, like PHP, JavaScript, ASP.Net, and other.

How to use it on JavaScript?

JavaScript allow us to use Regular Expressions in two different ways. We can do it with a literal expression, or with the RegEx Object. The major difference between this two ways is that with the Object we can change the expression at runtime. However, when we use literal regular expressions we achieve better results, because the literal expressions are compiled at load time and provides better performance.

Using literal declaration:
var re = /protech/i;

Using RegEx Object Constructor:
var re = new RegEx(“protech”,”i”);

In JavaScript we can use regular expression with two different approaches. Using the methods that the String Object provide or the RegEx methods.

RegEx methods:

  • compile – Change the regular expression in runtime
  • exec – Search a string with the regular expression and returns the found values.
  • test – Search a string with the regular expression and returns a boolean true or false indicating if found a match.

String methods:

  • search – Search the String with a regular expression and return the position.
  • match – Search the String with a regular expression and return an array of found values.
  • replace – Replace characters according to the regular expression.
  • split – Split a String according to the regular expression.

In this post i don’t want to explain the regular expression feature neither go much deeper in it’s use in JavaScript. I only want to make reference to the feature and share an interesting experience using it.

Let’s see an example of the use of regular expressions in JavaScript. This code will validate an e-mail in JavaScript using regular expressions. It’s easy to do but has a catch that I’ll show you.

// Three strings to test
var str = “a,”;
var str2 = “”;
var str3 = “a.b”; // These string is for sanity check// Literal declaration of the regular expression

var literal_regexp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i;

// RegEx Object Constructor declaration
var object_regexp = new RegExp(“^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$”,”i”);

// Result of the aplications of regular expressions
alert(; // Writes -1
alert(; // Writes 0
alert(object_regexp.test(str)); // Writes true
alert(object_regexp.exec(str)); // Writes a,,,b,.ws4,.org

alert(; // Writes 0
alert(; // Writes 0
alert(object_regexp.test(str2)); // Writes true
alert(object_regexp.exec(str2)); // Writes,,.ws4,.org

// With different declarations we achieve different results in the first string.

// Lets make a simples change
var object_regexp2 = new RegExp(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i);

// Result of the aplications of regular expressions
alert(; // Writes -1
alert(; // Writes -1
alert(object_regexp2.test(str)); // Writes false
alert(object_regexp2.exec(str)); // Writes null

// As we can see be aware when using RegExp Object that the behavior is not the same.

// Sanity check
var slre = /\./;
var sore = new RegExp(“\.”);
alert(; // Writes 1
alert(; // Writes 0
alert(sore.test(str3)); // Writes true
alert(sore.exec(str3)); // Writes a

Using the RegExp Object, when we try to find a real dot, scaping the dot like we usually do in regular expression, in the String the object assumes like the dot that means, in regular expression, any character

I really don’t know why this happened. If you do please comment this post. However, i think it’s better to use literal declaration.

Like I said, there are many websites explaining regular expressions and it use in JavaScript. Use the following links for further information:

Run Code Igniter scripts as CronScripts

Yesterday I was planing a CronScript to run every night and do some processing tasks. I was coding over Code Igniter (CI) and had my application structured to fit the MVC model.

CronScripts are usually small scripts that do some maintenance to the database, send e-mails, clean cache files, generate reports and other periodic tasks or longer tasks.

After done my script algorithms, I starting thinking how can I get the information from the database. Many of the information that I need from the DB were already done in the models use with CI. However, this models are based in the CI environment and don’t run without it. Other catch is that CI was developed to work over an HTTP connection. So, we need to make a connection, use the TCP stack, check the security, creating access logs and most important for big jobs, deal with timeout issues. In the recent versions of CI, the only thing that really matters is one information from the $_SERVER array. By default the CI uses the PATH_INFO property, but you can configure CI to use REQUEST_ID, to select witch controller and method to run. This way we can easily emulate this information and run a CI script without a browser and an HTTP connection. I also set DOCUMENT_ROOT property emulating a browser and allowing file system manipulation without know the real_path.

In fact, is really easy to run the CI environment from a cronjob or command line. There are some steps you must follow:

  1. Copy the index.php file, that is the file that starts the CI environment, from the DOCUMENT_ROOT and give it a different name. I call it bot.php.
  2. Now you have to do some changes to the copied file in order to execute it from the command line/cronjob. You can start by removing the timeout expiration. This is a really “pain in the ass” when we want to process a lot of data. So, add this line to the top of the file:

    // remove execution timeout

  3. Then you must emulate the browser by setting the value that CI uses to select the contoller/method that it will run. You can do it statically but I did it using an argument, allowing this file to run several scripts. This way you create an entry point from many cronjobs. Just for sanity check, you may had some verifications to the argument passed. This is unnecessary to protect from direct connections to the bot.php file, because when you use CI you have to set mod_rewrite and if you configure it well you will have almost any URL pointing to index.php, but it can be useful for value format mistakes.

    // emulate the browser setting path_info passed by argument
    if (!$argc || $argc!=3 || !eregi(“^([^\\’\”;]*)$”,$argv[1]) || !eregi(“^([a-zA-Z0-9/\\_ -:.]*)$”,$argv[2])) exit;
    $_SERVER[“PATH_INFO”] = $argv[1];

    // emulate browser setting DOCUMENT_ROOT
    $_SERVER[“DOCUMENT_ROOT”] = $argv[2];

  4. In my case, I put the bot.php just besides the index.php. So, I don’t need to change the system_folder variable neither the application_folder one. However, if you put it in an inner folder you must adjust these paths.
  5. Now you are able to use the CI environment resources, the controllers, libraries and models that you want. At this time you may code your controllers and methods and run them as a cronscript from the cronjob/command line. Don’t forget to protect your cronscript controller from connection from a web browser. To do this you must only add the following code to your controller constructor.

    if($_SERVER[’SCRIPT_FILENAME’] != ‘bot.php’)

Now that you can run CI scripts from the command line or from a cronjob that you added to the crontab like following:

# execute cronjob every day at 2am
00 02 * * * /usr/local/bin/php5 $HOME/system/scripts/clean_cache.php

Thanks for user Thoer and Mhort from code igniter Wiki for the great job. Check the CI wiki post.