Home > Article > Backend Development > Analysis of the impact of magic_quotes_gpc on unserialize in PHP, magicquotesgpc_PHP tutorial
This article analyzes the impact of magic_quotes_gpc on unserialize in PHP. Share it with everyone for your reference. The details are as follows:
magic_quotes_gpc is a function in PHP that adds some security filtering to single and double quotes. However, this function will have some impact on when we use the unserialize function. Let's look at some examples and solutions to this problem.
Yesterday, my friend asked me to help him solve the problem of the shopping cart program on his website. The program uses PHPCMS. It was fine before changing the space. The specific problem is that after successfully adding the shopping cart, it will jump to Shopping cart page, the shopping cart is empty.
I looked at the code. The general principle is to store the product ID and quantity in an array, then serialize it and store it in the COOKIE. Deserialize the COOKIE on the shopping cart page, get this array and read out the corresponding product information. .
After debugging, I found that the problem occurred in unserialize. I first wrote a piece of code based on its shopping cart principle. The code is as follows:
The reason is that when magic_quotes_gpc is turned on, the system will automatically escape and add the single quotes in the result of POST GET COOKIE, so the value of $_COOKIE['cart'] becomes a:1:{i: 0;a:2:{s:8:"goods_id";i:13;s:6:"number";i:1;}}, in this case, unserialize cannot successfully deserialize, and a problem occurs.
The solution is simply to change unserialize($_COOKIE['cart']) to unserialize(stripslashes($_COOKIE['cart'])), add stripslashes before COOKIE, and remove the escape character, so It’ll be no problem.
Let’s do another test on the impact of cookies:
1. Problem: The project data needs to be serialized and stored in a cookie, and then the cookie data is deserialized to obtain the original data. The code is as follows:
2. Analysis, The code is as follows:
① When enabled, stripslashes are required to process data
② When it is not enabled, accept data first addslashes and process data stripslashes
I hope this article will be helpful to everyone’s PHP programming design.