All posts by Bruno Amaral

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 http://ipod.about.com/cs/qt.htm

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 http://ipod.about.com/cs/qt.htm

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;

Examples

  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

Or

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.

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
    set_time_limit(0);

  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’)
    exit;

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.

Clean file name in PHP with Regular Expressions

In Web developing there are some main features and many concerns that we all must be aware. The file uploading is one of the important and indispensible features that we certainly will use sooner or later.

I’m sure that many of you have had troubles when uploading files that have names with special chars, especially if we run our application in a Linux SO. In fact, using Linux we have to be aware of case sensitive names and special chars. In Windows, we usually don’t have this problem and we can name our files without many limitations. This problem has a higher importance in Latin countries like mine (Portugal), here is normal to name files like “Activação Telefónica.doc”.

So, I decided to code a simple function that cleans the file name and post it here to be sure that when I need it again I known were this little simple but useful function is. I use the PHP function preg_replace to replace special chars with standard ones. This is only an example and don’t clean all special chars. You should add more chars to the filter by simple adding more arrays to the cleaner one. See the function bellow:


<?
$txt = "Activação Telefónica.jpg";

function cleanFileName( $str )
{
$cleaner = array();
$cleaner[] = array('expression'=>"/[àáäãâª]/",'replace'=>"a");
$cleaner[] = array('expression'=>"/[èéêë]/",'replace'=>"e");
$cleaner[] = array('expression'=>"/[ìíîï]/",'replace'=>"i");
$cleaner[] = array('expression'=>"/[òóõôö]/",'replace'=>"o");
$cleaner[] = array('expression'=>"/[ùúûü]/",'replace'=>"u");
$cleaner[] = array('expression'=>"/[ñ]/",'replace'=>"n");
$cleaner[] = array('expression'=>"/[ç]/",'replace'=>"c");

$str = strtolower($str);
$ext_point = strripos($str,”.”); // Changed to strripos to avoid issues with ‘.’ Thanks nico.
if ($ext_point===false) return false;
$ext = substr($str,$ext_point,strlen($str));
$str = substr($str,0,$ext_point);

foreach( $cleaner as $cv ) $str = preg_replace($cv[“expression”],$cv[“replace”],$str);

return preg_replace(“/[^a-z0-9-]/”,”_”,$str).$ext;
}

echo cleanFileName( $txt );
?>

I hope that this function will be useful to you.