簡體   English   中英

如何在圖片上傳PHP上添加隨機名稱

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

我在為圖片上傳添加隨機數或字符時遇到麻煩,以避免上傳具有相同名稱的圖片。

我發現了以下內容,但無法正常工作:

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

代碼的這一部分工作:

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

但是文件不在目錄中。

這是完整的代碼:

<?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>

您可以為圖像名稱添加時間。

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

最好的方法可能是$ uploadpath = tempnam($ dir,$ prefix); 使用rename();,它可以保證唯一的名稱,並且當同時上傳多個圖像時,不會發生多線程/多進程沖突。

編輯:或者,我建議僅在文件系統上提供ID號文件名,並將真實名稱存儲在數據庫中(例如SQLite或MySQL),這將保護怪異的字符免受文件系統的限制。 例如,名稱中帶有/或\\或漢字的文件。 您可以從AUTOINCREMENT PRIMARY id字段中獲取數字,這也將確保不會發生沖突

我在上傳時使用以下代碼重命名圖片,它對我來說正常工作

   $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