Problem using the hashid.id library [closed]

0

I'm trying to implement the hashids library in my project, I'm not using composer

My function is simple like this:

function generate_hash_id($id){
    require("../libs/Hashids.php");
    $hashids = new Hashids\Hashids('teste');
    $hash = $hashids->encrypt($id);
    return $hash;
}

But it is returning 500 Internal Server Error

I call the function inside an iterator

for($i = 0; $i < 10, $i++){
    generate_hash_id($i);
}

The structure of my project:

SoIunderstandthatthelibraryisnotinthispath,butthat'sthewayitis!

Followingthetipsof@guilherme,Iremovedtherequirefromwithinfunction.

require("../libs/Hashids.php");

function generate_hash_id($id){
    $hashids = new Hashids\Hashids('teste');
    $hash = $hashids->encrypt($id);
    return $hash;
}

for($i = 0; $i < 10, $i++){
    generate_hash_id($i);
}

Now the error that returns:

  

Fatal error: Uncaught Error: Call to undefined method Hashids \ Hashids :: encrypt () in /usr/share/nginx/www/api/automatic/index.php:16 Stack trace: # 0 / usr / share / nginx / www / api / automatic / index.php (110): generate_hash_id (1) # 1 {main} thrown in /usr/share/nginx/www/api/automatic/index.php on line 16

asked by anonymous 03.10.2016 / 21:15

1 answer

2

When you call the require more than once it will cause an exception error because the function was already declared the first time it called require '../libs/Hashids.php'; , if it calls again (in your case the loop) it goes try to declare again and this is where the error occurs.

500 Internal error server, to correct change require by require_once , else method $hashids->encrypt does not exist, correct is $hashids->encode , see: link

The correct code would be:

function generate_hash_id($id){
    require_once "../libs/Hashids.php";
    $hashids = new Hashids\Hashids('teste');
    $hash = $hashids->encode($id);
    return $hash;
}

For details on how to detect errors and how to use them in production and development mode, read this question and answers:

03.10.2016 / 21:28