快速上手PHP

对象:至少有一种编程语言经验者
目标:扫除你的畏惧,快速上手PHP
当然你也可以直接看官方手册

1.开发工具

对于初学者最重要的就是能够直接Coding,而且能看到运行效果,因此使用PhpStorm会让你感觉神清气爽.

2.语法基础

  1. 变量及操作符
  1. 变量类型包括:Boolean(TRUE,FALSE)布尔类型,integer整型,Float浮点型,String字符串,Array数组,Object对象,NULL,Callback回调类型
  2. PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。注意:无需声明变量类型
$isUnderstand = TRUE;        //Boolean
$fileCount = 5;              //integer
$height1 = 175.3;             //Float
$height2 = 176.9;             //Float
$name = 'xxx';               //String
$arr = array();              //Array
$sumHeight = $height1 + $height2;//操作变量
$fullName = $name.'yyy';
  1. PHPArray分两种(没有字典的概念,在JSON与对象转换中经常容易出错):
    1).索引数组(相当于C++中的数组);
$arr = array(1,2,3,4,'hello','world');
echo $arr[5];

2).关联数组(键值对,相当于C++中的Map)

$arr = array('h'=>'hello','w'=>'world');
echo $arr['w'];
  1. 控制语句
  1. 流程控制if else, switch
//if else
$isOK = TRUE;
$isReady = TRUE;
if($isOK){
  //dosomething
}elseif($isReady){
  //dosomething
}else{
  //dosomething
}
//switch
$str = '30';
switch ($str){    
  case '20':       
        echo $str;        
        break;    
  case '30':        
        echo $str.'hello';
        break;
}
  1. 循环控制for, foreach,while
for ($i = 0;$i < 100; $i++){
  //statement
}
foreach (array as $value){ 
//statement
}
// 或者:
foreach (array as $key => $value){
//statement
}

3.常用函数

  1. 字符串操作
$str = '345671';
$arr = array(1,2,3,4);
//字符串获取
echo substr($str,1,2);//从字符串中获取其中的一部分
//字符串连接
echo implode($arr,'*');//使用字符将数组的内容组合成一个字符串
echo join($arr,'*');//同 implode()
//字符串分割
print_r(explode('*',$str,2));//使用一个字符串分割另一个字符串,返回数组
print_r(str_split($str,3));//将字符串分割到数组中,每个数组中3个元素
//字符串替换
echo str_replace('*','$',$str);//把字符串的一部分替换为另一个字符串
//字符串计算
echo strpos('abcdecf', 'c');    //输出 2
$str1 = "This function returns the last occurance of a string";
echo strlen($str1);//取得字符串的长度
$pos = strrpos($str1, "st");
if($pos !== FALSE){
    echo '字串 st 最后出现的位置是:',$pos;
} else {
    echo '查找的字符串中没有 in 字串';
}
  1. 日期操作
<?php
//do something
sleep(3);
//do something
$running_time = time() - $_SERVER['REQUEST_TIME'];
echo '页面运行时间:',$running_time,' 秒';
?>
<?php
date_default_timezone_set('Asia/Shanghai');//设置时区
echo date('Y-m-d h:i:s',time());//输出格式
?>
  1. JSON转换
<?php
//encode
$arr = array('h'=>'hello','w'=>'world','p'=>'PHP','list'=>array(1,2,3,100));
echo json_encode($arr);//将数组转换成JSON
//decode
$str = '{"h":"hello","w":"world","p":"PHP","list":[1,2,3,100]}';
print_r(json_decode($str));//将JSON转换成数组
?>
  1. 文件操作
<?php//打开文件
if(!file_exists("test.txt")){  //如果文件不存在(默认为当前目录下)      
      $fh = fopen("test.txt","w"); 
      fclose($fh);          //关闭文件
}
?>
<?php//打开互联网文件
$fh = fopen("http://www.baidu.com/", "r");
if($fh){
    while(!feof($fh)) {
        echo fgets($fh);
    }
}
?>
<?php//打开文件
// 读取时同事将换行符转换成 <br />
//file_get_contents()把整个文件读入一个字符串,成功返回一个字符串,失败则返回FALSE
echo nl2br(file_get_contents('test.txt'));
?>
<?php//打开文件
$fh = @fopen("test.txt","r") or die("打开 test.txt 文件出错!");
// if条件避免无效指针
if($fh){
    while(!feof($fh)) {
        echo fgets($fh), '<br />';
    }
}
fclose($fh);
?>
<?php// 要写入的文件名字
$filename = 'file.txt';
// 写入的字符
$word = "你好!";
$fh = fopen($filename, "w");
echo fwrite($fh, $word);    // 输出:6
fclose($fh);
?>
<?php//写入文件
echo file_put_contents("test.txt", "This is something.");
?>
  1. 上传文件

文件上传功能是网络生活中经常使用的一个功能。使用 PHP 可以很方便的实现文件上传,其具体流程如下: 表单选择文件 -> 检查文件大小及类型 -> 生成临时文件 -> 移动临时文件至文件存储目录 -> 记录文件信息以便于管理。

  1. HTML表单
