Hi
Now is Friday, the night, because back to the bedroom also seems to have nothing to do, as in the Department of Water a water.
1. PHP
---Cookie---
--Set Cookies:
The most common way to set up cookies in PHP is to use the Setcookie function, Setcookie has 7 optional parameters, which we commonly used for the first 5:
Name (COOKIE name) can be accessed by $_cookie[' name ')
Value (values of the cookie)
Expire (expiry time) UNIX timestamp format, default = 0, indicates that the browser is off and is invalidated
Path (valid path) if the path is set to '/', the entire site is valid
Domain (valid domain) default entire domain name is valid, if ' www.imooc.com ' is set, it is only valid in WWW subdomain
PHP also has a function to set the cookie Setrawcookie,setrawcookie is basically the same as Setcookie, the only difference is that value values are not automatically urlencode, It is therefore necessary to manually carry out the urlencode when needed.
Because cookies are set by HTTP headers, they can also be set directly using the header method.
<?php
$value = time ();
Set up a cookie named Test here
Setcookie ("Test", $value);
if (isset ($_cookie[' test ')) {
echo ' success ';
}
--Delete Cookies
In the previous chapters, we learned about the function of setting cookies, but we found that PHP does not have a function of deleting cookies, and that deleting cookies in PHP is also done using the Setcookie function.
Setcookie (' Test ', ', Time ()-1);
You can see that the cookie expires before the current time, and the cookie is automatically invalidated and the cookie is deleted. The reason for this is that the cookie is passed through the HTTP header, the client sets the cookie based on the Set-cookie segment returned by the server, and if the cookie needs to be implemented with a new Del-cookie, the HTTP header becomes complex. In fact, the cookie can be set up, updated and deleted simply and clearly through Set-cookie.
After understanding the principle, we can also delete cookies directly through the header.
After the test has been removed successfully, the output is
Array (0) {
}
Valid path to--cookie
The path in the cookie is used to control which path the cookie is set to be valid, the default is '/', under all paths, and when another path is set, it is only valid in the path and sub-path set, for example:
Setcookie (' Test ', Time (), 0, '/path ');
The above settings will make test valid under/path and sub-path/PATH/ABC, but the cookie value of test cannot be read in the root directory.
In general, most of the use of all paths, only in a very small number of special needs, will set the path, in this case only in the specified path to pass the cookie value, can save data transmission, enhance security and improve performance .
When we set a valid path, we do not see the current cookie at the current path.
<?php
Complement path parameters to implement valid path settings
Setcookie (' Test ', ' 1 ', 0, '/path ');
Var_dump ($_cookie[' test ');
Output is null
--session (sessions) and cookies
Cookies store data on the client and establish a connection between the user and the server, which can often solve many problems, but the cookie still has some limitations:
Cookies are relatively less secure and easily compromised to cause cookie spoofing
The maximum value of a single cookie can only be stored 4k
Network transfer for each request, consuming bandwidth
Session data is stored on the server server, no size limit, through a session_id user identification, PHP by default, the session ID is saved through a cookie, so in a way, seesion relies on cookies. But this is not absolute, the session ID can also be implemented by parameters, as long as the session ID can be passed to the server to identify the mechanism can use the session.
--Using session
Using the session in PHP is very simple, first executing the Session_Start method to open the session, and then through the global variable $_session session read and write.
Session_Start (); $_session[' test '] = time (); Var_dump ($_session);
The session automatically encode and decode the values to be set, so the session can support any data type, including data and objects.
Session_Start (); $_session[' ary '] = array (' name ' = ' Jobs '); $_session[' obj '] = new StdClass (); Var_dump ($_session);
By default, the session is stored as a file on the server, so when a page opens the session, it will monopolize the session file, which will cause other concurrent accesses of the current user to be unable to execute and wait. This can be solved in the form of cache or database storage, which we'll cover in some advanced courses.
Note: Session_Start is a function
--Delete and destroy session
Deleting a session value can use PHP's unset function, which is removed from the global variable $_session and cannot be accessed.
Session_Start (); $_session[' name '] = ' jobs '; unset ($_session[' name '); Echo $_session[' name ']; Hint name does not exist
If you want to delete all sessions, you can use the Session_destroy function to destroy the current Session,session_destroy delete all data, but session_id still exists.
Session_Start (); $_session[' name '] = ' jobs '; $_session[' time ' = time (); Session_destroy ();
It is important to note that Session_destroy does not immediately destroy the value in the global variable $_session, but only when the next time it is accessed, $_session is empty, so if you need to destroy $_session immediately, you can use the unset function.
Session_Start (); $_session[' name '] = ' jobs '; $_session[' time ' = time (); unset ($_session); Session_destroy (); Var_dump ($_session); This is now empty
If it is necessary to destroy the session_id in the cookie at the same time, usually when the user exits, it is also necessary to explicitly call the Setcookie method to remove the session_id cookie value.
--use session to store user's login information
Session can be used to store multiple types of data, so it has a lot of uses, commonly used to store user login information, shopping cart data, or some temporary use of staging data.
After the user has successfully logged in, the user's information can usually be stored in the session, the general will separate some important fields stored separately, and then all the user information stored independently.
$_session[' uid '] = $userinfo [' uid '];$_session[' userinfo '] = $userinfo;
In general, the login information can be stored in the Sessioin, but also stored in the cookie, the difference between them is that the session can easily access a variety of data types, and the cookie only supports string type, while for some security relatively high data, Cookies need to be formatted and encrypted, and session storage is more secure on the server side.
<?php
Session_Start ();
Assuming the user is logged on successfully, the following user data is obtained
$userinfo = Array (
' UID ' = 10000,
' Name ' = ' spark ',
' Email ' = ' [email protected] ',
' Sex ' = ' man ',
' Age ' = ' 18 '
);
Header ("content-type:text/html; Charset=utf-8 ");
/* Save the user information to the session */
$_session[' uid '] = $userinfo [' uid '];
$_session[' name '] = $userinfo [' name '];
$_session[' userinfo '] = $userinfo;
echo "Welcome". $_session[' name ']. ' <br> ';
* A simple way to save user data to a cookie */
$secureKey = ' IMOOC '; Encryption key
$str = serialize ($userinfo); Serialization of user information
echo "User information before encryption:". $str;
$str = Base64_encode (Mcrypt_encrypt (mcrypt_rijndael_256, $secureKey, $str, MCRYPT_MODE_ECB));
echo "User Information encrypted:" $STR;
Store encrypted user data in a cookie
Setcookie (' UserInfo ', $str);
Decrypt when needed for use
$str = Mcrypt_decrypt (mcrypt_rijndael_256, $secureKey, Base64_decode ($STR), MCRYPT_MODE_ECB);
$uinfo = Unserialize ($STR);
echo "Decrypted user information:<br>";
Var_dump ($uinfo);
--Summary
Setcookie (), Setsession (), unset ()
----File System----
--Read File contents
PHP has a rich file operation function, the simplest function to read the file is file_get_contents, you can read the entire file into a string.
$content = file_get_contents ('./test.txt ');
The file_get_contents can also control the start point and length of the content through parameters.
$content = file_get_contents ('./test.txt ', NULL, NULL, 100, 500);
PHP also provides a method similar to the C language operation file, using methods such as Fopen,fgets,fread, fgets can read a line from the file pointer, Freads can read a string of a specified length.
$fp = fopen ('./text.txt ', ' RB '), while (!feof ($fp)) {echo fgets ($FP);//reads a row of}fclose ($FP);
$fp = fopen ('./text.txt ', ' RB '); $contents = "; while (!feof ($fp)) {$contents. = Fread ($fp, 4096);//read 4,096 characters at a time}fclose ($f p);
Using the fopen open file, it is best to use fclose to close the file pointer to avoid the file handle being occupied.
--Determine if a file exists, is readable, can be written
In general, in the operation of the file needs to determine the existence of the file, PHP commonly used to determine the existence of a file function has two is_file and file_exists.
$filename = './test.txt '; if (file_exists ($filename)) {echo file_get_contents ($filename);}
If you just judge the existence of the file, use file_exists on the line, file_exists can not only determine whether the file exists, but also can determine whether the directory exists, from the function name can be seen, Is_file is the exact decision to determine whether a given path is a file.
$filename = './test.txt '; if (Is_file ($filename)) {echo file_get_contents ($filename);}
It is more accurate to use is_readable and is_writeable to determine whether a file is readable or writable, based on whether the file exists.
$filename = './test.txt '; if (is_writeable ($filename)) {file_put_contents ($filename, ' Test ');} if (is_readable ($filename)) {echo file_get_contents ($filename);}
--Write content
As with the read file, PHP writes a file in two ways, the simplest way is to use file_put_contents.
$filename = './test.txt '; $data = ' Test '; file_put_contents ($filename, $data);
In the example above, the $data parameter can be a one-dimensional array, and when $data is an array, the array is automatically concatenated, equivalent to$data=implode(‘‘, $data);
Similarly, PHP supports a C language style of operation, using fwrite for file writing.
$fp = fopen ('./test.txt ', ' W ');
Fwrite ($fp, ' hello ');
Fwrite ($FP, ' World '); fclose ($FP);
--Get the file modification time
The file has many meta attributes, including: The owner of the file, creation time, modification time, last access time, and so on.
Fileowner: Get the file owner filectime: Get File creation time Filemtime: Get File modification time Fileatime: Get file access time
One of the most commonly used is the file modification time, through the file modification time, you can judge the timeliness of the file, often used in static files or cached data updates.
$mtime = Filemtime ($filename); Echo ' Modified time: '. Date (' y-m-d h:i:s ', Filemtime ($filename));
<?php
$filename = '/data/webroot/usercode/code/resource/test.txt ';
Echo ' owner: '. Fileowner ($filename). ' <br> ';
Echo ' creation time: '. Filectime ($filename). ' <br> ';
Echo ' Modified time: '. Filemtime ($filename). ' <br> ';
Echo ' Last access time: '. Fileatime ($filename). ' <br> ';
Assigning $mtime to a file modification time
$mtime = Filemtime ($filename);
Determine whether the file content is valid by calculating the time difference
if (Time ()-$mtime > 3600) {
Echo ' <br> cache expired ';
} else {
Echo file_get_contents ($filename);
}
--Get the size of the file
The size of the file can be obtained through the FileSize function, and the file size is expressed as a number of bytes.
$filename = '/data/webroot/usercode/code/resource/test.txt '; $size = FileSize ($filename);
If you want to convert the units of a file size, you can define your own function to implement it.
function GetSize ($size, $format = ' kb ') { $p = 0; if ($format = = ' kb ') { $p = 1; } elseif ($format = = ' mb ') { $p = 2; } elseif ($format = = ' GB ') { $p = 3; } $size/= Pow (1024x768, $p); Return Number_format ($size, 3);} $filename = '/data/webroot/usercode/code/resource/test.txt '; $size = FileSize ($filename); $size = GetSize ($size, ' KB '); Perform unit conversions Echo $size. ' KB ';
It is important to note that there is no simple function to get the size of the directory, the size of the directory is the sum of all subdirectories and the size of the file, so the recursive way to calculate the size of the directory.
--Delete Files
Similar to UNIX system commands, PHP uses the unlink function for file deletion.
Unlink ($filename);
To delete a folder use the RmDir function, the folder must be empty, and if it is not empty or does not have permission, the prompt fails.
RmDir ($dir);
If a file exists in the folder, you can cycle through all the files in the directory and then delete the directory, and the loop delete can use the Glob function to traverse all the files.
foreach (Glob ("*") as $filename) { unlink ($filename);}
--Summary
File_get_contents (), file_exists (), Is_file (), is_writeable (), is_readable ()
File_put_contents (), Filemtime (), FileSize (), unlink ()
---date and time---
--Get the current UNIX timestamp
The UNIX timestamp (called: timestamp) is a very important concept in PHP for time and date, which represents the sum of the seconds from January 1, 1970 00:00:00 to the current time.
PHP provides a built-in function time () to get the timestamp of the current time of the server. It is easy to get the current UNIX timestamp.
$time = time (); Echo $time;//1396193923, this number represents 1,396,193,923 seconds from January 1, 1970 00:00:00 When I output this script.
Time stamp, indicating point in time
--
Get the current date
PHP has a date () function built into it to get the current day.
Function Description: Date (timestamp format, specified timestamp "default is the current date and time, optional")
Return value: function date and time
Example://date function, the second parameter takes a default value case
echo Date ("y-m-d");//2014-03-30//date function, the second parameter has a value in the case of Echo date ("y-m-d", ' 1396193923 ');// 2014-03-30,1396193923 represents the Unix timestamp of 2014-03-30--
--
Unix timestamp of date acquired
The UNIX timestamp (called: timestamp) is a very important concept in PHP for time and date, which represents the sum of the seconds from January 1, 1970 00:00:00 to the current time.
PHP provides built-in function Strtotime implementations: Gets the timestamp of a date, or gets the timestamp of a time. For example:
echo strtotime (' 2014-04-29 ');//1398700800, this figure represents 1,398,700,800 seconds from January 1, 1970 00:00:00 to April 29, 2014. Echo strtotime (' 2014-04-29 00:00:01 ');//1398700801, this number means it's been 1,398,700,801 seconds since January 1, 1970 00:00:00 to 2014-04-29 00:00:01. Have you found the pattern? In fact strtotime (' 2014-04-29 ') is equivalent to Strtotime (' 2014-04-29 00:00:00 ')
--
Converts a formatted date string to a Unix timestamp
The Strtotime function expects to accept a string containing the U.S. English date format and attempt to resolve it to a Unix timestamp.
Function Description: Strtotime (time string to parse, calculates the timestamp of the return value "default is the current time, optional")
Return value: Success returns timestamp, otherwise FALSE
Like what
Echo Strtotime ("Now"), or//is equivalent to the current date and time of the English word, and converts the date time to a Unix timestamp. This effect is the same as echo time (). Echo strtotime ("+1 seconds") is equivalent to adding the current date and time to 1 seconds and converting the date time to a Unix timestamp. This effect is the same as echo time () +1. Echo strtotime ("+1 Day"), or the equivalent of adding the current date and time to 1 days. Echo strtotime ("+1 Week");//equivalent to the current date and time is added 1 weeks. Echo strtotime ("+1 Week 3 days 7 hours 5 Seconds"), or//equivalent to the current date and time is added 1 Weeks 3 day 7 hours 5 seconds.
--
Format Greenwich (GMT) Standard Time
The Gmdate function can format a GMT date and time, returning Greenwich Mean Time (GMT).
For example, we are now in the China time Zone is East eight, leading GMT 8 hours, sometimes called gmt+8, then the server run the following script to return the time should be this: the current time is assumed to be 2014-05-01 15:15:22echo date (' y-m-d H: I:s ', Time ()); The output is: 2014-05-01 15:15:22 echo gmdate (' y-m-d h:i:s ', Time ()); The output is: 2014-05-01 07:15:22 because GMT is now in China time zone minus 8 hours, so compared to the present time is less than 8 hours
----Graphic image Manipulation----
--GD Library
Graphic Device,php's GD library is an extended library for processing graphics, often used to process watermarks and generate verification codes.
PHP By default installed the GD library, installation needs to open
--
Draw lines
To manipulate a graphic, start by creating a new canvas, and you can create a blank picture of a true color with the Imagecreatetruecolor function:
$img = Imagecreatetruecolor (100, 100);
The color of the brush used in the GD library needs to be assigned through the Imagecolorallocate function, and the color value of the RGB is determined by the parameter setting:
$red = Imagecolorallocate ($img, 0xFF, 0x00, 0x00);
We then draw the line by calling the draw segment function Imageline, and finally get the line by specifying a starting point and ending point.
Imageline ($img, 0, 0, +, +, $red);
After the line is drawn, the output of the image is done through the header and Imagepng.
Header ("Content-type:image/png"); Imagepng ($img);
Finally, you can call Imagedestroy to release the memory that the picture occupies.
Imagedestroy ($IMG);
Through the above steps, you can find PHP drawing is very simple, but many times we do not just need to output images, perhaps we also need to get a picture file, can be specified by the Imagepng function file name after the image is saved to the file.
Imagepng ($img, ' img.png ');
<?php
$img = Imagecreatetruecolor (100, 100);
$red = Imagecolorallocate ($img, 0xFF, 0x00, 0x00);
Use Imageline to draw lines here
Imageline ($img, 0,10,90,80, $red);
Header ("Content-type:image/png");
Imagepng ($IMG);
Imagedestroy ($IMG);
--
Draw text in an image
GD library can be used for the basic operation of a variety of graphics, often have drawn lines, background fill, draw rectangles, draw text and so on.
Like drawing a line, you first need to create a new picture and initialize the color.
$img = Imagecreatetruecolor (+), $red = Imagecolorallocate ($img, 0xFF, 0x00, 0x00);
The imagestring function is then used to draw the text, which has many parameters: imagestring (resource $image, int $font, int $x, int $y, string $s, int $col), which can be To set the font size by $font, X, Y sets the position of the text display, $s the text to be drawn, $col is the color of the text.
Imagestring ($img, 5, 0, 0, "Hello World", $red), header ("Content-type:image/png"), Imagepng ($img); Imagedestroy ($img);
--
Output image File
As we have learned earlier, the image can be output directly to the browser via Imagepng, but many times we want to save the processed image to a file so that it can be used multiple times. Saves the image to a file by specifying a path parameter.
$filename = ' img.png '; Imagepng ($img, $filename);
Use Imagepng to save images in PNG format, if you want to save to other formats using different functions, using imagejpeg to save the picture in JPEG format, imagegif Save the picture to GIF format, you need to note that Imagejpeg compresses the picture, so you can also set a quality parameter.
$filename = ' img.jpg ';? Imagejpeg ($img, $filename, 80);
--
Generate an Image verification code
The simple verification code is actually the output of a few characters in the image, through the imagestring function described in the previous section can be achieved.
But in the processing, in order to make the verification code more secure, prevent other programs to automatically recognize, so often need to do some interference processing of verification code, usually by drawing some noise, interfering with line segments, the output of the characters to tilt, distort and other operations.
You can use Imagesetpixel to draw points to achieve noise disturbances, but drawing only one point is not very useful, so it is often used for random plotting using loops.
<?php
$img = Imagecreatetruecolor (100, 40);
$black = Imagecolorallocate ($img, 0x00, 0x00, 0x00);
$green = Imagecolorallocate ($img, 0x00, 0xFF, 0x00);
$white = Imagecolorallocate ($img, 0xFF, 0xFF, 0xFF);
Imagefill ($img, 0,0, $white);
Generate a random verification code
$code = ";
for ($i = 0; $i < 4; $i + +) {
$code. = rand (0, 9);
}
Imagestring ($img, 5, ten, $code, $black);
Add noise interference.
for ($i =0; $i <50; $i + +) {
Imagesetpixel ($img, rand (0, +), rand (0, +), $black);
Imagesetpixel ($img, rand (0, +), rand (0, +), $green);
}
Output Verification Code
Header ("Content-type:image/png");
Imagepng ($IMG);
Imagedestroy ($IMG);
--
Add a watermark to a picture
There are two ways to add a watermark to a picture, one is to put a string on top of the picture, and the other is to include a logo or other image on the image.
Because this is a picture that already exists, you can create a canvas directly from an existing image, creating an image directly from the image file via Imagecreatefromjpeg.
$im = Imagecreatefromjpeg ($filename);
After creating the image object, we can draw the string to the image through the previous GD function. If the watermark to be added is a logo image, then you need to create an image object, and then through the GD function imagecopy to copy the image of the logo to the source image.
$logo = Imagecreatefrompng ($filename); Imagecopy ($im, $logo, 0, 0, $width, $height);
When the logo image is copied to the original image, the watermark will be added after the output of the image to complete the watermark processing.
Imagejpeg ($im, $filename);
<?php
This is just for the case. To prepare some pictures of the material
$url = ' http://www.iyi8.com/uploadfile/2014/0521/20140521105216901.jpg ';
$content = file_get_contents ($url);
$filename = ' tmp.jpg ';
File_put_contents ($filename, $content);
$url = ' http://wiki.ubuntu.org.cn/images/3/3b/Qref_Edubuntu_Logo.png ';
File_put_contents (' Logo.png ', file_get_contents ($url));
Start adding a watermark operation
$im = Imagecreatefromjpeg ($filename);
$logo = imagecreatefrompng (' logo.png ');
$size = getimagesize (' logo.png ');
Imagecopy ($im, $logo, 0, 0, $size [0], $size [1]);
Header ("Content-type:image/jpeg");
Imagejpeg ($im);
-----Exception Handling-----
--
Throws an exception
Starting with PHP5, PHP supports exception handling, exception handling is an object-oriented feature, PHP code exceptions are thrown by throw, exception throws, the subsequent code will not be executed again.
Since throwing an exception interrupts program execution, why do you need to use exception handling?
Exception throws are used to notify the client when an unknown error is encountered, or if a pre-set condition is not met, so that other related processing can be done without causing the program to interrupt directly.
When a try catch is used in the code, the thrown exception is caught in the catch, otherwise it is interrupted directly.
1. Basic grammar
try{
Code with errors or exceptions that may occur
Catch represents capture, exception is a defined exception class for PHP
} catch (Exception $e) {
For exception handling, method:
1, self-treatment
2. Do not process, throw it again
}
2. Processing procedures shall include:
Try-the function that uses the exception should be in the "try" code block. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown.
Throw-this specifies how the exception is triggered. Note: Each "throw" must correspond to at least one "catch", which can of course correspond to multiple "catch"
Catch-The catch code block catches the exception and creates an object that contains the exception information.
Create a function Checknum () { if (>1) { throw new Exception ("exception hint-number must be less than or equal to 1") that throws an exception; } return true; }//Trigger exception in "Try" code block try{ checknum (2); If the exception is thrown, then the following line of code will not be output echo ' If you see this hint, your number is less than or equal to 1 ';} catch (Exception $e) { //catch exception echo ' catch exception: '. $e->getmessage ();}
The above code will get an error like this:
Catch exception:: Exception hint-number must be less than or equal to 1
Example Explanation:
The above code throws an exception and captures it:
Create the Checknum () function. It detects if the number is greater than 1. If it is, an exception is thrown.
Call the Checknum () function in the "Try" code block.
The exception in the Checknum () function is thrown
The catch code block receives the exception and creates an object ($e) that contains the exception information.
Output the error message from this exception by calling $e->getmessage () from this exception object
<?php
$filename = ' test.txt ';
try {
if (!file_exists ($filename)) {
throw new Exception (' file does not exist ');
}
} catch (Exception $e) {
echo $e->getmessage ();
}
--Exception Handling class
PHP has many exception handling classes, where exception is the base class for all exception handling.
Exception has several basic properties and methods, including the following:
Message content for exception messages
Code exception Codes
File name that throws an exception
Line throws an exception in the number of lines of the file
Among the methods commonly used are:
Gettrace getting exception tracking information
Gettraceasstring string that gets the exception trace information
GetMessage getting error messages
If necessary, you can create a custom exception-handling class by inheriting the exception class.
Custom exception class, inherited PHP exception base class Exceptionclass MyException extends Exception { function getInfo () { return ' custom error message '; }} The try { //function that uses the exception should be in the "try" code block. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown. throw new MyException (' Error ');//This specifies how to trigger an exception. Note: Each "throw" must correspond to at least one "catch", which can of course correspond to multiple "catch"} catch (Exception $e) {//"catch" code block catches an exception and creates an object containing the exception information Echo $e- >getinfo ();//Gets the custom exception information echo $e->getmessage ();//Gets GetMessage information inherited from the base class}
<?php
Class MyException extends Exception {
function GetInfo () {
Return ' custom error message ';
}
}
try {
throw new MyException (' Error ');
} catch (Exception $e) {
echo $e->getinfo ();
}
--
Catching exception information
After understanding the fundamentals of exception handling, we can catch exceptions by try catch, we put the executed code in the try code block, and once the code in it throws an exception, it can be caught in the catch.
Here we just through the case to understand the mechanism of the try catch and the method of exception capture, in practical applications, will not easily throw exceptions, only in extreme situations or very important circumstances, will throw an exception, throw an exception, can guarantee the correctness and security of the program, avoid causing unpredictable bugs.
The general exception handling process code is:
try { throw new Exception (' wrong '),} catch (Exception $ex) {echo ' Error: '. $ex->getmessage (). ' <br> '; echo $ex->gettraceasstring (). ' <br> ';} Echo ' exception handling, continue to execute other code ';
<?php
try {
throw new Exception (' wrong ');
} catch (Exception $ex) {
Echo ' Error: '. $ex->getmessage (). ' <br> ';
echo $ex->gettraceasstring (). ' <br> ';
}
Echo ' exception handling, continue to execute other code ';
--
Gets the row where the error occurred
After the exception is captured, we can get the exception information through the exception handling object, we already know the way to capture, and get the basic error information.
In real-world applications, we usually get enough exception information and write it to the error log.
We need to record the file name, line number, error message, exception tracking information, etc. to the log in order to debug and fix the problem.
<?php
try {
throw new Exception (' wrong ');
} catch (Exception $ex) {
$msg = ' Error: '. $ex->getmessage (). " \ n ";
$msg. = $ex->gettraceasstring (). " \ n ";
$msg. = ' exception line number: '. $ex->getline (). " \ n ";
$msg. = ' where file: '. $ex->getfile (). " \ n ";
Logging exception information to the log
File_put_contents (' Error.log ', $msg);
}
Boring Friday night.