首页 > 编程技术 > php

php获取上传文件类型 获取文件后缀

发布时间:2016-11-25 15:11

本教程提供了三款获取上传文件与图片类型的方法,方法也是很简单的前二种,是先把类型定义好,再用in_array判断,最后一步是利用了fopen再读取前二个字节,判断。
 代码如下 复制代码

//获得图片的格式,包括jpg,png,gif
function get_type($img_name)//获取图像文件类型
{
 if (preg_match("/.(jpg|jpeg|gif|png|bmp)$/i", $img_name, $matches)){
  $type = strtolower($matches[1]);
 }else{
  $type = "string";
 }
 return $type;
}

//判断上传文件类型
$allowedextensions = array("txt","csv","htm","html","xml",  
    "css教程","doc","xls","rtf","ppt","pdf","swf","flv","avi",  
    "wmv","mov","jpg","jpeg","gif","png");   
    foreach ($_files as $file) {  
    if ($file['tmp_name'] > '') {  
      if (!in_array(end(explode(".",  
            strtolower($file['name']))),  
            $allowedextensions)) {  
       die($file['name'].' is an invalid file type!<br/>'.  
        '<a href="网页特效:history.go(-1);">'.  
        '&lt;&lt go back</a>');  
      }  
}  
}  

//另类的读取文件与图片类型

function checktitle($filename) {
$file     = fopen($filename, "rb");
$bin      = fread($file, 2); //只读2字节
fclose($file);
$strinfo  = @unpack("c2chars", $bin);
$typecode = intval($strinfo['chars1'].$strinfo['chars2']);
$filetype = "";
switch ($typecode)
{
 case 7790:
 $filetype = 'exe';
 break;
 case 7784:
 $filetype = 'midi';
 break;
 case 8297:
 $filetype = 'rar';
 break;
 case 255216:
 $filetype = 'jpg';
 break;
 case 7173:
 $filetype = 'gif';
 break;
 case 6677:
 $filetype = 'bmp';
 break;
 case 13780:
 $filetype = 'png';
 break;
 default:
 $filetype = 'unknown'.$typecode;
}
//fix
if ($strinfo['chars1']=='-1' && $strinfo['chars2']=='-40' ) {
return 'jpg';
}
if ($strinfo['chars1']=='-119' && $strinfo['chars2']=='80' ) {
return 'png';
}
return $filetype;
}

 

?>

我们经常会碰到采集内容时,要补全地址是吧,下面我们来看看这款php把相对路径转换成绝对路径方法吧。

相对路径转化成绝对路径

 代码如下 复制代码

function relative_to_absolute($content, $feed_url) {
    preg_match('/(http|https教程|ftp):///', $feed_url, $protocol);
    $server_url = preg_replace("/(http|https|ftp|news):///", "", $feed_url);
    $server_url = preg_replace("//.*/", "", $server_url);

    if ($server_url == '') {
        return $content;
    }

    if (isset($protocol[0])) {
        $new_content = preg_replace('/href="//', 'href="'.$protocol[0].$server_url.'/', $content);
        $new_content = preg_replace('/src="//', 'src="'.$protocol[0].$server_url.'/', $new_content);
    } else {
        $new_content = $content;
    }
    return $new_content;
}

//取得所有链接

 代码如下 复制代码