<form enctype="multipart/form-data" action="upload.php" method="post">
<label for="file">请选择上传的文件</label>
<input type="file" name="file" size="40" />
<br />
<input type="submit" name="submit" value="确定" />
</form>

2.PHP文件处理

//upload.php
<?php
//文件存储路径
$file_path="upload/";
//664权限为文件属主和属组用户可读和写,其他用户只读。
if(is_dir($file_path)!=TRUE) mkdir($file_path,0664) ;
//定义允许上传的文件扩展名
$ext_arr = array("gif", "jpg", "jpeg", "png", "bmp", "txt", "zip", "rar");
if (empty($_FILES) === false) {
    //判断检查
    if($photo_up_size > 2097152){
        exit("对不起,您上传的照片超过了2M。");
    }
    if($_FILES["file"]["error"] > 0){
        exit("文件上传发生错误:".$_FILES["file"]["error"]);
    }
    //获得文件扩展名
    $temp_arr = explode(".", $_FILES["file"]["name"]);
    $file_ext = array_pop($temp_arr);
    $file_ext = trim($file_ext);
    $file_ext = strtolower($file_ext);
    //检查扩展名
    if (in_array($file_ext, $ext_arr) === false) {
        exit("上传文件扩展名是不允许的扩展名。");
    }
    //以时间戳重命名文件
    $new_name = time().".".$file_ext;
    //将文件移动到存储目录下
    move_uploaded_file($_FILES["file"]["tmp_name"],"$file_path" . $new_name);
    //向数据表写入文件存储信息以便管理
    //*********** 代码略 ***********//
    echo "文件上传成功!";
    exit;
} else {
    echo "无正确的文件上传";
}
?>
  1. 生成图片
    图像生成和处理
<?php
$img = imagecreate(400,400);//创建image
imagecolorallocate($img,0,0,0);//设置背景色
header('Content-type: image/png');
imagepng($img);
?>
  1. 图片打水印
    图像生成和处理
<?php
$img = imagecreate(400,400);//创建image
imagecolorallocate($img,0,0,0);//设置背景色
imagestring($img,0,0,200,20,'水印',255,0,0);//添加水印
header('Content-type: image/png');
imagepng($img);
?>

4. 表单及会话

  1. 表单创建和提交
    常见表单类型:PHP 表单,PHP $_POST,PHP $_GET
<html>
<body>
<form name="commentform" method="post" action="comment.php">
<p>称呼: <input type="text" name="nickname" /></p>
<input type="submit" value="提 交" />
</form>
</body>
</html>
//comment.php
<html>
<body>
<p>您的称呼是:<?php echo $_POST["nickname"]; ?></p>
</body>
</html>
  1. 会话管理
  1. Cookie设置和获取(PHP 内置了 $_COOKIE 变量以访问设置的cookie值)
<?php//设置Cookie
setcookie("username", "xiaoli", time()+3600, "/", ".5idev.com");
?>
<?php//读取Cookie
if (isset($_COOKIE["username"])) {
    echo "欢迎你: ".$_COOKIE["username"];
} else {
    echo "请登陆";
}
?>
<?php//销毁Cookie
setcookie("username", "", time()-3600);//失效时间
?>
  1. Session设置(PHP内置的$_SESSION变量可以很方便的访问设置的session变量。)
//要创建 session ,必须先使用 session_start() 函数开启一个 session 会话,系统会分配一个会话 ID:
<?php
session_start();
?>
//使用 session_register() 函数可以在目前会话下注册一个或多个全局 session 变量。
<?php
session_start();
$username = "xiaoming";
session_register("username");
//session_start();//方式二
//$_SESSION["username"] = "xiaoming";//方式二
?>
//读取Session
<?php
session_start();
echo "登记的用户名为:".$_SESSION["username"];    //输出 登记的用户名为:xiaoming
?>
//可以通过 session_unregister() 函数来注销单个 session 变量或使用 session_unset() 来注销整个 session 会话。
<?php
session_start();
session_unregister("username");    //注销 session 变量
session_unset();                    //注销 session 会话
//unset($_SESSION["username"]);//方式二
?>

5. 总结

哈哈,PHP是世界上最好的语言.

6. 参考

  1. 官方手册
  2. 在线教程
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、会话控制(session与cookie) 1.cookie简介 Cookie是存储在客户端浏览器中的数据,我们...
    空谷悠阅读 699评论 0 5
  • 一、php可以做什么 php是一种可以在服务器端运行的编程语言,可以运行在Web服务器端。 php是一门后台编程语...
    空谷悠阅读 3,277评论 4 97
  • PHP7 已经出来1年了,PHP7.1也即将和大家见面,这么多好的特性,好的方法,为什么不使用呢,也希望PHP越来...
    梦幻_78af阅读 2,231评论 1 10
  • 一、数组 1、数组的声明:$arr = array(); 2、数组的初始化:PHP有两种数组:索引数组、关联数组。...
    yzw12138阅读 1,251评论 2 2
  • 这个世界,人情这个词语,总是显得神秘。人情恩惠,好像是人与人之间的轮轴。在千山万水的世界里,会相聚,也容易擦肩而过...
    那个女孩好梦阅读 1,310评论 0 2

友情链接更多精彩内容