Hi, so im reading the password_hash() docs and wondering what the 'cost' is for?

Dani AI

Generated

Short answer for : cost is the work factor for the hash function — it controls how expensive (CPU/time) creating a hash is. For password_hash() with PASSWORD_BCRYPT the cost option increases the number of internal rounds (making hashing slower and therefore harder for attackers). See the PHP manual for details: PHP manual: password_hash.

Important details and practical guidance:

  • Bcrypt’s cost is exponential: increasing the cost by 1 roughly doubles the CPU work (bcrypt uses a 2^cost relationship for rounds). That is why small increases have large effects on time and attacker cost (bcrypt — Wikipedia).
  • Choose the highest cost your production servers can tolerate for an acceptable login delay (common targets are in the 100–250 ms range). Measure on your real hardware and under realistic load; don’t rely on defaults from a different machine.
  • Use a short benchmark to pick a value, then store hashes normally. When you raise the cost later, detect and rehash old hashes with password_needs_rehash() (PHP provides this): PHP manual: password_needs_rehash.

Example benchmark (run on your server to decide a cost):

<?php
for ($cost = 8; $cost <= 16; $cost++) {
    $t1 = microtime(true);
    password_hash('test-password', PASSWORD_BCRYPT, ['cost' => $cost]);
    $t2 = microtime(true);
    printf("cost=%d time=%.0f ms\n", $cost, ($t2 - $t1) * 1000);
}

Cautions: higher cost raises CPU usage and can affect throughput or open a DoS vector under high login load — combine a sensible cost with rate-limiting and other protections. If available, consider Argon2 for modern, tunable memory/time cost options.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.