function get_all_url($code){
        preg_match_all('/<as+href=["|']?([^>"' ]+)["|']?s*[^>]*>([^>]+)</a>/i',$code,$arr);
        return array('name'=>$arr[2],'url'=>$arr[1]);

定义和用法
header() 函数向客户端发送原始的 http 报头。

认识到一点很重要,即必须在任何实际的输出被发送之前调用 header() 函数(在 php教程 4 以及更高的版本中,您可以使用输出缓存来解决此问题):

<html>

实例一

 代码如下 复制代码
<?php # script 2.7 - view_tasks.php
// connect to the database:
$dbc = @mysql教程i_connect ('localhost', 'username', 'password', 'test') or die ('<p>could not connect to the database!</p></body></html>');
// get the latest dates as timestamps教程:
$q = 'select unix_timestamp(max(date_added)), unix_timestamp(max(date_completed)) from tasks';
$r = mysqli_query($dbc, $q);
list($max_a, $max_c) = mysqli_fetch_array($r, mysqli_num);
// determine the greater timestamp:
$max = ($max_a > $max_c) ? $max_a : $max_c;
// create a cache interval in seconds:
$interval = 60 * 60 * 6; // 6 hours
// send the header:
header ("last-modified: " . gmdate ('r', $max));
header ("expires: " . gmdate ("r", ($max + $interval)));
header ("cache-control: max-age=$interval");
?>

实例二

 代码如下 复制代码

<?php
// 结果出错
// 在调用 header() 之前已存在输出
header('location: http://www.111cn.net/');
?>语法
header(string,replace,http_response_code)

提示用户保存一个生成的 pdf 文件(content-disposition 报头用于提供一个推荐的文件名,并强制浏览器显示保存对话框):

 代码如下 复制代码

<?php
header("content-type:application/pdf");

// 文件将被称为 downloaded.pdf
header("content-disposition:attachment;filename='downloaded.pdf'");

// pdf 源在 original.pdf 中
readfile("original.pdf");
?>

<html>
<body>

 代码如下 复制代码

<script language="网页特效">
    function checkreg()
    {    
  if (form1.name.value=="")
  {
   // 如果真实姓名为空,则显示警告信息
         alert("真实姓名不能为空!");
   form1.name.focus();
   return false;
     }
  if (form1.password.value=="" )
  {
   // 如果密码为空,则显示警告信息
         alert("密码不能为空!");
   form1.password.focus();
   return false;
     }
  if (form1.pwd.value=="" )
  {
   // 如果密码为空,则显示警告信息
         alert("确认密码不能为空!");
   form1.pwd.focus();
   return false;
     }
  // 两次密码应一样
  if (form1.password.value!=form1.pwd.value && form1.password.value!="")
  {
   alert("两次密码不一样,请确认!");
   form1.password.focus();
   return false;
  }
  if (form1.email.value=="")
  {
   // 如果email为空,则显示警告信息
         alert("email不能为空!");
   form1.email.focus();
   return false;
     }
   // 检查email格式是否正确
  else if (form1.email.value.charat(0)=="." ||
   form1.email.value.charat(0)=="@"||
   form1.email.value.indexof('@', 0) == -1 ||
   form1.email.value.indexof('.', 0) == -1 ||
   form1.email.value.lastindexof("@")==form1.email.value.length-1 ||
   form1.email.value.lastindexof(".")==form1.email.value.length-1)
  {
   alert("email的格式不正确!");
   form1.email.select();
   return false;
  }
  return true;

    } 
</script>

<html>
<body>

<form name="form1" method="post" action="regok.php" enctype='multipart/form-data' onsubmit="return checkreg()" >
  <table border="0" cellspacing="1" cellpadding="3" align="center">
    <tr>
      <th colspan="2"><font size="5">用 户 注 册 界 面</font></th>
    </tr>   
    <tr>
      <td>姓   名:</td>
      <td>
        <input type="text" name="name">
    </tr>
    <tr>
      <td>密   码:</td>
      <td>
        <input type="password" name="password">       
    </tr>
 <tr>
      <td>确认密码:</td>
      <td>
        <input type="password" name="pwd">       
    </tr>
 <tr>
      <td>email:</td>
      <td>
        <input type="text" name="email">       
    </tr>
  <tr>
      <td>电   话:</td>
      <td>
        <input type="text" name="tel">
    </tr>
 <tr>
      <td>地   址:</td>
      <td>
        <input type="text" name="address">
    </tr>   
    <tr>
      <td  align=right >
        <input type="submit" name="submit" value="注 册">
      </td>
      <td align=center>
        <input type="reset" name="submit2" value="重 写">
      </td>
    </tr>
  </table>
</form>

</body>

</html>

<?php

 代码如下 复制代码

//初始化session
session_start();
// 包含数据库教程连接文件和头文件
$conn=mysql教程_connect("localhost","phpdb","phpdb")
        or die("不能连接数据库服务器: ".mysql_error());
mysql_select_db("book",$conn) or die ("不能选择数据库: ".mysql_error());
?>
<?php
// 取得网页的参数
$name=$_post['name'];
$password=$_post['password'];
$email=$_post['email'];
$tel=$_post['tel'];
$address=$_post['address'];

// 加密密码
$password=md5($password);

// 连接数据库,注册用户
$sql="insert into user(name, password, email, tel, address) values('$name','$password','$email', '$tel','$address')";
mysql_query($sql,$conn) or die ("注册用户失败: ".mysql_error());

// 获得注册用户的自动id,以后使用此id才可登录
$result=mysql_query("select last_insert_id()",$conn);
$re_arr=mysql_fetch_array($result);
$id=$re_arr[0];

// 注册成功,自动登录,注册session变量
session_register("user");
$user=$id;
echo "<table align=center><tr><td align=center>注册成功!</td></tr>";
echo "<tr><td align=center><font color=red>您的注册id是:".$id;
echo ",请您记住,以后用此id登录!</font></td></tr></table>";

本款php教程是一款告诉你如何连接和选择数据库并且利用php把数据保存,删除,修改,更新,查询 mysql数据库的php入级教程。

*/

 代码如下 复制代码

// 连接和选择数据库
$conn=mysql_connect("localhost","phpdb","phpdb")
        or die("不能连接数据库服务器: ".mysql_error()); 
mysql_select_db("test",$conn) or die ("不能选择数据库: ".mysql_error()); 
// 插入记录部分
// 编辑插入记录的sql语句
$insertsql="insert into user(name,password,address,tel,email) values('王强','123','深圳','8163445','wang@wel.com')";
// 执行插入操作
$insert = mysql_query($insertsql,$conn);
// 检测插入操作是否成功
if ($insert){
 echo "插入记录成功!";
 echo "<br>";
}
else
{
 echo "插入记录失败!";
 echo "<br>";
}

// 修改记录部分
// 编辑修改记录的sql语句
$updatesql="update set tel='1234567' from user where name='王强'";
// 执行修改操作
$update = mysql_query($updatesql,$conn);
// 检测修改操作是否成功
if ($update){
 echo "修改记录成功!";
 echo "<br>";
}
else
{
 echo "修改记录失败!";
 echo "<br>";
}

// 删除记录部分
// 编辑删除记录的sql语句
$deletesql="delete from user where name='王强'";
// 执行删除操作
$delete = mysql_query($deletesql,$conn);
// 检测删除操作是否成功
if ($delete){
 echo "删除记录成功!";
 echo "<br>";
}
else
{
 echo "删除记录失败!";
 echo "<br>";
}

/*
use test;
create table users (
   id int(3) not null auto_increment,
   name varchar(20) not null,
   password varchar(50) not null,
   address varchar(50),
   tel varchar(20),
   email varchar(50) not null,
   primary key (id)
);
*'

?>

标签:[!--infotagslink--]

您可能感兴趣的文章: