Import multiple redirects from file

Hi sometimes we need quickly import a lot of redirects. We can just put file with redirects in format:

source/dummypage,redirect/destination-page

source/dummypage,redirect/destination-page

source/dummypage,redirect/destination-page

Then read line by line and create redirect if it is unique.

We can easilly do all this using code given below.

  /**
 * Import redirects from csv file.
 */
function yourmodule_update_7172() {
  $csvFile = drupal_get_path('module', 'yourmodule') . '/files_404/file_name.csv';
  $file_handle = fopen($csvFile, 'r');
  $count = 1;

  while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);

    if($line_of_text[0] != "" && $line_of_text[1] != "") {
      $redirect = new stdClass();
      redirect_object_prepare($redirect);
      $redirect->source =  $line_of_text[0];
      if(strpos($redirect->source,'?')) {
        $redirect->source = strstr($redirect->source,'?');
      }
      $redirect->redirect =  $line_of_text[1];
      redirect_hash($redirect);
      $already_exists = (int) db_query("SELECT 1 from redirect WHERE hash = :hash", array(':hash' => $redirect->hash))->fetchCol();
      if(!$already_exists) { // hash is set after saved
        redirect_save($redirect);
        if (function_exists('drush_log')) {
            drush_log($count . ' redirect processed from 210', 'success');
            $count++;
         }
      }
    }
  }
  fclose($file_handle);
}