Generate random string in PHP

if ( ! function_exists( 'generate_random_string' ) ) {
	/*
	 * Generates random string
	 */
	function generate_random_string( $length, $do_include_uppercase = true, $do_include_numbers = true ) {
		// Form available characters string
		$chars = 'abcdefghijklmnopqrstuvwxyz';
		if ( $do_include_uppercase ) {
			$chars .= strtoupper( $chars );
		}
		if ( $do_include_numbers ) {
			$chars .= '0123456789';
		}
		$chars_length = strlen( $chars );
		// Generate random string
		$random_string = '';
		for ( $i = 1; $i <= $length; $i++ ) {
			$random_string .= $chars[ rand( 0, $chars_length - 1 ) ];
		}
		return $random_string;
	}
}

No comments yet.

Leave a Reply