首页 > 编程技术 > php

php 错误处理与异常处理方法与实例教程(1/2)

发布时间:2016-11-25 17:34

在程序开发中,错误处理这一块是非常重要的,今天本文章就来告诉他关于在php开发中,错误处理函数并且举例说明错误处理的重要性。

  1、内置异常处理类。
  2、捕获并处理异常的示例。
  3、exception类的成员函数getmessage()。
  4、exception类的成员函数getfile()。
  5、exception类的成员函数getline()。
  6、显示警告或错误信息。
  7、自定义错误处理函数。

*/

 // 1、内置异常处理类。

 代码如下 复制代码

 class exception
{
    protected $message = 'unknown exception';   // 异常信息
    protected $code = 0;                        // 用户自定义异常代码
    protected $file;                            // 发生异常的文件名
    protected $line;                            // 发生异常的代码行号

    function __construct($message = null, $code = 0);

    final function getmessage();                // 返回异常信息
    final function getcode();                   // 返回异常代码
    final function getfile();                   // 返回发生异常的文件名
    final function getline();                   // 返回发生异常的代码行号
    final function gettrace();                  // backtrace() 数组
    final function gettraceasstring();          // 已格成化成字符串的 gettrace() 信息

    function __tostring();                      // 可输出的字符串
}
 

// 2、捕获并处理异常的示例。

 代码如下 复制代码

 try
{
    $error = '抛出异常信息,并且跳出try块<br/>';
    if(is_dir('./test'))
    {
        echo '检测到../ch16是一个目录';
        echo '<br/>';
        echo '可能继续做其他一些操作';
        echo '<br/>';
        echo '....';
        echo '<br/>';
    }
    else
    {
        throw new exception($error,12345);
    }
    echo '上面throw异常的话,这行代码不会执行,转而执行catch块<br/>';
}
catch(exception $e)
{
    echo '捕获异常: ' . $e->getmessage() . "<br/>错误代码:" . $e->getcode().'<br/>';    //显示$error和123456
    echo '<br/>';
}

echo '继续执行';

 

本款php ajax应用实例是一款利用ajax+php调用城市二级联动菜单,这样我们可以实时的根据数据库内容更新了。

 代码如下 复制代码

<html>
<head>
<title>ajax+php无刷新二级联动菜单的应用实例</title>

<script language="网页特效">
var xmlhttp = null;

function getxmlhttprequest()
{
    var xmlhttp=null;
    try
    {
        xmlhttp = new xmlhttprequest();
    }
    catch(e)
    {
        try
        {
            xmlhttp = new activexobject("msxml2.xmlhttp");
        }
        catch (e)
        {
            try
            {
                xmlhttp = new activexobject("microsoft.xmlhttp");
            }
            catch(e)
            {
                xmlhttp = false;
            }           
        }
    }

return xmlhttp;
}

function sendrequest()
{
    var prov_name = document.getelementbyid("province").value;

    if((prov_name == null) || (prov_name == ""))
        return;
   
    xmlhttp = getxmlhttprequest();
    if(xmlhttp == null)
    {
        alert("浏览器不支持xmlhttprequest!");
        return;
    }

    var url = "www.111cn.net.php";
    url = url + "?prov=" + prov_name;

    xmlhttp.open("get", url, true);
    xmlhttp.onreadystatechange = updatepage;
    xmlhttp.send(null);
}

function updatepage()
{
    if(xmlhttp.readystate == 4 && xmlhttp.status == 200)
    {
        var response = xmlhttp.responsetext;
        document.getelementbyid("city").innerhtml = response;
    }
}
</script>

<head>

<body>
<h3>请选择一个省(自治区):</h3>

<form action="www.111cn.net.php">
    <div>
    <select id="province" onchange="sendrequest()">
        <option value="">请选择一个省(自治区)</option>
        <option value="ah">安徽</option>
        <option value="fj">福建</option>
        <option value="gs">甘肃</option>
        <option value="gd">广东</option>
        <option value="gx">广西</option>
        <option value="gz">贵州</option>
        <option value="hn">海南</option>
        <option value="hb">河北</option>
        <option value="hh">河南</option>
        <option value="hl">黑龙江</option>
    </select>
    </div>
</form>

<div id="city">
</div>

</body>
</html>

www.111cn.net.php代码

 代码如下 复制代码

<?php
$city_arr = array(
"ah"=>"合肥",
"fj"=>"福州",
"gs"=>"兰州",
"gd"=>"广州",
"gx"=>"南宁",
"gz"=>"贵阳",
"hn"=>"海口",
"hb"=>"石家庄",
"hh"=>"郑州",
"hl"=>"哈尔滨"
);

