PHP上传时更改文件名缩略图

时间:2016-07-05 19:36:21

标签: php file-upload file-rename

如果选中单选按钮“thumbnail”,我会在文件名中添加“_thumb”,如果选择“full size”,则不添加它(保持文件名不变)。这适用于我的数据库条目,但不适用于实际文件。我怀疑我以某种方式将“_thumb”添加到两种类型的文件 - thumbnail和fullsize - 因为在我上传到的文件夹中我只看到添加了“_thumb”的文件夹。我无法弄清楚出了什么问题,请帮忙!

到目前为止这是我的php:

<?php
session_start();
if(isset($_POST['category'])) {
$_SESSION['category']=$_POST['category']; }
if(isset($_POST['size'])) {
$_SESSION['size']=$_POST['size']; }
?>
 <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Upload</title>
<style>.thumbnails{height:60px;display:block;}.galery{height:200px;}</style>
</head>

<body>

<?php

$con = mysqli_connect("localhost","Melvin","") or die ("could not connect to server: " . mysqli_connect_error($con));
mysqli_select_db($con, "galerie") or die ("Could not connect to database: " . mysqli_error($con));

if(isset($_POST['submit'])){

$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = '_images/_galerie/';
$target = '_images/_galerie/' .$name;

	if(move_uploaded_file($tmp_name,$location.$name)){
		
		echo "Successfully uploaded";
		
		$nam = $_POST['nam'];
		$category = $_POST['category'];
		$size = $_POST['size'];
		
		if ($size == 'thumb') {
			// add "thumb" between filename and extension 			
			$extension_pos = strrpos($target, '.'); // find position of the last dot, so where the extension starts
			$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);			
			$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$thumb."','$nam','$category','$size')");	
		} else {
			$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$target."','$nam','$category','$size')");	
		}		
		
		function renameImg() {
			$name = $_FILES['file']['name'];
			$target = '_images/_galerie/' .$name;
			$extension_pos = strrpos($target, '.');
			$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
			rename($target, $thumb);
			//echo $name . " replaced with " . $thumb;
		};
		renameImg();
		
	} else {
		
		echo "file not uploaded";
			
	}

}
?>

<div style="margin:20px 0 40px 0;">
    <form action="stack_overflow_upload_2.php" method="POST" enctype="multipart/form-data">    
        Upload: <input type="file" name="file">
        Title: <input type="text" name="nam" value="Image Gallery">
        Category: <select name="category" id="selectCat">
   
            <option value="black" 
			<?php 
			if (isset($_SESSION['category'])) {
				if($_SESSION['category'] == "black"){ 
					echo ' selected'; }}
			?> >black</option>
            <option value="colour" 
			<?php
            if (isset($_SESSION['category'])) {
				if($_SESSION['category'] == "colour"){ 
					echo ' selected'; }}
			?> >colour</option>
        </select>
        
        	<br>           
        	
        <input type="radio" name="size" value="full" id="regularRadio"        
        <?php
        	if(isset($_SESSION['size'])) {
				if($_SESSION['size'] == "full") {
					echo 'checked="checked"	';
				}
			}
		?> >
        <label for="regularRadio">Full size</label>
        <br>        	
        <input type="radio" name="size" value="thumb" id="thumbRadio"
        <?php
        	if(isset($_SESSION['size'])) {
				if($_SESSION['size'] == "thumb") {
					echo 'checked="checked"	';
				}
			}
		?> >
        <label for="thumbRadio">Thumbnail</label>
        <br>
        
        <input type="submit" name="submit">
    </form>
</div>

<?php
$result = mysqli_query($con, "SELECT * FROM images WHERE img_size='thumb'");

while($row = mysqli_fetch_array($result)){	
	echo "<img src=".$row['img_name'] . " &nbsp; class='thumbnails' style='display:inline;float:left;'>";
		
}
?>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

只需在renameImg函数上添加此方法

if(file_exists('_images/_galerie/' .$name))
    rename('_images/_galerie/' .$name, $thumb);

答案 1 :(得分:0)

<?php

$root = null;

// Set the current directory.
// Make sure you set this up so
// that you get out of your own root.
// Assuming this php file is at the root
// of this composer package, this should suffice.
$directory = dirname(__FILE__);

// Go up until you find a composer.json file
// which should exist in the ancestors
// because its a composer package.
do {
    $directory = dirname($directory);
    $composer = $directory . '/composer.json';
    if(file_exists($composer)) $root = $directory;
} while(is_null($root) && $directory != '/');

// We either are at the root or we got lost.
// i.e. a composer.json was nowhere to be found.
if(!is_null($root))
{
    // Yay! we are at the root.
    // and $root contains the path.
    // Do whatever you seem fit!
    bootstrapOrSomething();
}
else
{
    // Oh no! Can we default to something?
    // Or just bail out?
    throw new Exception('Oops, did you require this package via composer?');
}