Common business logic in PHP

Time:2021-7-27

How does PHP split and merge files when operating breakpoint continuation

To realize breakpoint continuation in PHP, you need to divide a large file into multiple small files, and then upload them individually. Merge after transfer.

│ merge.php – merge file script  \

│ merge.zip – merged file  \

│ socket.zip – files to be split  \

│ split.php – split file script  \


│ \

└ – split – small file directory after splitting

split.php

<?php
$fp = fopen("socket.zip", "rb");
$filesize = 10;
$i = 0;
$no = 1;
while(!feof($fp))
{
  $file = fread($fp, $filesize);
  $fp2 = fopen("./split/socket.port".sprintf("%04d",$no).".".$i."-".($i+$filesize).".tmp", "wb");
  fwrite($fp2, $file, $filesize);
  fclose($fp2);
  $i+=$filesize+1;
$no++;
}
fclose($fp);

merge.php

<?php
$filelist = glob('./split/*socket*.tmp');
$filesize = 10;
//print_r($filelist);
$mergeFileName = 'merg.zip';
unlink($mergeFileName);
  $fp2 = fopen($mergeFileName,"w+");
foreach($filelist as $k => $v)
{
  $fp = fopen($v, "rb");
   $content = fread($fp, $filesize);

   fwrite($fp2, $content, $filesize);
   unset($content);
   fclose($fp);
   echo $k,"\n";
}
  fclose($fp2);

Some encryption methods

PHP’s own encryption function

Irreversible encryption functions are MD5 (), crypt ()

  • Md5() is used to calculate MD5 hash. The syntax is:string md5(string str);
  • Crypt() encrypts the string with the UNIX Standard DES module. This is a one-way encryption function and cannot be decrypted. To compare strings, put the first two characters of the encrypted string in the salt parameter, and then compare the encrypted string. The syntax is:string crypt(string str, string [salt]);

Reversible encryption: Base64_ Decryption functions corresponding to encode() and urlencode():

  • base64_ Encode() encodes the string in mime Base64. This coding method allows Chinese characters or pictures to be transmitted smoothly on the network. The syntax is string Base64_ encode(string data); Its decryption function is: String Base64_ decode(string encoded_ data); Return to the original.
  • Urlencode() encodes the string as a URL. For example, a space becomes a plus sign. Syntax: string URLEncode (string STR);  \
  • Its decryption function is: string URLDecode (string STR); Return to the original

case

Encryption and decryption algorithm

<? php  
<? php  
<? php  
<?php  
function passport_encrypt($txt, $key = 'www.zhuoyuexiazai.com') {   
    srand((double)microtime() * 1000000);   
    $encrypt_key = md5(rand(0, 32000));   
    $ctr = 0;   
    $tmp = '';   
    for($i = 0;$i < strlen($txt); $i++) {   
    $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;   
    $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);   
    }   
    return urlencode(base64_encode(passport_key($tmp, $key)));   
}   
function passport_decrypt($txt, $key = 'www.zhuoyuexiazai.com') {   
    $txt = passport_key(base64_decode(urldecode($txt)), $key);   
    $tmp = '';   
    for($i = 0;$i < strlen($txt); $i++) {   
    $md5 = $txt[$i];   
    $tmp .= $txt[++$i] ^ $md5;   
    }   
    return $tmp;   
}   
function passport_key($txt, $encrypt_key) {   
    $encrypt_key = md5($encrypt_key);   
    $ctr = 0;   
    $tmp = '';   
    for($i = 0; $i < strlen($txt); $i++) {   
    $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;   
    $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];   
    }   
    return $tmp;   
}   
$txt = "1";   
$key = "testkey";   
$encrypt = passport_encrypt($txt,$key);   
$decrypt = passport_decrypt($encrypt,$key);   
echo $encrypt."<br>";   
echo $decrypt."<br>";   
?>

Encryption and decryption algorithm used in discuz

Sometimes we need to use PHP to encrypt specific information, that is, generate an encrypted string through the encryption algorithm. The encrypted string can be decrypted through the decryption algorithm, which is convenient for the program to process the decrypted information. The most common applications are user login and some API data exchange scenarios. The most common applications are user login and some API data exchange scenarios. The principle of encryption and decryption is generally to add the key to the algorithm through a certain encryption and decryption algorithm, and finally get the encryption and decryption result.

<? php  

Limit IP access and submission times

principle

The number of submissions must be written into the database. For example, when the user logs in, he forgets to write the number of errors in the database 1, and the error time, and then write 2. When it is full, for example, 5 times, he will be prompted not to log in again. Please try again tomorrow, and then use DateDiff to calculate the time of error and now (). If it is greater than 24, open it again for him to try.

It’s easier to seal the IP, especially to disconnect the IP. First, let’s talk about the opening of the IP segment: first take out the IP accessed by the customer. For convenience of explanation, ip192.168.6.2 is set. Now the IP segment to be opened is 192.168.The broken,

Url = split (IP, ".") 'the IP here is the client IP

In fact, banning an IP is the same as the above method. Or simply take out the direct comparison between IP and client from the database.

Generally, the IP segments in the database are set to double precision, so these are required:

if Request.ServerVariables("HTTP_X_FORWARDED_FOR")="" then
IP=Request.ServerVariables("REMOTE_ADDR")
else
IP=Request.ServerVariables("HTTP_X_FORWARDED_FOR")
end if
sip=IP
cip=split(ip,".")
ip=256*256*256*cip(0)+256*256*cip(1)+256*cip(2)+cip(3)-1

