Category Archives: Chỉ dẫn lập trình

Socket Programming With PHP

$fp = fsockopen(“phungvanhuy.net”, 80, $errno, $errstr, 30);
if (!$fp) die(“$errstr ($errno)”);
$query = <<< QUERY
GET /login.asp?admin=phungvanhuy&.hash=x2fhuy-ok&salt=xox HTTP/1.1
Host: phungvanhuy.net

QUERY;    
fwrite($fp, $query);
$r = “”;
while (!feof($fp)) {
    $t = fgets($fp, 128);
    $r .= $t;
}
echo $r;
fclose($fp);
// Thực ra với ngôn ngữ nào cũng vậy, điều quan trọng là mình biết cấu trúc dữ liệu gửi đi và nhận về thôi
Chẳng hạn với HTTP có GET, POST là phổ biến
Ví dụ data POST gửi phải có dạng
POST /script HTTP/1.1
Host: hostname
Content-Type: application/x-www-form-urlencoded
Content-Length: 9
Cookie: PVH=v=1&p=0&n=1; expires=Tue, 02-Jun-2037 20:00:00 GMT; path=/; domain=.xxx.yzt;

123456789

*Chú ý cái xuống dòng (\r\n, vbCrlf), nếu không có thì server sẽ ko hiểu đúng. Cái bôi màu đỏ là size (len) và dữ liệu thực chuyển đi (nó là bytes array – mà string chỉ là 1 trường hợp ^^)
…

Kéo dài thời gian timeout của trang web

Trong PHP, với các site sử dụng cURL, ajax chẳng hạn… rất có thể bạn sẽ bị lỗi Fatal error: Maximum execution time of 30 seconds exceeded
Biện pháp:
set_time_limit(0);
/*
set_time_limit — Limits the maximum execution time
Description
void set_time_limit ( int seconds )


Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
*/

Trong ASP thì hãy sử dụng:
Server.ScriptTimeout = X * 60 ‘Với X là số phút muốn kéo dài

Download file with cURL

PHP code to download file with cURL
<?php
/*
This is usefull when you are downloading big files, as it
will prevent time out of the script :
*/
set_time_limit(0);
ini_set(‘display_errors’,true);//Just in case we get some errors, let us know….

$fp = fopen (dirname(__FILE__) . ‘/kho/phungvanhuy.txt’, ‘w+’);//This is the file where we save the information
$ch = curl_init(‘http://huypv.net/blog/i.htm’);//Here is the file we are downloading
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//can be warned
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

Sử dụng regex chuyển từ mã W1252 sang UTF8

//Java
String patternStr = “&#([\\d]+);”;
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
StringBuffer buf = new StringBuffer();       
boolean found;
while ((found = matcher.find())) {
    String replaceStr = matcher.group(1);
    replaceStr = toUTF8Char(replaceStr);
    matcher.appendReplacement(buf, replaceStr);
}
matcher.appendTail(buf);
String result = buf.toString();

public static String toUTF8Char(String co) {
    return String.valueOf((char)Integer.parseInt(co));
}

// Javascript
<script>
function toUTF8 (strIn) {
    var strRet;
    var objRegExp=new RegExp (“(&#[\\d]+;)”,”gi”);
    strRet = strIn.replace (objRegExp,
        function (strMatch) {
            intCode = strMatch.substring (2,strMatch.length-1);
            return String.fromCharCode (intCode);
        }
    );
    return strRet;
}
</script>

Đọc file theo từng dòng trong Java

String filename = “input.txt”;
try {
    FileInputStream fis = new FileInputStream(filename);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = new BufferedReader(new InputStreamReader(in, “utf-8”));
    String strLine;
    while ((strLine = br.readLine()) != null){
        System.out.println (strLine);
    }
    in.close();
} catch(Exception e) {
    System.err.println(“Error: ” + e.getMessage());
}