duanjian4150 2015-04-09 11:45
浏览 47
已采纳

从标题更改为随机数

I have this code that should rename images. It takes the title of the site and generates a name but if there is no title it just keeps the old name.

How can i make it so that instead of the title it just randoms the number insteed? so instead of "title.extension" it will be randomnumber.jpg ?

            $tmp = download_url( $img );

            preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $img, $matches);

            $newfn = str_replace(array("%2B", "%52", "%20", "%5"), "B", basename($matches[0]));

            $oofnm = basename($matches[0]);

            if($newfn != $oofnm) {              

                $newfn2 = str_replace(array(".jpg", ".png", ".gif"), "", $newfn);

                $tmppath = pathinfo( $tmp );                                                        // extract path parts
                $newpth = $tmppath['dirname'] . "/". $newfn2 . "." . $tmppath['extension'];   

                rename($tmp, $newpth);                                                                 // renames temp file on server
                $tmp = $newpth;                 
            }

            $file_array['name'] = $newfn;
            $file_array['tmp_name'] = $tmp;

            // If error storing temporarily, unlink
            if ( is_wp_error( $tmp ) ) {
                @unlink($file_array['tmp_name']);
                $file_array['tmp_name'] = '';
                continue;
            }
  • 写回答

1条回答 默认 最新

  • dtfbj24048 2015-04-09 11:49
    关注

    Just drop all unnecessary:

    $path_parts = pathinfo($matches[0]);
    $file_array['name'] = rand(0,time()/1000) . "." . $path_parts['extension'];
    

    I am not sure why you are using time()/1000 as upper bound for rand function. I would rather use rand with fixed min and max args or even use more advanced mt_rand function.

    But I would recommend you to use uniqid() function for unique file to generate unique file identifiers:

    $file_array['name'] = uniqid() . "." . $path_parts['extension'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错