Of course, these situations are in the aspect of database operation, and cookies are not involved.

In fact, sealing IP is not ideal and will affect innocent people. Perhaps it is because dynamic IP escaped.

Encapsulation instance

<? php

Limit input times

  • The page needs session first_ start();
  • Make a judgment when clicking login. If it is determined that the password entered by the user is wrong
If (the user's password is incorrect){

regular expression

"^ [0-9] * [1-9] [0-9] * $" / / positive integer

PHP receive coupons

Business requirements

According to the back-end settings, coupon template, user type settings, start and end times of coupon activities, and finally generate different coupon activity links.

Code environment

Common business logic in PHP

  • Settings and restrictions on the front end:
    • Judge whether the coupon exists or is deactivated
    • Judge the activity start time and coupon start time
  • Then, to receive the activity coupon, you need to judge the following conditions:
    • Activity ended
    • At the beginning of the activity
    • The activity is received by new users, and the received users are old users
    • The activity is received by old users, and the received users are new users
    • Are coupons collected
    • Coupon tips received
    • Received successfully

code implementation

/**

Users receive coupons and issue coupons

/**

If you cancel an order (cash + full minus + points), how do you share the discount

  • If the goods of an order do not participate in a certain activity, they need to share the discount. Generally speaking, the items that need to be shared include shopping money, points, coupons, full reduction, etc. And use the discount on the whole order.
  • Multiple n-discounts, restrictions on rush purchase, group purchase, etc. are all reflected in the commodity unit price, so the difficulty lies in how to apportion the discount. For example, an order is placed with shopping money and points. It needs to be returned after the order is cancelled. At this time, the money to be returned to the user is the money after the commodity price – shopping money – points

Common business logic in PHP

The following provides preferential allocation methods, which can be used for reference if necessary

<? php

Use Sina API to generate short websites and shorten long websites!

Sina provides an API for converting long links into short links, which can convert long links into short links   t.cn/xxx   Short links in this format.

The API has two formats:

http://api.t.sina.com.cn/short_ URL / short.json (the returned result is in JSON format)

Request parameters:

  • Source is the appkey assigned when applying for an application. It represents the unique identity of the application when calling the interface. url_ Long long links that need to be converted need to be urlencoded, no more than 20 at most.
  • Multiple URL parameters need to be requested as follows:url_long=aaa&url_long=bbb

Create source method

  • 1. Entry http://open.weibo.com/ , select menu micro connection – > website access. 2. Click access now to create a new application, fill in the application name, and click create. 3. After the creation is successful, the appkey is the value of the source parameter and can be used to request the creation of a short link.
<? php

Return JSON format

[
    {
        "url_short": "http:\/\/t.cn\/Rki0twp",
        "url_long": "http:\/\/detail.tmall.com/item.htm?spm=a21wu.241046-us.9629632455.7.193eb6cbbC9gFg&id=585958323801",
        "type": 0
    }
]

Return XML format

<?xml version="1.0" encoding="UTF-8"?>
<urls>
    <url>
        <url_short> http://t.cn/Rki0twp</url_short>
        <url_long>https://detail.tmall.com/item.htm?spm=a21wu.241046-us.9629632455.7.193eb6cbbC9gFg&id=585958323801</url_long>
        <type>0</type>
    </url>
</urls>

The generated short link is  http://t.cn/Rki0twp , The visit will jump to  https://detail.tmall.com/item.htm?spm=a21w…

The complete classes are as follows:

/*

You can also use the following complete method

<? php

PHP fopen/file_ get_ Performance comparison between contents and curl

fopen/file_ get_ Contents will perform DNS query again for each request and will not cache DNS information.

  • However, curl will automatically cache DNS information. Requests for web pages or pictures under the same domain name only need one DNS query. This greatly reduces the number of DNS queries. So curl performs better than fopen / file_ get_ Contents is much better.
    • fopen/file_ get_ Contents uses HTTP when requesting http_ fopen_ Wrapper, not keeplive.
  • Curl can. In this way, curl will be more efficient when multiple links are requested multiple times.
    • fopen/file_ get_ The contents function will be affected by allow in the php.ini file_ url_ The impact of the open option configuration.
  • If the configuration is turned off, the function fails. Curl is not affected by this configuration.
    • Curl can simulate a variety of requests, such as post data, form submission, etc. users can customize requests according to their own needs.
  • And fopen / file_ get_ Contents can only use get to get data.
    • file_ get_ Contents will store the results in a string when getting the remote file, and the fields function will store them in array form
    • Therefore, I prefer to use curl to access remote URLs. PHP has curl module extension, which is very powerful.
#Recently, I need to get music data on other people's websites. File used_ get_ Contents function, but it always encounters the problem of obtaining failure. Although the timeout is set according to the examples in the manual, it will not work most of the time:

file_ get_ Contents seconds required to grab google.com:

2.31319094
2.30374217
2.21512604
3.30553889
2.30124092

Curl usage time:

0.68719101
0.64675593
0.64326
0.81983113
0.63956594

Curl and file_ get_ Contents performance comparison PHP source code is as follows:

<? php
  • file_ get_ Contents speed: 4.2404510975 seconds
  • Curl speed: 2.8205530643 seconds
  • Curl ratio file_ get_ Contents is about 30% faster. The most important thing is that the server load is lower

file_ get_ Contents is handled frequently. When I was young, it felt good to use it. Nothing unusual. If your file is processed by 1K + people. Then your server CPU is waiting to rise.

This work adoptsCC agreement, reprint must indicate the author and the link to this article