简体   繁体   English

如何在图片上传PHP上添加随机名称

[英]How to add random name on image upload PHP

I'm having trouble adding random numbers or characters on my image uploads to avoid uploads with the same name. 我在为图片上传添加随机数或字符时遇到麻烦,以避免上传具有相同名称的图片。

I found the following, but can't get it to work: 我发现了以下内容,但无法正常工作:

https://www.sitepoint.com/community/t/adding-generated-random-number-to-image-name-before-upload/25950 https://www.sitepoint.com/community/t/adding-generated-random-number-to-image-name-before-upload/25950

This part of the code works: 代码的这一部分工作:

// get the file name
$uploadpath = $uploadpath= $random1 . basename( $_FILES['fileup']['name']);       

But the file is not in uploaded in the directory. 但是文件不在目录中。

Here is the full code: 这是完整的代码:

<?php
header("index.php");
// Simple PHP Upload Script:  http://coursesweb.net/php-mysql/
$output = ''; // Make a variable for output
$uploadpath = 'uploads/';      // directory to store the uploaded files
$max_size = 5000;          // maximum file size, in KiloBytes
$alwidth = 1920;            // maximum allowed width, in pixels
$alheight = 1080;           // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png');        // allowed extensions

if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
  $uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);       // gets the file name
  $sepext = explode('.', strtolower($_FILES['fileup']['name']));
  $type = end($sepext);       // gets extension
  list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);     // gets image width and height
  $err = '';         // to store the errors

  // Checks if the file has allowed type, size, width and height (for images)
  if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
  if($_FILES['fileup']['size'] > $max_size*5000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
  if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;

  // If no errors, upload the image, else, output the errors
  if($err == '') {
    if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) { 
      $output .= '<br>Direct Link: <input type="text" value="http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath.'">';
      $output .= '<br>BB Code: <input type="text" value="[img]'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath.'[/img]">';
    }
    else $output .= '<b>Unable to upload the file.</b>';
  }
  else $output .= $err;
}
?> 
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <!--[if IE]>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <![endif]-->
    <title>SendIT / Free image Upload</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--style sheets-->
    <link rel="stylesheet" href="css/filoxenia.css">
    <link rel="stylesheet" href="css/magnific-popup.css">
    <link rel="stylesheet" href="css/custom.css">
    <script src="js/vendor/custom.modernizr.js"></script>
    <style>
  .wrap{
    width: 700px;
    margin: 10px auto;
    padding: 10px 15px;
    background: white;
    border: 2px solid #DBDBDB;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    text-align: center;
    overflow: hidden;
  }
  #preview {
    color: red;
  }
  #preview img{
    margin-top: 30px;
    max-width: 100%;
    border: 0;
    border-radius: 3px;
    -webkit-box-shadow: 0px 2px 7px 0px rgba(0, 0, 0, .27);
    box-shadow: 0px 2px 7px 0px rgba(0, 0, 0, .27);
    overflow: hidden;
  }
  input[type="submit"]{
    background-color: red;
    border: 0;
    color: white;
    font-weight: bold;
    font-style: italic;
    padding: 6px 15px 5px;
    cursor: pointer;
  }
  </style>  
</head>

<body>
    <header class="contain-to-grid">
        <div class="row">
            <div class="large-12 column">
                <nav id="menu" class="top-bar">

                    <ul class="title-area">
                        <li class="name">
                            <a href="index.php">
                                <img src="images/logo.png" alt="logo">
                            </a>
                        </li>
                        <li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a>
                        </li>
                    </ul>

                    <section class="top-bar-section">
                        <ul class="right">
                            <li><a href="index.php">Home</a>
                            </li>
                            <li><a href="features.html">PLANS &amp; PRICING</a>
                            </li>
                            <li><a href="terms.html">Terms</a>
                            </li>
                            <li id="signup"><a href="login.php" class="button no-margin">Login</a>
                            </li>
                        </ul>
                    </section>
                </nav>
            </div>
        </div>
    </header>

    <section id="main" role="main">

        <div class="breadcrumb-container">
            <div class="row">
                <div class="large-12 column">
                    <nav class="breadcrumbs animated bounceInDown">
                        <a href="index.html">Home</a>
                        <a class="current" href="#">Upload</a>
                    </nav>
                </div>
            </div>
        </div>

        <section class="part">

<div class="wrap">
  <p>Valid formats: jpeg, gif, png, Max upload: 4mb (Free Users)</p>
  <!-- simple file uploading form -->
  <form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
    <input type="file" accept="image/*" name="fileup" />
    <input id="button" type="submit" value="Upload">
  </form>
  <p><?php echo $output;?></p>
</div><!--wrap-->




            <div id="space"></div>
        </section>

    </section>
    <style>
    #space {
      padding-top: 450px;
    }
    </style>

    <a id="back-top" href="#"><i class="icon-caret-up"></i></a>

    <footer>
        <div class="row">
            <p class="small-12 large-4 large-uncentered column copyright">
                Copyright &copy; 2015 SendIT All Rights Reserved.
            </p>

            <p class="small-12 large-8 column social">
                <a href="mailto:info@filoxenia.com"><i class="icon-envelope"></i></a>
                <a href="#"><i class="icon-rss"></i></a>
                <a href="//www.facebook.com" target="_blank"><i class="icon-facebook"></i></a>
                <a href="//www.twitter.com" target="_blank"><i class="icon-twitter"></i></a>
                <a href="//www.google.com/plus" target="_blank"><i class="icon-google-plus"></i></a>
                <a href="//www.linkedin.com" target="_blank"><i class="icon-linkedin"></i></a>
                <a href="skype:echo123?call" target="_blank"><i class="icon-skype"></i></a>
            </p>
        </div>

    </footer>

    <!-- Javascript -->
    <!-- jQuery Library-->
    <script type="text/javascript" src="js/vendor/jquery.form.js"></script>
    <script type="text/javascript" src="js/vendor/script.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    <script src="js/vendor/jquery.magnific-popup.js"></script>
    <script src="js/foundation/foundation.js"></script>
    <script src="js/foundation/foundation.topbar.js"></script>
    <script src="js/foundation/foundation.section.js"></script>
    <script src="js/filoxenia.js"></script>
    <script src="js/custom.js"></script>
</body>

</html>

You can add time to your image name. 您可以为图像名称添加时间。

$img = basename($_FILES['fileup']['name']); //Get here extension from image
$result = expload('.',$img);
$uploadpath= result[0].date('dmY').'_'.time().'.'.$result[1];   

the best way to do this is probably $uploadpath=tempnam($dir,$prefix); 最好的方法可能是$ uploadpath = tempnam($ dir,$ prefix); with rename();, it guarantee a unique name and give no chance for a multi-threading/multi-process collision when several images is being uploaded at the same time. 使用rename();,它可以保证唯一的名称,并且当同时上传多个图像时,不会发生多线程/多进程冲突。

edit: or, i suggest just giving id number filenames on your filesystem, and store the real names in a database (like SQLite or MySQL), this will protect weird characters from the limitations of your filesystem. 编辑:或者,我建议仅在文件系统上提供ID号文件名,并将真实名称存储在数据库中(例如SQLite或MySQL),这将保护怪异的字符免受文件系统的限制。 for instance, files with / or \\ or chinese characters in the name. 例如,名称中带有/或\\或汉字的文件。 you can get the number from an AUTOINCREMENT PRIMARY id field, which will also guarantee no collision 您可以从AUTOINCREMENT PRIMARY id字段中获取数字,这也将确保不会发生冲突

I use following code to rename the image while uploading and it work properly for me 我在上传时使用以下代码重命名图片,它对我来说正常工作

   $ext = substr(strrchr($_FILES['userfile']['name'], "."), 1);//get extension of uploading imagge
   $new_name = md5(rand() * time()) . ".$ext"; //rename the image

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM