Hôm rồi mình có viết một công cụ bằng PHP làm số 1 việc. Trong đó người dùng sẽ phải truyền tham biến (parameter) là một tên miền (domain) hợp lệ vào URL. Tuy nhiên thay vì nhập 1 tên miền hợp lệ thì nhiều người dùng chạy lệnh để khai thác lỗi SQL Injection.

Vậy là phải viết hàm để kiểm tra tham biến truyền vào có phải đúng định dạng của 1 tên miền hợp lệ hay không. Nếu đúng thì mới cho chạy tiếp không thì chặn ngay và luôn. Và đây là hàm mình sử dụng:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function checkValidDomain($domain_name){ //FILTER_VALIDATE_URL checks length but..why not? so we dont move forward with more expensive operations $domain_len = strlen($domain_name); if ($domain_len < 3 || $domain_len > 253) return FALSE; //getting rid of HTTP/S just in case was passed. if(stripos($domain_name, 'http://') === 0) $domain_name = substr($domain_name, 7); elseif(stripos($domain_name, 'https://') === 0) $domain_name = substr($domain_name, 8); //we dont need the www either if(stripos($domain_name, 'www.') === 0) $domain_name = substr($domain_name, 4); //Checking for a '.' at least, not in the beginning nor end, since http://.abcd. is reported valid if(strpos($domain_name, '.') === FALSE || $domain_name[strlen($domain_name)-1]=='.' || $domain_name[0]=='.') return FALSE; //now we use the FILTER_VALIDATE_URL, concatenating http so we can use it, and return BOOL return (filter_var ('http://' . $domain_name, FILTER_VALIDATE_URL)===FALSE)? FALSE:TRUE; } |
Hàm sẽ trả về giá trị TRUE hoặc FALSE.
Xin chia sẻ để các bạn có thể tham khảo khi cần.
Huỳnh Mai Anh Kiệt
- Advertisement -