PHP learning summary (2)

First, the common method of string

1. String acquisition

  • substr(string, str, len): Get a part of it from the string
$str = "我爱我.的.祖国.png";
$s = substr(strrchr($str,'.'),1);
echo $s;
$arr = explode(".",$str);
$ext = array_pop($arr);
echo "<br>$ext<br>";
  • strstr(string, str) finds the first occurrence of a string in another string and returns all characters from that position to the end of the string
  • strrchr(string,str): Finds the last occurrence of a string in another string and returns all characters from that position to the end of the string

2. String replacement

  • String Replacement: Use a string to replace some characters in a string

3. String calculation

  • strlen(string): get the length of the string
  • strpos(string,str,start): The function is used to locate the first occurrence of a string and returns an integer.
  • strrpos(): locates the last occurrence of a string
$str = "我爱我的祖国,我的祖国是中国";
$str = str_replace("祖国","国家", $str);
echo "<br>$str<br>";

Two, time

1.php timestamp

  • Definition: UNIX timestamp (timestamp) is a very important concept of time and date in PHP, which represents the sum of seconds from January 1, 1970 00:00:00 to the current time.
    PHP provides the built-in function time() to get the timestamp of the server's current time.
<?php
echo time();
?>
  • Format time
    date() function is used to format time and returns a string.
string date( string format [, int timestamp] )
  • Convert string to timestamp
    strtotime("2021-10-20")

3. HTTP global array (uppercase)

  • $_GET[ ]
    Get all get requests
<?php
echo $_REQUEST["nickname"]	//输出用户输入的称呼
echo $_REQUEST["id "];		//输出 10
?>
  • $_POST[ ]
    Get all post requests
<?php
echo '您的称呼是:',$_POST["nickname"]; 
?>
  • $_REQUEST[ ]
    Get all t requests (both get and post can be obtained)
<?php
echo $_REQUEST["nickname"]	//输出用户输入的称呼
echo $_REQUEST["id "];		//输出 10
?>

Four, jsonp method

1.json_encode

PHP json_encode() is used to encode variables in JSON. If the function executes successfully, it returns JSON data, otherwise it returns FALSE.

grammar

string json_encode ( $value  )

example

<?php
   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);//{"a":1,"b":2,"c":3,"d":4,"e":5}
?>

2.json_decode

The PHP json_decode() function is used to decode a string in JSON format and convert it into a PHP variable.

grammar

mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

parameter

  • json_string : JSON string to be decoded, must be UTF-8 encoded data
  • assoc: When this parameter is TRUE, an array will be returned, and when FALSE, an object will be returned.
  • depth : a parameter of integer type, which specifies the recursion depth
  • options : binary mask, currently only JSON_BIGINT_AS_STRING is supported.

example

<?php
   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
   //结果
   object(stdClass)#1 (5) {
    
    
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    
    
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
?>

Five, header method

return json format

header("Content-type: application/json");

Return html format and specify encoding is utf-8

header("Content-type: text/html;charset=utf-8");

6. Overview of sesson

PHP sessions solve this problem by storing user information on the server for later use (such as user name, purchases, etc.). However, session information is temporary and will be deleted after the user leaves the site. If you need to store information permanently, you can store the data in a database.

The working mechanism of Session is: create a unique id (UID) for each visitor, and store variables based on this UID. The UID is stored in a cookie, or transmitted through the URL

Session is a more secure way for a client to communicate with a website (server). Once the session session is opened, it can be used (maintained) on any page of the website, thus establishing a "dialogue" mechanism between the visitor and the website.

The session session will create a unique session ID for each visitor who opens the session session to identify the user. This session ID may be stored in a cookie on the user's computer, or it may be passed through the URL. The corresponding specific session value will be stored on the server side, which is also the main difference from cookies, and the security is relatively high.

create session

To create a session, you must first use the session_start() function to open a session session, and the system will assign a session ID:

<?php
session_start();
?>

read session

PHP's built-in $_SESSION variable can easily access the set session variable.

<?php
// 检索 session 数据
echo "浏览量:". $_SESSION['views'];
?>

destroy session

 <?php
 //删除某些数据
 	session_start();
   if(isset($_SESSION['views']))
   {
    
    
       unset($_SESSION['views']);
   }
   //永久删除数据
    session_destroy();
    ?>

7. isset() detects whether a variable exists

PHP isset() is used to detect whether one or more variables are set, and returns TRUE if the detected variable exists, otherwise returns FALSE.
grammar

bool isset( mixed var [, mixed var [, ...]] )

example

$var = 1;
if(isset($var)){
    
    
    echo '变量 $var 已经被设置';
} else {
    
    
    echo '变量 $var 还未被设置';
}

//结果
//变量 $var 已经被设置

Notice

  • isset() can only be used to detect variables, passing any other parameters will cause a parsing error.
  • isset() is a language construct not a function, so it cannot be called from a variable function.

Eight, php form

PHP predefines $_POST and $_GET variables to receive form information.

HTML form validation

When the form is used to collect customer input information, don't take it for granted that the customer will comply with the specified content according to the expected input. Customer input should be strictly checked at all times.

<body>
<form name="commentform" method="post" action="comment.php">
<p>
称呼: <input type="text" name="nickname" />
</p>
<input type="submit" value="提 交" />
</form>
</body>

client authentication

Client-side form verification is generally based on Javascript script verification. This verification method can effectively reduce the burden on the server, and can also instantly remind customers of input errors.

server-side validation

In some cases, server-side authentication (such as accessing a database) may be required in addition to client-side authentication. At this time, it is necessary to do a logical verification in the PHP program. About server-side authentication

9. Verification code

create picture

$image = imagecreatetruecolor(,);

Create picture colors

$bg = imagecolorallocate(图片,R,G,B);
// RGB是0-255的取值

$bg = imagecolorallocate($image,255,255,255);
// 创建白色的背景

Image area padding

imagefill(图片,x,y,颜色)

imagefill($image,0,0,$bgcolor);

content generation

$data='abcdefghijkmnpqrstuvwxy3456789';
$f=substr($data,rand(0,strlen($data)),1);
从data中随机取出一个字符串

Draw characters on pictures

 imagestring(图片,字体大小,x,y,字符,字符颜色)

session storage

$_SESSION["code"] = $code;

full code

//必须至于顶部,多服务器端记录验证码信息,便于用户输入后做校验
      session_start();
  
     //默认返回的是黑色的照片
     $image = imagecreatetruecolor(100, 30);
     //将背景设置为白色的
     $bgcolor = imagecolorallocate($image, 255, 255, 255);
     //将白色铺满地图
     imagefill($image, 0, 0, $bgcolor);
  
     //空字符串,每循环一次,追加到字符串后面  
     $captch_code='';
  
    //验证码为随机四个数字
     for ($i=0; $i < 4; $i++) {
    
     
         $fontsize=6;
         $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
         
         //产生随机数字0-9
         $fontcontent = rand(0,9);
         $captch_code.= $fontcontent;
        //数字的位置,0,0是左上角。不能重合显示不完全
         $x=($i*100/4)+rand(5,10);
         $y=rand(5,10);
          imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
     }
       
  
   
    $_SESSION['authcode'] = $captch_code;
 //为验证码增加干扰元素,控制好颜色,
 //点   
     for ($i=0; $i < 200; $i++) {
    
     
         $pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
         imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor);
     }
  
 //为验证码增加干扰元素
 //线   
     for ($i=0; $i < 3; $i++) {
    
     
         $linecolor = imagecolorallocate($image,rand(80,220),rand(80,220),rand(80,220));
         imageline($image, rand(1,99), rand(1,29),rand(1,99), rand(1,29) ,$linecolor);
     }
  
     header('content-type:image/png');
     imagepng($image);
   
     //销毁
    imagedestroy($image);

Guess you like

Origin blog.csdn.net/pink_cz/article/details/120911951