Drupal 7

Warning message

JQuery Cycle must be installed in order to run the slideshow. Please go to Status Report for instructions.

There are many methods to recover admin password described here https://www.drupal.org/node/44164 but this method gives you a admin panel to recover admin username and password.

Please copy and paste the below code in a file and name it whatever you like or download the attachment in this post, remove .txt extension and drop it in root of your website[in same place where you find robots.txt]. In my case i named it as "generate_drupal_admin_pwd.php".

and then access your website like: http://YOUR_WEBSITE_NAME/generate_drupal_admin_pwd.php

Warning: Putting .php files in root directory have many security concerns, its recommended after changing password you should delete the file.

<title>Recover Password</title>

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">

function checkPasswordMatch() {
    var password = $("#txtNewPassword").val();
    var confirmPassword = $("#txtConfirmPassword").val();
    if(password != '' && confirmPassword != '') {
        if (password != confirmPassword)
                $("#divCheckPasswordMatch").html("<div class='pass_dont_match'>Passwords do not match!</div>");
                $("#divCheckPasswordMatch").html("<div class='pass_match'>Passwords match.</div>");

$(document).ready(function () {

html { height: 100% }
::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; }
::selection { background: #fe57a1; color: #fff; text-shadow: none; }
body { background-image: radial-gradient( cover, rgba(92,100,111,1) 0%,rgba(31,35,40,1) 100%), url('http://i.minus.com/io97fW9I0NqJq.png') }
.login {
  background: #eceeee;
  border: 1px solid #42464b;
  border-radius: 6px;
  height: 330px;
  margin: 20px auto 0;
  width: 298px;
  margin-top: 50px;
.login h1 {
  background-image: linear-gradient(top, #f1f3f3, #d4dae0);
  border-bottom: 1px solid #a6abaf;
  border-radius: 6px 6px 0 0;
  box-sizing: border-box;
  color: #727678;
  display: block;
  height: 43px;
  font: 600 14px/1 'Open Sans', sans-serif;
  padding-top: 14px;
  margin: 0;
  text-align: center;
  text-shadow: 0 -1px 0 rgba(0,0,0,0.2), 0 1px 0 #fff;
input[type="password"], input[type="text"] {
  background: url('http://i.minus.com/ibhqW9Buanohx2.png') center left no-repeat, linear-gradient(top, #d6d7d7, #dee0e0);
  border: 1px solid #a1a3a3;
  border-radius: 4px;
  box-shadow: 0 1px #fff;
  box-sizing: border-box;
  color: #696969;
  height: 39px;
  margin: 9px 0 9px 29px;
  padding-left: 37px;
  transition: box-shadow 0.3s;
  width: 240px;
    padding-left: 33px;

  margin-top: 53px;
input[type="password"]:focus, input[type="text"]:focus {
  box-shadow: 0 0 4px 1px rgba(55, 166, 155, 0.3);
  outline: 0;
.show-password {
  display: block;
  height: 16px;
  margin: 26px 0 0 28px;
  width: 87px;
input[type="checkbox"] {
  cursor: pointer;
  height: 16px;
  opacity: 0;
  position: relative;
  width: 64px;
input[type="checkbox"]:checked {
  left: 29px;
  width: 58px;
.toggle {
  background: url(http://i.minus.com/ibitS19pe8PVX6.png) no-repeat;
  display: block;
  height: 16px;
  margin-top: -20px;
  width: 87px;
  z-index: -1;
input[type="checkbox"]:checked + .toggle { background-position: 0 -16px }
.forgot {
  color: #7f7f7f;
  display: inline-block;
  float: right;
  font: 12px/1 sans-serif;
  left: -19px;
  position: relative;
  text-decoration: none;
  top: 5px;
  transition: color .4s;
.forgot:hover { color: #3b3b3b }
input[type="submit"] {
  font-family:Arial, "Helvetica", sans-serif;
  text-shadow:1px 1px 0px #37a69b;
  margin: 29px 0 0 29px;
  border: none;
  background-color: #37a69b;
  background-image: linear-gradient(top,#3db0a6,#3111);
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  box-shadow: inset 0px 1px 0px #2ab7ec, 0px 5px 0px 0px #497a78, 0px 10px 5px #999;

.shadow {
  background: #000;
  border-radius: 12px 12px 4px 4px;
  box-shadow: 0 0 20px 10px #000;
  height: 12px;
  margin: 30px auto;
  opacity: 0.2;
  width: 270px;

input[type="submit"]:active {
  box-shadow: inset 0px 1px 0px #2ab7ec, 0px 2px 0px 0px #31524d, 0px 5px 3px #999;

.pass_match {
  padding-left: 96px;
  padding-top: 8px;
  color: darkgreen;

.pass_dont_match {
  padding-left: 65px;
  padding-top: 8px;
  color: red;

.pass_changed {
  margin-left: 777px;
  color: green;
.mainloginarea {
margin-top: 250px;


 define('DRUPAL_ROOT', getcwd()); //the most important line
require_once './includes/bootstrap.inc';
DRUPAL_ROOT . '/includes/password.inc';
$admin_name = db_query("SELECT name from {users} WHERE uid = :uid", array(":uid" => 1))->fetchField();

if((!empty($_POST['txtNewPassword'])) && (!empty($_POST['txtConfirmPassword']))) {
$_POST['txtNewPassword'] === $_POST['txtConfirmPassword']) {
$newpwd = $_POST['txtNewPassword'];
$hashed_pass user_hash_password($newpwd);
$updated = db_update('users') // Table name no longer needs {}
'pass' => $hashed_pass,
condition('uid', 1, '=')
'Admin password changed',

<div class = "mainloginarea">
<h1 align = "center">Drupal Admin Password Changer</h1>
      <div class="login">
           <form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <div class = "admin_username"> Admin Username:<b><?php echo $admin_name ?></b></div><br />
        <input placeholder= "Enter Password" name="txtNewPassword" type="password" id="txtNewPassword">
        <input placeholder = "Re-Enter Password" name="txtConfirmPassword"  type="password" id="txtConfirmPassword">

                <div class="registrationFormAlert" id="divCheckPasswordMatch">
        <input type="submit" value="Submit">
<div class="shadow"></div>
<?php if($updated) print "<div class=pass_changed>Thank You! Password Changed. <a href= $base_url/user>Click Here<a/> to login</div>"; ?>

Drupal admin password changer panel

Sometimes you need to show page to anonymous user. Create a page using hook_menu by using below code:

  $items['your/path/name'] = array(
    'title' => 'You Title',
    'description' => 'Your Page Description',
    'page callback' => '_any_function_if_you_want_to_call',
    //'access arguments' => TRUE, <-- Comment or remove this if you have it
    'access callback' => TRUE,  <-- Add this
    'page arguments' => array(2), // Optional if you are receiving any arguments from URL
    'type' => MENU_NORMAL_ITEM,

In Drupal, when you add exposed filters, it defaults to first word of your select list. But if you want to show all the results on page load then you have to set the exposed filters to "Any" option by default.

To do this:

Add a filter and Expose filter to visitors.

Choose Single filter, give it a label, choose "Is one of" under Operator, and have no terms selected/highlighted in the "Select terms from vocabulary" box. The only option checked under the vocab box is "Display error message."

TIP: CTRL- or CMD-click to unselect the items in the box.

Settings file protection by password encryption

Settings.php was criticized for storing the plain text MySQL username and password. This procedure will let us remove the username and password from the settings.php and let us put that credentials outside of the website directory and store into another folder which can be taken care by security team or server managing people.

To do this, include a line at the top of settings.php file:

require_once '../secure_mysite/secure_credentials.php';

This line specify that include a script called “secure_credentials.php” and if it’s not found, stop the script from further running. For now, we have created a secure folder called “dbpw” which we have stored outside of website directory. We stored our php script into this folder and call that script using above line inside settings.php.
This secure_credentials.php contain two function i.e. one for encryption and one for decryption.


function encrypt_credentials($username, $password, $encrypted_key = NULL, $iv = NULL) {
  $method = "AES-256-CBC";
  $password_file = "/www/htdocs/secure_mysite/pass.txt";
  $key_file = "/www/htdocs/secure_mysite/key.txt";
  $wasItSecure = true;
  $ivlen = openssl_cipher_iv_length($method);
  $iv = openssl_random_pseudo_bytes($ivlen, $wasItSecure);

  if (!file_exists($key_file)) {
  	if(!$fh = fopen($key_file, "w")) { die("

Could Not Open Key File"); } $encrypted_key = openssl_random_pseudo_bytes(32); $result = fwrite($fh, $encrypted_key); fclose($fh); } $encrypted_data = openssl_encrypt($password, $method, $encrypted_key, 0, $iv); //create a file handler by opening the file if(!$fh = fopen($password_file, "w")) { die("

Could Not Open Password File"); } $txt = $username . ":" . $encrypted_data . ":" . $iv; $result = fwrite($fh, $txt); if($result) echo "Username and Password successfully encrypted and stored\n"; fclose($fh); } function decrypt_credentials($param) { $password_file = "/www/htdocs/secure_mysite/pass.txt"; $key_file = "/www/htdocs/secure_mysite/key.txt"; $method = "AES-256-CBC"; $filecontents = file_get_contents($key_file); $all_words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY); if(!$fh = fopen($password_file, "r")) { die("

Could Not Open Password File"); } while(!feof($fh)) { $line = fgets($fh, 4096); $from_file = explode(":", $line); } $decrypted_pass = openssl_decrypt($from_file[1], $method, $all_words[0], 0, $from_file[2]); fclose($fh); return ($param == 'username') ? $from_file[0] : $decrypted_pass; }

Encryption Function:

function encrypt_credentials($username, $password, $rand_pass = NULL, $iv = NULL) {}

This function takes 4 parameters in which 2 are optional, but username and password is required. This function used AES-256-CBC encryption method to encrypt the password. To use the encryption properly I have used:

string openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [,string $iv = "" ]] )

For making this script more automatic and independent I have generated 3rd argument $encrypted_key in above function by using an inbuilt function openssl_random_pseudo_bytes(). This key will be stored in a separate key file called “key.txt”. The key will be generated only once when the program runs first time. If you want to generate a new or different key you have to delete key.txt file. The openssl_encrypt() function require one more parameter which is “iv” (initialization vector) as the 5h parameter. The “iv” is generated automatically in this script by PHP inbuilt function openssl_random_pseudo_bytes(). Then all these parameters passed into openssl_encrypt() function to generate the encrypted data. The generated data will be stored inside “pass.txt” file. This text file contain 3 parameters as well which are separated by “:” parameter.
Username: Encrypted Data: IV

To run the above function we need to run this command by CD into the folder and then run the command from the command line:

 php -r 'require "secure_credentials.php";encrypt_credentials("superman", "makeitsecure!#2");' 

Where superman is example of username and makeitsecure!#2 is the password.

You will only need to run this command with username and password. With this command it will call the encrypt_credentials() function inside the secure_credentials.php file and store the results in pass.txt file. File pass.txt will look something like this:

 superman:cmWK+ymPjL7vB5v4+FM39A==:°ß™™ÊÏ s߈ÜÄVë 

When the settings file will run it will call the decrypt function.
The two statements inside the settings file will call the decrypt function in the secure_credentials.php file.

$databases = array (
  'default' => 
  array (
    'default' => 
    array (
      'database' => 'yourdb',
      'username' => decrypt_credentials('username'), //Note this statement
      'password' => decrypt_credentials('password'), //Note this statement
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',

When this function is called, it looks for the pass.txt, opens it and decrypt the password and send the password in the decrypted format to the Drupal back again.
By above process we are not storing the plain password anywhere and the password will be only known by the Person who will run the command line function. If he forgots the password, this command line function needs to be run once again.

You can use two solutions for this but avoiding the 2nd solution with arg() function is better according to Drupal docs. You should arg() function wherever possible because resulting code is hard to read.

1) Use menu_get_object function

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  // User is on a taxonomy term page

2) Use arg() function

if (arg(0) ==  "taxonomy" && arg(1) == "term" && is_numeric(arg(2)) && arg(3) == "") {
  // Taxonomy term page

If you want to add small JS without creating a new JS file, you can create a module and put the below code in your custom .module file.

  '(function ($) {
// You can write here anything you like to perform. 
 alert("this is test"); })(jQuery);',
    'type' => 'inline',
    'scope' => 'footer',
    'group' => JS_THEME,
    'weight' => 5,

Here is the example function of inner join usage in Drupal 7. In this example we are fetching first and last name from database which we have already added in user entity.

 $matches = array();
 $select = db_select('users', 'u');
// Create inner join on table field_data_field_first_name
 $select->innerjoin('field_data_field_first_name', 'fn', 'fn.entity_id = u.uid'); 
// Create inner join on table field_data_field_last_name
 $select->innerjoin('field_data_field_last_name', 'ln', 'ln.entity_id = u.uid');  
 $select->fields('u', array('uid', 'name'))
           ->fields('fn', array('field_first_name_value'))
           ->fields('ln', array('field_last_name_value'))
           ->condition('status', 1)
           ->condition('field_first_name_value', '%' . db_like(check_plain($string . '')) . '%', 'LIKE')
           ->range(0, 10);

 $result = $select->execute()->fetchAllAssoc('uid');

    foreach ($result as $patron) {
      if (isset($patron->field_first_name_value) && isset($patron->uid)) {
        $matches[$patron->field_first_name_value . '-' . $patron->field_last_name_value . ' [uid:' . $patron->uid . ']'] = check_plain($patron->field_first_name_value) . '-' . check_plain($patron->field_last_name_value);

Drupal 7 views 3 are designed to work on exposed filters, if and only if you use AJAX in your views block. That means you have to enable 
Use AJAX: YES  in you advanced section of Drupal views.

This error occurs usually during a file upload and when you try to check the Drupal logs you will find error something like this -
"PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 2: INSERT INTO {file_managed}."

Usually if you remove the white spaces from your filename which you are uploading will solve this error . So for example if you have a filename like "tech rappers.jpg" then try changing the filename to "techrappers.jpg" or tech-rappers.jpg" will solve this error.

Alternatively, you can use the below module also :


To resolve this error you must wrap your JavaScript inside function like this :

(function ($) { 
  // Your jQuery code.
  $('#something1').click(function () {
  //Put your code between these comments.


Subscribe to RSS - Drupal 7