2017-01-02 75 views
1

我正在創建網站。我這樣做,當你上傳一個新的配置文件圖片,它會重命名爲用戶ID。我怎麼做?它的配置文件圖片。所以我可以讓用戶圖像和上傳工作比他們做得更好。驗證碼:將文件重命名爲ID

<?php 
require_once('connection.php'); 
require_once('auth.php'); 
$id=$_SESSION['SESS_MEMBER_ID']; 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$uploadOk = 1; 
$temp = explode($_FILES["file"]["name"]); 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 
if(isset($_POST["submit"])) { 
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
    if($check !== false) { 
     echo "File is an image - " . $check["mime"] . "."; 
     $uploadOk = 1; 
    } else { 
     echo "File is not an image."; 
     $uploadOk = 0; 
    } 
} 
// Check if file already exists 
if (file_exists($target_file)) { 
    echo "Sorry, file already exists."; 
    $uploadOk = 0; 
} 
// Check file size 
if ($_FILES["fileToUpload"]["size"] > 500000) { 
    echo "Sorry, your file is too large."; 
    $uploadOk = 0; 
} 
// Allow certain file formats 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
&& $imageFileType != "gif") { 
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
    $uploadOk = 0; 
} 
// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) { 
    echo "Sorry, your file was not uploaded."; 
// if everything is ok, try to upload file 
} else { 
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file . $id.".".$temp)) { 
     echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 
} 
?> 
<?php 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "UPDATE users SET picture='uploads/$id' WHERE mem_id='$id'"; 

if ($conn->query($sql) === TRUE) { 
    echo "Record updated successfully"; 
} else { 
    echo "Error updating record: " . $conn->error; 
} 

$conn->close(); 
?> 
+1

看起來你已經是用' $ target_file。的$ id。 「」 $ temp'。什麼不工作? – ceejayoz

+0

說我上傳了一個名爲doggo.png的文件,它將它重命名爲doggo.png4array – Moo06

+1

因爲'$ temp'是數組! –

回答

0

我想用爆炸的方式是不正確的:

$temp = explode(".", $_FILES["file"]["name"]); 

,然後將文件擴展名爲end($temp)

$newfilename = $id . '.' . end($temp); // e.g. "png" 

move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir . $id.".".$newfilename)