if(empty($_get['prov']))
{
    echo iconv("gb2312","utf-8",'<font color="red">您没有选择省(自治区)</font>');
}
else
{
    $prov = $_get['prov'];
    $city = $city_arr[$prov];
    echo iconv("gb2312","utf-8",'所选省(自治区)省会(首府)为:'.$city);
}
?>

这是一款由php+mysql数据库的读取数据库的内容再生成树型号菜单由js来控制
 代码如下 复制代码

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>类别目录树</title>
<script type="text/网页特效">
function showmenu(menuid)
{
if(menuid.style.display=="none"){
menuid.style.display="";
}
else{
menuid.style.display="none";
}
}
</script>
<style>
body{margin:0px;}
table tr td{font-size:12px}
</style>
</head>
<body>

<?php
$globals["id"] =1; //用来跟踪下拉菜单的id号
$layer=1; //用来跟踪当前菜单的级数
//连接数据库
$con=mysql_connect("localhost","root","123456");
mysql_select_db("demo");

//提取一级菜单
$sql="select * from think_news where `f_id`=0";
$result=mysql_query($sql,$con);
//如果一级菜单存在则开始菜单的显示
if(mysql_num_rows($result)>0) showtreemenu($con,$result,$id);
function showtreemenu($con,$result,$layer)
{
//取得需要显示的菜单的项目数
$numrows=mysql_num_rows($result);
//开始显示菜单,每个子菜单都用一个表格来表示
  echo "<table cellpadding='0' cellspacing='0' border='0' width='100%'>";
 for($rows=0;$rows<$numrows;$rows++)
 {
   //将当前菜单项目的内容导入数组
    $menu=mysql_fetch_array($result);
   //提取菜单项目的子菜单记录集
   $sql="select * from think_news where f_id=$menu[id]";
   $result_sub=mysql_query($sql,$con);
   echo "<tr>";
   //如果该菜单项目有子菜单,则添加javascript onclick语句
   if(mysql_num_rows($result_sub)>0)
   {
         echo "<td width='20' valign= 'top' ><span onclick='showmenu(menu".$globals['id'].")' ><img" width=100% src='menu_minus.gif' border='0'  align='absmiddle'></span></td>";
         echo "<td class='menu' >";
   }
   else
   {
         echo "<td width='20'><img" width=100% src='menu_plus.gif' border='0' align='absmiddle' > </td>";
         echo "<td class='menu'>";
   }
   //如果该菜单项目没有子菜单,只显示菜单名称
   echo $menu["title"];
   echo "</td></tr>";
   //如果该菜单项目有子菜单,则显示子菜单
   if(mysql_num_rows($result_sub)>0)
   {
       //指定该子菜单的id和style,以便和onclick语句相对应
       echo "<tr id=menu".$globals["id"]++." style='display:none'>";
       echo "<td width='20'> </td>";
       echo "<td>";
       //将级数加1
       $layer++;
       //递归调用showtreemenu()函数,生成子菜单
       showtreemenu($con,$result_sub,$layer);
       //子菜单处理完成,返回到递归的上一层
       echo "</td></tr>";
   }
   //子菜单处理完成,返回到递归的上一层,将级数减1
   $layer--;
  }
  echo "</table>";
}

本文章利用了php多文件上传类来实现,多文件上传最主要就是关于file的属性必须以数组形式并且用foreach或for也读取来一个个用move_uploaded_file把文件上传到服务器这样就实现的多文件上传哦。
 代码如下 复制代码

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>php多文件上传代码</title>
</head>

<body>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="spec[]">
<input type="file" name="spec[]">


<!--<input type="file" name="spec">
<input type="file" name="manual">-->
<input type="submit">
</form>
</body>
</html>

server.php

<?php
//upload array files
include 'upload.class.php';
$u = new upload('../uploads/product/','spec','group');
print_r($u->getnewname());
echo $u->geterror();
/***********************
 //upload single file
$u = new upload('../www.111cn.net/product/','spec');
print_r($u->getnewname());
$u = new upload('../mb.111cn.net/product/','manual');
print_r($u->getnewname());
echo $u->geterror();
************************/
?>

 

//###########################################################
//
// for questions and comments
// roland (alias -=: vlieg :=-)
// icq #78354631
// mail: vlieg@atoomnet.net
//
// nb: this script won't work on free hosting pages, because of the secure mode!
// nb: you must have registered your icq# at http://web.icq.com/sms/login/ in order for this script to work
//###########################################################


