當前位置:首頁 » 文件傳輸 » php上傳頭像源碼
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

php上傳頭像源碼

發布時間: 2022-09-23 04:46:38

A. PHP如何實現表單提交時用戶上傳頭像到數據

  • <!DOCTYPE html>

  • <head>

  • <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  • <title>注冊頁面</title>

  • </head>

  • <body>

  • <form action="enteringDb.php" method="post" enctype="multipart/form-data">

  • <table border="1">

  • <tr><th colspan="2">注冊頁面</th></tr>

  • <tr><td>用戶名</td><td><input type="text" name="name" size="30" maxlength="10"/></td></tr>

  • <tr><td>請上傳用戶頭像</td><td><input type="file" name="file" id="file"/></td></tr>

  • <tr><td>

  • <input type="submit" name="submit" value="提交"/>

  • <input type="reset" value="重置"/>

  • </td></tr>

  • </table>

  • </form>

  • </body>

  • </html>

B. 求php文件上傳源碼

<?php
//文件和圖片上傳類
class UploadFile
{//類定義開始
public $maxSize = -1; // 上傳文件的最大值
public $supportMulti = true; // 是否支持多文件上傳
public $allowExts = array();// 允許上傳的文件後綴// 留空不作後綴檢 查
public $allowTypes = array(); // 允許上傳的文件類型 // 留空不做檢查
public $thumb = false; // 使用對上傳圖片進行縮略圖處理
public $thumbMaxWidth; // 縮略圖最大寬度
public $thumbMaxHeight; // 縮略圖最大高度
public $thumbPrefix = 'thumb_'; // 縮略圖前綴
public $thumbSuffix = '';
public $thumbPath = ''; // 縮略圖保存路徑
public $thumbFile = '';// 縮略圖文件名
public $thumbRemoveOrigin =false;// 是否移除原圖
public $zipImages = false; // 壓縮圖片文件上傳
public $autoSub = false; // 啟用子目錄保存文件
public $subType = 'hash';// 子目錄創建方式 可以使用hash date
public $dateFormat = 'Ymd';
public $hashLevel = 1; // hash的目錄層次
public $savePath = ''; // 上傳文件保存路徑
public $autoCheck = true; // 是否自動檢查附件
public $uploadReplace = false;// 存在同名是否覆蓋
// 例如可以是 time uniqid com_create_guid 等
// 必須是一個無需任何參數的函數名 可以使用自定義函數
public $saveRule = '';// 上傳文件命名規則
// 例如可以是 md5_file sha1_file 等// 上傳文件Hash規則函數名
public $hashType = 'md5_file';
private $error = '';// 錯誤信息
private $uploadFileInfo ;// 上傳成功的文件信息
/**
+----------------------------------------------------------
* 架構函數
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='')
{
if(!empty($maxSize) && is_numeric($maxSize)) {
$this->maxSize = $maxSize;
}
if(!empty($allowExts)) {
if(is_array($allowExts)) {
$this->allowExts = array_map('strtolower',$allowExts);
}else {
$this->allowExts = explode(',',strtolower($allowExts));
}
}
if(!empty($allowTypes)) {
if(is_array($allowTypes)) {
$this->allowTypes = array_map('strtolower',$allowTypes);
}else {
$this->allowTypes = explode(',',strtolower($allowTypes));
}
}
if(!empty($savePath)) {
$this->savePath = $savePath;
}
if(!empty($saveRule)) {
$this->saveRule = $saveRule;
}

}

private function save($file)
{
$filename = $file['savepath'].$file['savename'];
if(!$this->uploadReplace && is_file($filename)) {// 不覆蓋同名文件
$this->error = '文件已經存在!'.$filename;
return $this -> error;
}
// 如果是圖像文件 檢測文件格式
if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && $this -> error === getimagesize($file['tmp_name'])) {
$this->error = '非法圖像文件';
return $this -> error;
}
if(!move_uploaded_file($file['tmp_name'], iconv('utf-8','gbk',$filename))) {
$this->error = '文件上傳保存錯誤!';
return $this -> error;
}
if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
$image = getimagesize($filename);
if($this -> error !== $image) {
//是圖像文件生成縮略圖
$thumbWidth = explode(',',$this->thumbMaxWidth);
$thumbHeight = explode(',',$this->thumbMaxHeight);
$thumbPrefix = explode(',',$this->thumbPrefix);
$thumbSuffix = explode(',',$this->thumbSuffix);
$thumbFile = explode(',',$this->thumbFile);
$thumbPath =
$this->thumbPath?$this->thumbPath:$file['savepath'];
// 生成圖像縮略圖
if(file_exists(dirname(__FILE__).'/Image.class.php'))
{
require_once(dirname(__FILE__).'/Image.class.php');
$realFilename = $this->autoSub?basename($file['savename']):$file['savename'];
for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
$thumbname = $thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
Image::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
}
if($this->thumbRemoveOrigin) {
// 生成縮略圖之後刪除原圖
unlink($filename);
}
}
}
}

return true;
}

/**
+----------------------------------------------------------
* 上傳文件
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $savePath 上傳文件保存路徑
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
public function upload($savePath ='') {

if(empty($savePath)) //如果不指定保存文件名,則由系統默認
$savePath = $this->savePath;
$savePath .= date('Ym',time())."/";
if(!is_dir($savePath)) { // 檢查上傳目錄

if(is_dir(base64_decode($savePath))) {// 檢查目錄是否編碼後的
$savePath = base64_decode($savePath);
}else{
if(!mkdir($savePath)){ // 嘗試創建目錄
$this->error = '上傳目錄'.$savePath.'不存在';return $this -> error;
}
}
}else {
if(!is_writeable($savePath)) {
$this->error = '上傳目錄'.$savePath.'不可寫'; return $this -> error;
}
}
$fileInfo = array();
$isUpload = $this -> error;

// 獲取上傳的文件信息
// 對$_FILES數組信息處理
$files = $this->dealFiles($_FILES);
foreach($files as $key => $file) {
//過濾無效的上傳
if(!empty($file['name'])) {
//登記上傳文件的擴展信息
$file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);

// 自動檢查附件
if($this->autoCheck) {
if(!$this->check($file))
return $this -> error;
}

//保存上傳文件
//echo "<pre>";print_r( $file );
if(!$this->save($file)) return $this -> error;
/*
if(function_exists($this->hashType)) {
$fun = $this->hashType;
$file['hash'] = $fun(auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
}
*/
//上傳成功後保存文件信息,供其他地方調用
unset($file['tmp_name'],$file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if($isUpload) {
$this->uploadFileInfo = $fileInfo;
return $fileInfo;
}else {
$this->error = '沒有選擇上傳文件';
return $this -> error;
}
}

/**
+----------------------------------------------------------
* 轉換上傳文件數組變數為正確的方式
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $files 上傳的文件變數
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
private function dealFiles($files) {
$fileArray = array();
foreach ($files as $file){
if(is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i=0; $i<$count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
}else{
$fileArray = $files;
}
break;
}
return $fileArray;
}

/**
+----------------------------------------------------------
* 獲取錯誤代碼信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $errorNo 錯誤號碼
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
* @throws ThinkExecption
+----------------------------------------------------------
*/
protected function error($errorNo)
{
switch($errorNo) {
case 1:
$this->error = '上傳的文件超過了 php.ini 中 upload_max_filesize 選項限制的值';
break;
case 2:
$this->error = '上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值';
break;
case 3:
$this->error = '文件只有部分被上傳';
break;
case 4:
$this->error = '沒有文件被上傳';
break;
case 6:
$this->error = '找不到臨時文件夾';
break;
case 7:
$this->error = '文件寫入失敗';
break;
default:
$this->error = '未知上傳錯誤!';
}
return ;
}

/**
+----------------------------------------------------------
* 根據上傳文件命名規則取得保存文件名
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 數據
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSaveName($filename)
{
$rule = $this->saveRule;
if(empty($rule)) {//沒有定義命名規則,則保持文件名不變
$saveName = $filename['name'];
}else {
if(function_exists($rule)) {
//使用函數生成一個唯一文件標識號
$saveName = $rule().rand(1001,9999).".".$filename['extension'];
}else {
//使用給定的文件名作為標識號
$saveName = $rule.rand(1001,9999).".".$filename['extension'];
}
}
if($this->autoSub) {
// 使用子目錄保存文件
$saveName = $this->getSubName($filename).'/'.$saveName;
}
return $saveName;
}

/**
+----------------------------------------------------------
* 獲取子目錄的名稱
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 上傳的文件信息
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
private function getSubName($file)
{
switch($this->subType) {
case 'date':
$dir = date($this->dateFormat,time());
break;
case 'hash':
default:
$name = md5($file['savename']);
$dir = '';
for($i=0;$i<$this->hashLevel;$i++) {
$dir .= $name{0}.'/';
}
break;
}
if(!is_dir($file['savepath'].$dir)) {
mkdir($file['savepath'].$dir);
}
return $dir;
}

/**
+----------------------------------------------------------
* 檢查上傳的文件
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param array $file 文件信息
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function check($file) {
if($file['error']!== 0) {
//文件上傳失敗
//捕獲錯誤代碼
$this->error($file['error']);
return $this -> error;
}

//檢查文件Mime類型
if(!$this->checkType($file['type'])) {
$this->error = '上傳文件MIME類型不允許!';
return $this -> error;
}
//檢查文件類型
if(!$this->checkExt($file['extension'])) {
$this->error ='上傳文件類型不允許';
return $this -> error;
}
//文件上傳成功,進行自定義規則檢查
//檢查文件大小
if(!$this->checkSize($file['size'])) {
$this->error = '上傳文件大小超出限制!';
return $this -> error;
}

//檢查是否合法上傳
if(!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上傳文件!';
return $this -> error;
}
return true;
}

/**
+----------------------------------------------------------
* 檢查上傳的文件類型是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $type 數據
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkType($type)
{
if(!empty($this->allowTypes))
return in_array(strtolower($type),$this->allowTypes);
return true;
}

/**
+----------------------------------------------------------
* 檢查上傳的文件後綴是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $ext 後綴名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkExt($ext)
{
if(!empty($this->allowExts))
return in_array(strtolower($ext),$this->allowExts,true);
return true;
}

/**
+----------------------------------------------------------
* 檢查文件大小是否合法
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param integer $size 數據
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkSize($size)
{
return !($size > $this->maxSize) || (-1 == $this->maxSize);
}

/**
+----------------------------------------------------------
* 檢查文件是否非法提交
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function checkUpload($filename)
{
return is_uploaded_file($filename);
}

/**
+----------------------------------------------------------
* 取得上傳文件的後綴
+----------------------------------------------------------
* @access private
+----------------------------------------------------------
* @param string $filename 文件名
+----------------------------------------------------------
* @return boolean
+----------------------------------------------------------
*/
private function getExt($filename)
{
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
}

/**
+----------------------------------------------------------
* 取得上傳文件的信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return array
+----------------------------------------------------------
*/
public function getUploadFileInfo()
{
return $this->uploadFileInfo;
}

/**
+----------------------------------------------------------
* 取得最後一次錯誤信息
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
public function getErrorMsg()
{
return $this->error;
}

}//類定義結束
?>

C. 用PHP怎麼上傳web用戶頭像呢😢

index.php:
<?php
echo"

<form action='uploadfile.php' method='post' enctype='multipart/formdata'>
<input type='file' name='file'>
<input type='submit' value='上傳'>
</form>
";
?>
uploadfile.php:
<?php
//接受圖片
$file=$_FILES['file'];
// echo '<pre>';
// print_r($file);
$parr=explode('.',$file['name']);
$hz=$parr[count($parr)-1];
$newfilename=date('YmdHis',time()).rand(1000,9999).'.'.$hz;
if(move_uploaded_file($file['tmp_name'],'./img/'.$newfilename))
{
$headimgurl='http://yourIP/img/'.$newfilename;
}
?>

D. php怎麼實現頭像上傳到客戶端

php根據APP的上傳方式來決定PHP端的獲取方式,多數都是表單式上傳。
$_FILES; file_get_contents('php://input')都可以。

還有的是先在客戶端讀取了文件內容,再base64編碼,再上傳。

比較簡單的大文件斷點上傳,其實就可以靠APP處理。

E. 用PHP上傳用戶頭像怎麼解😢

修改第一
echo " <tr><form action = 'info.php?id=$row[imgid]' method = 'post'> ";
修改第二:
你在info.php中接受你傳過來的id
加入用$cls = $_POST["id"];
然後把id在這樣傳值
echo "<img src='image.php?imgid=$cls'>";
最後
$img_sql="select image_id,content from nsms_images where image_id='$imgid'";這里就可以得到參數了

F. php上傳用戶頭像功能,請問我這樣做對嗎就是直接把用戶上傳的原始大小的頭像圖片顯示在頁面上,在設

不好,如果客戶上傳的圖標有3M大小,設置成頭像的話,載入就需要半天,一半是利用php生成縮略圖。將縮略圖設置為頭像

G. php怎麼上傳頭像

php上傳頭像的功能需要掌握的就是有關文件上傳類的php知識,需要知道的圖片的格式,圖片上傳大小的限制,需要用到的函數有is_uploaded_file(文件上傳的方式)等等,這里舉個例子:
$allowType = array('image/png', 'image/jpeg', 'image/gif');
//做上傳圖片的驗證
//使用try/catch來做判斷
try{
if ( !is_uploaded_file($_FILES['thumb']['tmp_name']) ) {
throw new Exception('縮略圖上傳錯誤'); //拋出錯誤
}
if ( !is_uploaded_file($_FILES['img']['tmp_name']) ) {
throw new Exception('大圖上傳錯誤'); //拋出錯誤
}
if ( !in_array($_FILES['thumb']['type'], $allowType) ) {
throw new Exception('縮略圖格式錯誤'); //拋出錯誤
}
if ( !in_array($_FILES['img']['type'], $allowType) ) {
throw new Exception('大圖格式錯誤'); //拋出錯誤
}
if ( !($_FILES['thumb']['size'] <= 2*1024*1024) ) {
throw new Exception('縮略圖大小錯誤'); //拋出錯誤
}
if ( !($_FILES['img']['size'] <= 2*1024*1024) ) {
throw new Exception('大圖大小錯誤'); //拋出錯誤
}
$thumb_filename = time().mt_rand().substr($_FILES['thumb']['name'], strrpos($_FILES['thumb']['name'], '.'));
$img_filename = mt_rand().time().substr($_FILES['img']['name'], strrpos($_FILES['img']['name'], '.'));
if ( !move_uploaded_file($_FILES['thumb']['tmp_name'], UPLOAD_PATH.'/goods/'.$thumb_filename) ) {
throw new Exception('縮略圖上傳失敗'); //拋出錯誤
}
if ( !move_uploaded_file($_FILES['img']['tmp_name'], UPLOAD_PATH.'/goods/'.$img_filename) ) {
throw new Exception('大圖上傳失敗'); //拋出錯誤
}
} catch ( Exception $e ) {
$message = $e->getMessage();
}
這個函數實現了對圖片的類型的判斷,大小的判斷,還有上傳圖片的命名。

H. 用php寫一個上傳圖片的程序 謝謝

<?php
$uptypes=array('image/jpg', //上傳文件類型列表
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'application/x-shockwave-flash',
'image/x-png');
$max_file_size=5000000; //上傳文件大小限制, 單位BYTE
$destination_folder="upload/"; //上傳文件路徑
$watermark=0; //是否附加水印(1為加水印,其他為不加水印);
$watertype=1; //水印類型(1為文字,2為圖片)
$waterposition=1; //水印位置(1為左下角,2為右下角,3為左上角,4為右上角,5為居中);
$waterstring="newphp.site.cz"; //水印字元串
$waterimg="xplore.gif"; //水印圖片
$imgpreview=1; //是否生成預覽圖(1為生成,其他為不生成);
$imgpreviewsize=1/2; //縮略圖比例
?>
<html>
<head>
<title>M4U BLOG - fywyj.cn</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style type="text/css">body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;margin-left:20px;}
strong{font-size:12px;}
aink{color:#0066CC;}
a:hover{color:#FF6600;}
aisited{color:#003366;}
a:active{color:#9DCC00;}
table.itable{}
td.irows{height:20px;background:url("index.php?i=dots" repeat-x bottom}</style>
</head>
<body>
<center><form enctype="multipart/form-data" method="post" name="upform">
上傳文件: <br><br><br>
<input name="upfile" type="file" style="width:200;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="17">
<input type="submit" value="上傳" style="width:30;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff" size="17"><br><br><br>
允許上傳的文件類型為:jpg|jpeg|png|pjpeg|gif|bmp|x-png|swf <br><br>
<a href="index.php">返回</a>
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
//是否存在文件
{
echo "<font color='red'>文件不存在!</font>";
exit;
}

$file = $_FILES["upfile"];
if($max_file_size < $file["size"])
//檢查文件大小
{
echo "<font color='red'>文件太大!</font>";
exit;
}

if(!in_array($file["type"], $uptypes))
//檢查文件類型
{
echo "<font color='red'>只能上傳圖像文件或Flash!</font>";
exit;
}

if(!file_exists($destination_folder))
mkdir($destination_folder);

$filename=$file["tmp_name"];
$image_size = getimagesize($filename);
$pinfo=pathinfo($file["name"]);
$ftype=$pinfo[extension];
$destination = $destination_folder.time().".".$ftype;
if (file_exists($destination) && $overwrite != true)
{
echo "<font color='red'>同名文件已經存在了!</a>";
exit;
}

if(!move_uploaded_file ($filename, $destination))
{
echo "<font color='red'>移動文件出錯!</a>";
exit;
}

$pinfo=pathinfo($destination);
$fname=$pinfo[basename];
echo " <font color=red>已經成功上傳</font><br>文件名: <font color=blue>".$destination_folder.$fname."</font><br>";
echo " 寬度:".$image_size[0];
echo " 長度:".$image_size[1];
if($watermark==1)
{
$iinfo=getimagesize($destination,$iinfo);
$nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
$white=imagecolorallocate($nimage,255,255,255);
$black=imagecolorallocate($nimage,0,0,0);
$red=imagecolorallocate($nimage,255,0,0);
imagefill($nimage,0,0,$white);
switch ($iinfo[2])
{
case 1:
$simage =imagecreatefromgif($destination);
break;
case 2:
$simage =imagecreatefromjpeg($destination);
break;
case 3:
$simage =imagecreatefrompng($destination);
break;
case 6:
$simage =imagecreatefromwbmp($destination);
break;
default:
die("<font color='red'>不能上傳此類型文件!</a>");
exit;
}

image($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);

switch($watertype)
{
case 1: //加水印字元串
imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
break;
case 2: //加水印圖片
$simage1 =imagecreatefromgif("xplore.gif");
image($nimage,$simage1,0,0,0,0,85,15);
imagedestroy($simage1);
break;
}

switch ($iinfo[2])
{
case 1:
//imagegif($nimage, $destination);
imagejpeg($nimage, $destination);
break;
case 2:
imagejpeg($nimage, $destination);
break;
case 3:
imagepng($nimage, $destination);
break;
case 6:
imagewbmp($nimage, $destination);
//imagejpeg($nimage, $destination);
break;
}

//覆蓋原上傳文件
imagedestroy($nimage);
imagedestroy($simage);
}

if($imgpreview==1)
{
echo "<br>圖片預覽:<br>";
echo "<a href=\"".$destination."\" target='_blank'><img src=\"".$destination."\" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);
echo " alt=\"圖片預覽:\r文件名:".$destination."\r上傳時間:\" border='0'></a>";
}
}
?>
</center>
</body>
</html>

I. php上傳文件如何實現上傳頭像的時候可以顯示出頭像

兩種方案:

  1. 前端直接使用 FileReader可以直接讀取圖片在前端顯示,可以在用戶點擊確定後再通過 ajax上傳到後端(當然,你也可以直接通過 form表單 submit提交)

  2. 用戶點擊上傳文件的時候,直接用 ajax把圖片是傳到後端,後端回傳圖片在伺服器中的地址,前端把這個圖片顯示出來。

J. 如何用thinkPHP實現 類似於QQ頭像上傳的功能

1.建立圖片上傳通道
2.傳成功後把返回的路徑保存在該用戶的表中