Web typical application technology in PHP

Source: Internet
Author: User
Tags php session setcookie

There are 5 main areas to be talked about:
    1. PHP interaction with Web pages: Table only son value, file upload and download
    2. HTTP protocol
    3. PHP Session Technology: Cookies and session
    4. PHP Image technology: GD Library, image of the common production and operation, verification code, QR Code, watermark, thumbnail, 3D diagram and so on
    5. File operations: Open, close, read files, write files, traverse directories, etc.
One, PHP and Web page interaction: Table only son value, file upload and download 1, table only son value

1.1. Radio Box

Single.html

<! DOCTYPE html>
<title> single option pass value </title>
<meta charset= "Utf-8" >
<body>
<form method= "GET" action= "single.php" >
<p> Username: <input type= "text" name= "username"/></p>
<p>
Gender
<input type= "Radio" name= "Gender" value= "1"/> Male
<input type= "Radio" name= "Gender" value= "2"/> Female
<input type= "Radio" name= "Gender" value= "3"/> Secrecy
</p>
<p> Password: <input type= "password" name= "password"/></p>
<p><input type= "Submit" value= "Submission" ></p>
</form>
</body>

single.php

<?php

Header (' Content-type:text/html;charset=utf8 ');
Echo ' <pre> ';
Var_dump ($_get);

Note:

    • The name value of a group of choices must be the same;
    • You must have the Value property, and the Value property cannot be the same.

1.2. Multi-select box

Muliselect.html

<! DOCTYPE html>
<title> single option pass value </title>
<meta charset= "Utf-8" >
<body>
<form method= "POST" action= "muliselect.php" >
<p> Username: <input type= "text" name= "username"/></p>
<p>
Hobby
<input type= "checkbox" Name= "hobby[" value= "singing" > Singing
<input type= "checkbox" Name= "hobby[" value= "Dance" > Dance
<input type= "checkbox" Name= "hobby[]" value= "movie" > Movie
<input type= "checkbox" Name= "hobby[]" value= "basketball" > Basketball
</p>
<p><input type= "Submit" value= "Submission" ></p>
</form>
</body>

muliselect.php

<?php

Header (' Content-type:text/html;charset=utf8 ');
/*echo ' <pre> ';
Var_dump ($_post); * *
1, connecting the database
mysql_connect (' localhost:3306 ', ' root ', ' aaa ');
mysql_query (' Set names UTF8 ');
mysql_query (' use php2018 ');
2, receive data
$user _name = Trim ($_post[' username ');
$user _gender = $_post[' gender ');
$hobby = $_post[' hobby ');
$user _password = MD5 (Trim ($_post[' password '));

Convert an array to a string to write to the database
$user _hobby = Implode (', ', $hobby);

3, Data warehousing
$sql = "INSERT INTO user values
(NULL, ' $user _name ', ' $user _gender ', ' $user _hobby ', ' $user _password ') ";

$result = mysql_query ($sql);

if ($result) {
echo ' Insert success ';
}else {
Echo ' Insert failed ';
}

/*create Table User (
user_id int primary Key auto_increment,
User_name varchar () NOT NULL default ' anonymous ',
User_gender enum (' 1 ', ' 2 ', ' 3 ') Comment ' 1 is male 2 is female 3 is confidential ',
User_hobby set (' Sing ', ' Dance ', ' movie ', ' Basketball '),
User_password Char (32)
);*/

Note:

    • When we use PHP to get the value of a multi-box, we get an array;
    • When we deposit the value of a multi-box into a database, we need to divide the obtained array into a string with the implode () function and then into the database.
2. File Upload

Implement file uploads, by following these steps:

1), on the server side to open the file upload function;

2), on the browser side to provide the ability to upload files form. The fact is to add properties to the form: enctype= "Multipart/form-data";

3), the use of $_files to receive uploaded documents related information;

4), verification documents;

5), move the files from the temporary folder to the specified directory.

In fact, the use of a function: Move_upload_file (temporary file name, the target directory and file name); There is a return value, if the upload succeeds returns true, otherwise it returns false;

PHP default upload temporary folder is under the C disk, and sometimes because of permissions issues will cause upload failure, so we generally modify the uploaded temporary folder.

Encapsulate File Upload function

upload.php

<?php

# File Upload function

/**

* File Upload

* @param array $file upload the file information (is an array, there are 5 elements)

* @param array $allow file upload type

* @param string & $error reference type to log error messages

* @param string $path File upload path

* @param int $maxsize = 2*1024*1024 the size of the file allowed to upload

* @return false| $newname returns False if the upload fails, and returns the new name of the file if successful

*/

function upload ($file, $allow,& $error, $path, $maxsize =2097152) {

# 1, Judging system errors

Switch ($file [' ERROR ']) {

Case 1:

$error = ' upload error, beyond the size of the file limit! ‘;

return false;

Case 2:

$error = ' upload error, beyond the size allowed by the form! ‘;

return false;

Case 3:

$error = ' upload error, file upload is incomplete! ‘;

return false;

Case 4:

$error = ' Please select the file you want to upload first! ‘;

return false;

Case 6:

Case 7:

$error = ' Sorry, the server is busy, please try again later! ‘;

return false;

}

# 2, Judging logic errors

2.1. Determine file size

if ($file [' Size '] > $maxsize) {

$error = ' exceeds the file size, the maximum allowable value is: '. $maxsize. ' bytes ';

return false;

}

2.2. Determine file type

if (!in_array ($file [' type '], $allow)) {

Illegal file type

$error = ' The uploaded file type is incorrect, the allowed type is: '. Implode (', ', $allow);

return false;

}

# 3, get the new name of the file

$newname = Randname ($file [' name ']);

# 4, move temporary files to the specified path

$target = $path. ‘/‘ . $newname;

if (Move_uploaded_file ($file [' Tmp_name '], $target)) {

return $newname;

}else {

$error = ' An unknown error occurred and the upload failed! ‘;

return false;

}

}

# define a function that produces a random name

/**

* @param the old name of the string $filename file

* @param a new name for string $newname file

*/

function Randname ($filename) {

The time portion of the generated file name

$newname = Date (' Ymdhis ');

Plus a random six-digit number.

$str = ' 0123456789 ';

Get six-bit random numbers

for ($i =0; $i < 6; $i + +) {

Add the random number you get to the new name

$newname. = $str [Mt_rand (0,strlen ($STR))];

}

Plus suffix name

$newname. = STRRCHR ($filename, '. ');

return $newname;

}

?>

3. File download

Ii. HTTP protocol 1, Request protocol

1.1. Composition: Request line, request header, blank line, request data

1.1.1, request line. Divided into three parts: request mode, request path, protocol version

1.1.2, request header.

The request header is the collection of all the protocol entries that are currently needed!

The protocol is the browser in the request server in advance to tell the server some information, and each of the protocol entries to occupy a single line!

Common Request headers:

      • Host: the hostname (domain name) of the server to be requested in the current URL
      • Accept-encoding: is the browser sent to the server, declaring that the browser supports the type of compression encoding such as gzip
      • Accept_charset: Indicates that the browser supports the character set
      • Referer: Which URL is this request from?
      • Accept-language: Types of languages that can be received, cn,en, etc.
      • Cookies:
      • User-agent: User agent, kernel information for the browser that is currently initiating the request
      • Accept: Indicates the type of data that the browser can receive, text/html,image/img
      • Content-length (POST): A request header only when Post is submitted, showing the current committed data length (bytes)
      • If-modified-since (GET): asks if the resource file has been modified when the client requests a resource file from the server
      • Content-type (POST): Defines the type of network file and the encoding of the Web page, and determines what form and encoding the browser will use to read the file

1.1.3, empty line

Used to separate the request header from the request data, meaning that the request header is over!

1.1.4, request data

2. Response Agreement

2.1. Composition: Response line, response header, blank line, response body

Iii. session Technology 1, cookies

1.1. Basic operation

      • Additions and deletions: Setcookie (name, value)
      • Check: $_cookie

1.2. Properties

      • Validity period: The default one session cycle. Can be set by Setcookie the third parameter;
      • Valid path: The default current directory and its subdirectories. Can be set by a fourth parameter;
      • Valid domain: The default current site (subdomain), can be set by the fifth parameter;
      • Safe Transfer only: Default no, sixth parameter setting;
      • HttpOnly: Default No, the seventh parameter is set.

1.3. Precautions

      • The value of the cookie, which only supports string types;
      • The key (subscript) of a cookie can be written in the form of an array subscript.
2. Session

2.1. Basic operation

Additions and deletions are done through the $_session array.

2.2. Properties

The implementation of the session requires the support of a cookie, which has the same properties as the cookie.

2.3. Precautions

      • Session data can be any type of data (a cookie can only be a string type)
      • $_session the subscript of an array element can only be a string type (associative type), not an indexed array

