首頁  >  文章  >  後端開發  >  php 上传图片改名

php 上传图片改名

WBOY
WBOY原創
2016-06-23 14:01:571173瀏覽

从网上找了一段上传 图片代码,然后想把上传的图片名改成用户名+图片后缀(用户名为$user,)但是没看懂这段代码,所以不知道怎么弄,请各位指点

$user="hah";$targetFolder = '/uploads'; // Relative to the rootif (!empty($_FILES)) {	$tempFile = $_FILES['userfile']['tmp_name']; //	$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;	$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['userfile']['name'];				$fileTypes = array('jpg','jpeg','gif','png'); // File extensions	$fileParts = pathinfo($_FILES['userfile']['name']);	if (in_array($fileParts['extension'],$fileTypes)) {		$arr = getimagesize($tempFile);         						move_uploaded_file( $tempFile,$targetFile);		$data = array(				"state" => '00',				"desc"  => 	'ok',				"src"   => "http://localhost/uploads/".$_FILES['userfile']['name'],				"touxiang"  => 	$touxiangs,		);						echo json_encode($data);	} else {		echo 'Invalid file type.';	}}


回复讨论(解决方案)

修改第7行
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['userfile']['name'];

$targetFile = $targetPath . '/' . $user . '.' . pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);

<?php	$user="hah";$targetFolder = '/uploads'; // Relative to the rootif (!empty($_FILES)) {	$tempFile = $_FILES['userfile']['tmp_name']; //	$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;			$fileTypes = array('jpg','jpeg','gif','png'); // File extensions	$fileParts = pathinfo($_FILES['userfile']['name']);	$targetFile = rtrim($targetPath,'/') . '/' . $user . '.' .$fileParts['extension'];	if (in_array($fileParts['extension'],$fileTypes)) {		$arr = getimagesize($tempFile);         						move_uploaded_file( $tempFile,$targetFile);		$data = array(				"state" => '00',				"desc"  => 	'ok',				"src"   => "http://localhost/uploads/".$user . '.' .$fileParts['extension'],				"touxiang"  => 	$touxiangs,		);						echo json_encode($data);	} else {		echo 'Invalid file type.';	}}?>

搞定了,多谢

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn