您好,欢迎访问一九零五行业门户网

php如何实现头像上传

php实现头像上传的方法:【 本文操作环境:windows10系统、php 7、thinkpad t480电脑。
最近在做项目时需要使用到头像上传的功能,于是记录下实现的过程。
如果我们要完成头像上传功能需要php页面,一个页面我们定义为touxiang.php,另一个页面我们定义为upload.php。
看下具体代码:
1.touxiang.php
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>无标题文档</title><link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" /><script src="bootstrap-3.3.7-dist/js/jquery-1.11.2.min.js"></script><script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script><style type="text/css">#yl{ width:200px; height:200px; background-image:url(img/avatar.png); background-size:200px 200px;}#file{ width:200px; height:200px; float:left; opacity:0;}.modal-content{ width:500px;}.kk{ margin-left:130px;}</style></head><body><!-- 按钮触发模态框 --><button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#mymodal"> 上传头像</button><!-- 模态框(modal) --><div class="modal fade" id="mymodal" tabindex="-1" role="dialog" aria-labelledby="mymodallabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title" id="mymodallabel"> 上传头像 </h4> </div> <div class="modal-body"> <form id="sc" action="upload.php" method="post" enctype="multipart/form-data" target="shangchuan"> <input type="hidden" name="tp" value="" id="tp" /> <div id="yl" class="kk"> <input type="file" name="file" id="file" onchange="document.getelementbyid('sc').submit()" /> </div></form><iframe style="display:none" name="shangchuan" id="shangchuan"></iframe> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭 </button> <!--<button type="button" class="btn btn-primary"> 提交更改 </button>--> </div> </div><!-- /.modal-content --> </div><!-- /.modal --></div></body><script type="text/javascript">//回调函数,调用该方法传一个文件路径,该变背景图function showimg(url){ var div = document.getelementbyid("yl"); div.style.backgroundimage = "url("+url+")"; document.getelementbyid("tp").value = url;}</script></html>
在这个页面我们需要引入一个模态框和bootstrap.min.css,jquery-1.11.2.min.js,bootstrap.min.js三个文件
2.upload.php
<?phpif($_files["file"]["error"]){ echo $_files["file"]["error"];}else{ if(($_files["file"]["type"]=="image/jpeg" || $_files["file"]["type"]=="image/png")&& $_files["file"]["size"]<1024000000) { $fname = "./img/".date("ymdhis").$_files["file"]["name"]; $filename = iconv("utf-8","gb2312",$fname); if(file_exists($filename)) { echo "<script>alert('该文件已存在!');</script>"; } else { move_uploaded_file($_files["file"]["tmp_name"],$filename); unlink($_post["tp"]); echo "<script>parent.showimg('{$fname}');</script>"; } }}
效果如下所示:
推荐学习:php培训
以上就是php如何实现头像上传的详细内容。
其它类似信息

推荐信息