$htmlreply="";
$post ="post http://web.icq.com/karma/dologin/1,,,00.html http/1.0
accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
referer: http://web.icq.com/sms/login/1,,,00.html
accept-language: nl
content-type: application/x-www-form-urlencoded
accept-encoding: gzip, deflate
user-agent: mozilla/4.0 (compatible; msie 5.0; windows 98; digext)
host: web.icq.com
content-length: ".$contentlength."
proxy-connection: keep-alive
pragma: no-cache
cookie: uin=".$uin."; sms_country=".$prefix."; karmaservice1=yes; uin=".$uin."; sms_country=".$prefix."; karmaservice1=yes

uservice=1&ulogin=".$uin."&upassword=".$passw."&x=0&y=0";

$remote = fsockopen("web.icq.com", 80, &$errno, &$errstr, 30);

global $remote;
global $post;
fputs($remote, $post);

while (!feof($remote)) { $htmlreply.=fgets($remote,120); }
//uncomment for output: echo "".htmlspecialchars($htmlreply)."";
fclose($remote);

//****************************************************************//persoonlijke cookie uit de inlogpage halen
// en: fetch personal cookie from login page

$splited = split(" ",$htmlreply);
$cookies = $splited[3];
$cookies = str_replace("set-cookie: karmalogin=","",$cookies);
$cookies = str_replace("; path=/","",$cookies);
$cookies = str_replace(" ","",$cookies);
//uncomment voor output: echo $cookies;

if (strlen($prefix) == 2) { $contentprefix = ' '.$prefix; } else { $contentprefix = $prefix; }
$charcount = (160-strlen($message));
$contentlength= ( 1561+
strlen($message)+
strlen($charcount)+
strlen($phonenumber)+
strlen($prefix)
);

//****************************************************************//verzendpagina openen met de opgehaalde cookie
// en: open send page with fetched cookie

$htmlreply="";
$post ='post http://web.icq.com/sms/send_history/1,,,00.html http/1.0
accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*
referer: http://web.icq.com/sms/send_session/1,,,00.html?prefix=+'.$prefix.'&carrier=&tophone='.$phonenumber.'
accept-language: nl
content-type: multipart/form-data; boundary=---------------------------7d12442eab4
accept-encoding: gzip, deflate
user-agent: mozilla/4.0 (compatible; msie 5.0; windows 98; digext)
host: web.icq.com
content-length: '.$contentlength.'
proxy-connection: keep-alive
pragma: no-cache
cookie: uin='.$uin.'; sms_country='.$prefix.'; karmaservice1=yes; karmalogin='.$cookies.'; uin='.$uin.'; sms_country='.$prefix.'; karmaservice1=yes; karmalogin='.$cookies.'

-----------------------------7d12442eab4
content-disposition: form-data; name="carrier"


-----------------------------7d12442eab4
content-disposition: form-data; name="prefix"

'.$contentprefix.'
-----------------------------7d12442eab4
content-disposition: form-data; name="tophone"

'.$phonenumber.'
-----------------------------7d12442eab4
content-disposition: form-data; name="usession"

1
-----------------------------7d12442eab4
content-disposition: form-data; name="ureply"


-----------------------------7d12442eab4
content-disposition: form-data; name="ulastid"


-----------------------------7d12442eab4
content-disposition: form-data; name="usend"

1
-----------------------------7d12442eab4
content-disposition: form-data; name="unextid"


-----------------------------7d12442eab4
content-disposition: form-data; name="uhistorycounter"

1
-----------------------------7d12442eab4
content-disposition: form-data; name="count"

0
-----------------------------7d12442eab4
content-disposition: form-data; name="usubmitcount"

0
-----------------------------7d12442eab4
content-disposition: form-data; name="checknewmsg"

180000
-----------------------------7d12442eab4
content-disposition: form-data; name="charcount"

'.$charcount.'
-----------------------------7d12442eab4
content-disposition: form-data; name="msg"

'.$message.'
-----------------------------7d12442eab4
content-disposition: form-data; name="x"

30
-----------------------------7d12442eab4
content-disposition: form-data; name="y"

16
-----------------------------7d12442eab4--
';

$remote = fsockopen("web.icq.com", 80, &$errno, &$errstr, 30);

global $remote;
global $post;
fputs($remote, $post);

while (!feof($remote)) { $htmlreply.=fgets($remote,120); }
//uncomment for output: echo "".htmlspecialchars($htmlreply)."";
fclose($remote);

//****************************************************************// check if message is send if send 'moved permanently' is returned

if (eregi('moved permanently',$htmlreply))
{ echo "sms message successfully sent!"; }
else
{ echo "sms not sent!"; }

标签:[!--infotagslink--]

您可能感兴趣的文章: