【问题标题】:How can I prevent a conflict between JSON encode and a unique id generator?如何防止 JSON 编码和唯一 ID 生成器之间的冲突?
【发布时间】:2017-11-14 19:51:53
【问题描述】:

我想在我的数据库中插入一个唯一的 id 并通过 json 编码输出一些文本。像这样我的代码工作正常,我的输出是“hello”:

   $json = array(
        'example' => 'hello',
    );

   echo json_encode($json);

   $uniqueID = "123";

   $pdo = $db->prepare('INSERT INTO example (unique_id) values(:unique_id) ');
    $pdo->execute(array(
        ':unique_id' => $uniqueID,
    )); 

但是当我想生成唯一的 id 时,出现了一些我无法弄清楚的错误:

   $json = array(
        'example' => 'hello',
    );

   echo json_encode($json);

   $random_id_length = 10; 
   $uniqueID = crypt(uniqid(rand(),1)); 
   $uniqueID = strip_tags(stripslashes($uniqueID)); 
   $uniqueID = str_replace(".","",$uniqueID); 
   $uniqueID = strrev(str_replace("/","",$uniqueID)); 
   $uniqueID = substr($uniqueID,0,$random_id_length); 

   $pdo = $db->prepare('INSERT INTO example (unique_id) values(:unique_id) ');
    $pdo->execute(array(
        ':unique_id' => $uniqueID,
    )); 

像这样,一切都正确地插入到数据库中。但我没有得到任何输出。

【问题讨论】:

  • 错误信息是什么?
  • 我没有收到任何错误信息,只是一个空白页
  • 但是当我只使用行$uniqueID = crypt(uniqid(rand(),1))时已经引起了错误
  • 你检查过错误日志有什么吗?你说它插入,所以它必须运行执行。按照这个逻辑,它应该已经将 json 打印到屏幕上
  • 好吧,我不熟悉错误日志,但我没有看到任何错误输出

标签: php mysql json


【解决方案1】:

我认为你得到的错误是这样的:

PHP: crypt(): No salt parameter was specified. You must use a randomly generated salt and a strong hash function to produce a secure hash.

来自docs:

盐参数是可选的。然而, crypt() 创建一个没有盐的弱哈希。如果没有它,PHP 5.6 或更高版本会引发 E_NOTICE 错误。确保指定足够强的盐以提高安全性。

docs 也建议使用 password_hash 代替:

password_hash() 使用强哈希,生成强盐,并自动应用适当的轮次。 password_hash() 是一个简单的 crypt() 包装器,并且与现有的密码哈希兼容。鼓励使用 password_hash()。

所以尝试改变:

$uniqueID = crypt(uniqid(rand(),1));

收件人:

$uniqueID = password_hash(uniqid(rand(),1), PASSWORD_DEFAULT);

【讨论】:

  • 我测试过了,可惜还是没有输出
  • 问题正是那一行。当我将其更改为 $uniqueID = uniqid(rand(),1); 时,它起作用了
猜你喜欢
  • 2020-05-16
  • 2014-05-28
  • 2019-05-07
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
相关资源
最近更新 更多