2.4, the session of the destruction

      • Unset (): Destroys a data in session, and does not destroy the conversation data area;
      • $_session = ARRAY (): Clears the $_session and does not destroy the session data area;
      • Session_desroy ((): Destroys session data area.
3. The difference between a cookie and a session
Cookies Session
Storage location Browser-side Server-side
Data volume Big Small
Types of data stored can only be a string Any type
Security Lower Higher
The default valid path Can only be the current directory and its subdirectories The whole station is valid

Four, image technology 1, GD picture production

1.1. Create a canvas

Imagecreatetruecolor (Width,height);

1.2. Create a brush color

Imagecolorallocate (Img,red,green,blue);

1.3. Draw the text (draw on the canvas)

Imagestring (Img,size,x,y,string,color);

1.4. Output or save pictures

      • Output: imagepng (image Resource);

Before you output:

1), set the response header information: header ("Content-type:image/png");

2), clear buffer data: Ob_clean ();

      • Save: Imagepng (Picture resource, path/Picture name);
2. Implement verification Code

<?php

# 1. Create a canvas

$canWidth = 170; The width of the canvas

$canHei = 40; The height of the canvas

$img = Imagecreatetruecolor ($canWidth, $canHei);

# 2. Fill the canvas with the background color

$bgColor = Imagecolorallocate ($img, Mt_rand (0,120), Mt_rand (0,120), Mt_rand (0,120));

Imagefill ($img, 1, 1, $bgColor);

#/3, defining the display text on the canvas

Displays the range of random characters

$arr = Array_merge (range (' A ', ' Z '), Range (' A ', ' Z '), range (0, 9));

A random character that gets the specified number of digits

$str = ";

Shuffle ($arr);

$charNum = 4; Number of verification codes

$KEYARR = Array_rand ($arr, $charNum);

foreach ($keyArr as $value) {

$str. = $arr [$value];

}

4. Writing characters to the canvas

$span = Ceil ($canWidth/($charNum + 1));

for ($i =1; $i <= $charNum; $i + +) {

Create a brush color for the canvas

$charColor = Imagecolorallocate ($img, Mt_rand (120,255), Mt_rand (120,255), Mt_rand (120,255));

Imagestring ($img, 5, $span * $i, N, $str [$i-1], $charColor);

}

5. Create interference lines

for ($i =0; $i < 8; $i + +) {

Create Interference line Colors

$linColor = Imagecolorallocate ($img, Mt_rand (75,150), Mt_rand (75,150), Mt_rand (75,150));

Create a disturbance line

Imageline ($img, Mt_rand (0, $canWidth-1), Mt_rand (0, $canHei-1), Mt_rand (0, $canWidth-1), Mt_rand (0, $canHei-1), $ Lincolor);

}

6. Display pictures

Header (' content-type:image/png ');

Ob_clean ();

Imagepng ($IMG);

?>

V. File operation 1, Directory basic operation
      • Create directory: mkdir (directory address and name, permissions);
      • Delete Delete: rmdir (directory address);
      • Move/Rename Directory: rename (original file path, new file path);

(The move here is essentially renaming, but the name of the directory is not just the file name, but also the path to the directory, when we change the path of the directory, it is both a mobile directory, can be said to be renamed;)

      • Get Directory Contents:
    1. Open Directory, Opendir, get a directory handle (directory resource);
    2. Read the files in the directory sequentially, Readdir;
    3. Close the directory handle (CLOSEDIR);

1.2. Common Directory operation function

      • GETCWD: Gets the current working path;
      • ChDir: Change the current working path;
      • Rewinddir: Resets the resource pointer back to the first one;
      • Scandir: Browses a directory and returns the contents of the directory as an indexed array.

1.3. Recursively traverse the directory

bianli.php

<?php

/**

* Recursive traversal of files

* @param string $path directory path (address)

* @param int $deep = 0 Depth of current directory

*/

function Readdirs ($path, $deep =0) {

$dir _handle = Opendir ($path); Get the handle to the $path directory

while (false!== $file = ReadDir ($dir _handle)) {

Filter out./And.. /

if ($file = = "." | | $file = = "..") {

Continue

}

Output file

Echo str_repeat ('-', $deep), $file, ' <br/> ';

Enter recursive points and recursive exits

if (Is_dir ($path. '/'. $file)) {

Readdirs ($path. '/'. $file, $deep + 1);

}

}

}

$path = './';

Readdirs ($path);

?>

2. File operation

2.1, the basic operation of the file

      • READ: file_get_contents; reads the file contents of the specified path, returning as a string;
      • Write: file_put_contents; Overwrite writes, writes the specified data to the specified file and overwrites the previous content. If you need to append data, you need to set a third parameter file_append;

2.2. Common file functions

      • filetype: Gets the type of a file. There are three types of files under Windows, dir, file, unknown.
      • File_exists: Determine if a file exists;
      • Is_dir: Determine if a file is a dir file;
      • Is_file: Determine if a file is file;

Web typical application technology in PHP

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.