Basic PHP Operations

Source: Internet
Author: User
PHP can create. php files Separately, or you can write them after adding PHP tags to the HTML. If you do not display Chinese characters, you should not add them inside the tag:

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

A. PHP markup

 
  

Or

After the declaration, you can write PHP code in PHP and other markup methods, not to understand.

Two. PHP comments

The annotation method is similar to JS.

Three. Variables and constants

1. Variables

    • The variables are declared as:
      $a = ten; $b = "AAA";
      The value of the output variable can be used: echo for the output query. At the same time, variable declarations allow nesting with each other, such as:
$n = ' Hello '; $ $n = ' Gaoshan '; echo $hello;

The output is:

Gaoshan
    • In addition, ECHO can also output the label content
echo "This is a link to Baidu", or echo "";

The output, then, is a connection and a button.

    • One thing to note is that when assigning a value, the $c= $a means assigning a value to C but has no effect on a itself, whereas & $c = $a means that the storage address of a is assigned to C, then A and C are changed, and the other one changes.

2. Constants

Parameter definition

Constants: Constants that cannot be changed cannot be assigned the first parameter once defined: the second parameter of the constant name to be defined: the value of the constant the third argument: whether the case is _* insensitive (true) _*

Example:

Define ("PI", "3.1415926", true); Echo Pi;echo Pi;

At this point, two outputs are 3.1415926, but if the true of parameter three is changed to False, then echo Pi;

3. Echo Features

    • After echo if the concatenated string contains variables, then you should use "" or "if necessary," in "," $ "default to the declaration symbol of the variable, but in '," $ "defaults to a symbol, the" $ "prototype for output.
$name = "Tom"; $age = 22;echo "My name is $name, age $age"; Echo ' My name is $name, age $age ';

At this point the print result is

My name is Tom, age 22 My name is $name, age $age
    • When we want to output the format and content of an object, we usually use the output function as Var_dump ().
Var_dump ($age); Var_dump ("HHAHSDHD");

The result of this printing is

Int (+) string (8) "HHAHSDHD"
    • Echo calculates the value of the output, such as
echo "Z12" + "34B" + "5" + true;

The result of this printing is

   //0 + 34 + 5 + 1

4. Super keyword

Keywords that can be used in all scenarios such as:

Echo __line__; Output row number of rows
Echo __file__; Output the file address of this file
Function Show () {echo __function__;//output This function name};show (); Output as Show

Sub-Super keyword

echo $_server[' http_user_agent ']; Print server information

Define a class

Class Person {public Function showname () {//Function name is case-insensitive  echo __class__;//print out which class the result is for person  echo __method__; Print out the method of the Class}}

Create an object using this class created

$p = new Person (); Echo $p-showname (); Results for person and Person::showname

5. String

Some common functions of manipulating strings in PHP are introduced.

1. Connection of strings

The output is used when the ". "To connect, as in

$STR = "World"; Echo $str. "Hahaha"; Display as: Worldhahaha

Note: here, use ". "And with", "the connection is visually indistinguishable, but a point connection is the concatenation of two strings into one, and the comma is the two strings simply put together to display it."

2. Get the length of a string
echo strlen ($STR); Display as 5
3. Determine where the substring first appears

To determine where "BC" appears in "AABBCBC"

Echo Strpos ("AABBCBC", "BC");  Output is 5

If case insensitive

Echo Stripos ("AABBCBC", "BC"); Output is 3
4. The concept of binary security

_* Concept:* _ when the string operation, whether to represent the end of the string "\" character to do the processing, is to stop, or continue to check, this feature is inherited C language.

    • _* unsafe: *_ stop because the string behind the \ is not readable
    • _* security: *_ "\" As a character, continue to read down

Example:

echo strcoll ("AAAA", "Aaaa\0asdasds");

Here is an unsafe string-related function that determines whether two strings are equal. As we can see, when we read the second string, the function omits the contents of "\" and evaluates to "0", which is equal.

5. Substitution of strings
$str 1 = "gaoshan@163.com"; Echo str_replace ("G", "s", $str 1); This is a sensitive case of the way Echo str_ireplace ("G", "s", $str 1); This is the case-insensitive way//The results of the above two outputs are: saoshan@163.com
6. Interception of strings

Here we use two methods:

1) substr (string to be processed, intercept from the beginning of the first, intercept several characters)
echo substr ("Hello World", 3, 4); Output is: Lo W
2) Find the position where the string first appears and return the character after it
echo strstr ("Hello World", "Lo"); The output is: Lo World
7. Remove spaces before and after a string
$strT = "        Hello world!!!            "; echo trim ($strT);//output: Hello World!!!
8. String-Case conversions

Small Turn big

$strA = "Fgjhgkbadkahd"; Echo strtolower ($strA); The output results are: Fgjhgkbadkahdecho strtoupper ($strA); The output is: FGJHGKBADKAHD
9. Reverse string
echo strrev ("Hello PHP"); The output is: PHP Olleh
10. Take out the contents of the label/take out the contents with the label
Echo strip_tags ("Tom");//output: Tomecho htmlspecialchars ("Tom");//output: Tom

6. Arrays

1. Creation and printing of arrays
$arr = Array (4, 7, 6, 2, 9); Var_dump ($arr);//output is: Array (5) {[0]=> int (4) [1]=> int (7) [2]=> int (6) [3]=> I NT (2) [4]=> int (9)}
2. Access to array elements
Echo $arr [2]; The output element is: 6
3. Adding an array element
$arr [] = ten; $arr [] = Array (' A ', ' B '); Var_dump ($arr);//output result is; Array (7) {[0]=> int (4) [1]=> int (7) [2]=> int (6) [3]=> int (2) [4]=> int (9) [5]=> Int (ten) [6]=> array (2) {[0]=> string (1) "A" [1]=> string (1) "B"}} print_r ($arr); Functions that are specifically used to output an array are: Array ([0] = 4 [1] = 7 [2] = 6 [3] = 2 [4] = 9 [5] = [6] = = Array ( [0] = a [1] = b))
4. Standard creation and operation of arrays
$arrK =array ("User" = "TOM", "Password" and "123456");p Rint_r ($arrK); The result of the output is: Array ([user] + TOM [password] = 123456) echo $arrK ["User"]; The output is: tom$arrk["sex"] = "male"; $arrK [] = "AAA";p Rint_r ($arrK); The output is: Array ([user] + TOM [Password] = 123456 [sex] = male [0] = AAA)
5. Iterating the array

Connect to 4 code

foreach ($arrK as $key = + $value) {echo $key. The value is: ". $value."
";};

The output is:

The value of user is: The value of Tompassword is: The value of 123456sex is: The value of MALE0 is: AAA
6. Delete a key-value pair in the array

Suppose there's an array like this

$arr = Array ("name" = "Tom", "age" +);p Rint_r ($arr);//output is: Array ([name] + tom [age] +) echo JS On_encode ($arr);//The output is: {"name": "Tom", "Age": 22}//this is to convert the array data into JSON format for easy reading

So if you want to delete the name key value pair in the array

unset ($arr ["name"]);p Rint_r ($arr); The output is: Array ([age] = 22)
7. Length of the array
echo count ($arr);
8. Determine if a value is inside the array

Note: Here is no, refers to the value, "1" and 1 is equivalent. This function will have a Boolean return value.

$arr 1 = Array (3,6,9,5,33, "ten"), Var_dump (In_array ($arr 1)); True
9. Two-dimensional array
$arrT = Array (Array (11,22,33), Array (44,55,66)), Echo $arrT [to]; Print Result: 66
10. Fast-growing into an array
$arrfast 1 = range (1,9);
$arrfast 2 = Range ("A", "a");

7. Forms

How does a php file get information about HTML submissions?

Html:

   
 
         

Php:

 
  

When you submit a submit form in an HTML file, the information is printed in the PHP file.

8. Functions

1. Use of functions

In PHP, the use of functions and JS is basically the same.

Function Show () {echo "AAAA";}; Show ();

With parameters:

function SayHello ($a) {echo "". $a;}; SayHello ("ASDHKASDH");

With return value:

function Retfunc () {return "Lalalala";} Echo Retfunc ();
2. Pass reference parameters

Do not add &, just $a = 20, the value of the 20 is assigned to the function, in the function to change the value of the parameter, the value of the $a is added &, is the address of $ A = 20, assigned to the function parameters, in the function changed the value of the parameter, $a value change

Function Varop (& $c) {$c =40; echo $c;} $a = 20;varop ($a); Echo $a;
3. Assigning default values to function parameters
function Add ($m, $n =9) {echo $m + $n;} Add (3, 4); 3+4add (3); 3+9add (3); Case insensitive

##** four . File control * * Use PHP to control the files within a folder. First, in the same directory, create a file named 11.txt.

1. Open File

$f = fopen ("11.txt", "R");

R is mode, life is the way you can handle files.

Code meaning
"R" Read-only opens, pointing the file pointer to the file header.
"R+" Read-write mode opens, pointing the file pointer to the file header.
"W" The Write method opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.
"W+" Read-write mode opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.
A Write to open, pointing the file pointer to the end of the file. If the file does not exist, try to create it.
"A +" Read-write mode opens, pointing the file pointer to the end of the file. If the file does not exist, try to create it.
"X" Creates and opens in writing, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns false, and generates an E_warning level error message. If the file does not exist, try to create it.
"X+" Creates and opens read-write, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns false, and generates an E_warning level error message. If the file does not exist, try to create it.

2. Reading files

There are four ways to read the file:

1). Read by character
$str = Fread ($f, 3);//What file to read, and how long to read (3 bytes to represent a kanji)

Can get the size of the file, read all

$str = Fread ($f, FileSize ("11.txt"));
2). Read by line
$str = fgets ($f); This is a line echo $str;

Traversing files by row

while ($str =fgets ($f)) {echo $str.
";}
3). Put the file in the array
$arr = File ("11.txt");p Rint_r ($arr);
4). Entire read (fastest)
$str = file_get_contents ("11.txt"); Echo $str;

3. Writing files

A line of writing overwrites the original content, and if the file itself does not exist, a new file is created and then written.

$f = fopen ("11.txt", "w"); Fwrite ($f, "tom\n"); Fwrite ($f, "jerry\n");

If you want to write the entire article:

File_put_contents ("11.txt", "Eat grapes not spit grape skin, do not eat grapes pour spit grape skin");

4. Close the file

It's a good habit to close a file after it's done

Fclose ($f);

5. Copying files

Copy files directly into the original folder

Copy ("11.txt", "22.txt");

6. Renaming files

Rename ("22.txt", "33.txt"); 22.txt renamed to 33.txt

7. deleting files

Unlink ("33.txt"); 33.txt was deleted

##** five . Directory Operations * *

First get the current directory

$d = Opendir (".")//. Represents the current directory,.. Indicates a parent directory

1. Open the current directory

1). read one item in the current directory in turn
$str = Readdir ($d); Echo $str;

If you want to read a few of the contents of the directory sequentially, repeat the above code.

2). Read and print all files in this directory

Loop through the contents of this directory and print

while ($str = Readdir ($d)) {echo $str. "";}
3). Close the folder
Closedir ($d);

2. Get an array of catalog files

 $arr = Scandir (".");   
  for ($i =0; $i 
  
    3. New/Delete a directory (display return value) 
   

New:

var_dump (mkdir ("Test"));//bool (TRUE) 

Delete:

var_dump (RmDir ("Test"));//bool (TRUE) only empty directories can be deleted 
4. Operation URL

First get the basic information of address address in this computer print

 $path = "Http://localhost/PHPSamp Le/dirmanage%e7%9b%ae%e5%bd%95%e6%93%8d%e4%bd%9c.php "; File path 
 $str = basename ($path);//File name 
 $str = DirName ($path); The name of the folder where 
 $newPath = $str. " /login.html "; Using the features of PHP echo, we can stitch the acquired address into a new address to operate the 
 $arr = PathInfo ($path);//To print the relevant information at once /pre> 
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.