Pages

Thursday, October 11, 2012

Simple and Secure PHP Download Script with Limits Tutorial


Below is the important preparation you need to do:
1. Create a folder in your web server that contains the content to be downloaded (e.g ebookdownloads).
2. Change the file permission of the directory to 755.
3. Upload the content for downloading to that folder (e.g. ebook.pdf).
4. This folder will not be publicly visible during the downloading process, so your user will not have an obvious idea as to where the files are saved. Even if they managed to learn the path, any direct downloading will be denied by the server (details below).
5. Upload .htaccess inside this protected folder containing the content for downloading. The htaccess should force downloading of the content type (for example, if it is a PDF file) as well as prevent direct file downloading and any forms of hot linking. Below is the content of the .htaccess:
<Files thisisyourprotectedfile.pdf>
  order deny,allow
  deny from all
</Files>
<Files *.pdf>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>
6. The recommended file permission for .htaccess and the file for downloading is 644.
7. On the page where you need to present the download link, you can use this code below:
<a rel="nofollow" href="http://www.yourdomain.com/download.php">Download this Content</a>
Let's name our download script "download.php." It needs to be uploaded to the root directory of your website. Aside from using the anchor text "Download this content," you can also use a download button/image link to make it look attractive and prominent to the user.
8. On the download page where you are presenting the download link to the user, you need to place the session key script at the top most part of the page. The page where you will need to show the download link should execute a PHP script or have a .php extension.
<?php
session_start();
$key= 'This is your example key, please change this.';
$_SESSION['key'] = md5($key);
?>
Since this is a PHP script, the download page should support PHP and not be a pure HTML page.


source: http://www.devshed.com/c/a/PHP/Simple-and-Secure-PHP-Download-Script-with-Limits-Tutorial/

NodeJS

Aplikasi web menjadi salah satu peluang bisnis yang menjanjikan pada sekarang ini. Untuk saat ini, ada banyak sekali teknologi untuk membangun aplikasi tersebut diantaranya ASP.NET, PHP JSP, dan yang lainnya. Tetapi, ada satu aplikasi web yang dapat menjadi alternatif yang dapat diandalkan kemampuannya dalam meningkatkan performance, yaitu Nodejs. Apa itu Nodejs? Berikut ini akan kami uraikan secara ringkas semua yang yang berkaitan dengan Nodejs.
Apa itu Nodejs?
Nodejs pertama kali dikembangkan oleh Ryan Dahl. Framework ini dibuat untuk memperoleh performance aplikasi web yang tinggi dan mengoptimalisasikan lingkungan concurrent yang tinggi pula. Framework Nodejs memungkinkan bekerja dengan keandalan tinggi dan dengan I/O non-blocking. Tujuan dari non-blocking ini untuk menghindari proses waiting yang lama dan mengurangi beban CPU.
Secara teknis, Nodejs dibangun menggunakan C/C++ dan berjalan di atas framework Javascript V8, framework yang dikembangkan oleh Google dan bagian dari sistem inti browser Chrome. Nodejs berisi framework yang didalamnya sudah terdapat web server sehingga kita sudah tidak perlu menggunakan web server lainnya seperti Apache dan IIS. Bahasa pemrograman yang digunakan pada Nodejs adalah Javascript. Portal resmi Nodejs dapat dikunjungi di alamat website http://www.nodejs.org.
Lalu, apa kelebihan dari nodejs? Secara umum, Nodejs berjalan di atas V8 Javascript Interpreter untuk menjalankan kode Javascript. Untuk menjaga performance tetap tinggi, Nodejs menerapkan solusi event-driven. Fitur-fitur yang ditawarkan oleh Nodejs antara lain:
  • Konsumsi memori yang kecil.
    Hampir sebagian besar web server menghadapi masalah concurrent request yang tinggi untuk menangani user secara bersama-sama. Untuk penyelesaian masalah ini, umumnya web server menerapkan multiple thread sebagai solusi yang memungkinkan satu koneksi ditangani oleh satu server thread. Kita sudah mengetahui bahwa penggunaan thread ini akan mengalokasi memory stack. Semakin banyak thread yang berjalan, maka penggunaan konsumsi memori juga semakin meningkat. Jika jumlah user meningkat, hal ini akan menjadi tidak bagus. Nodejs mempunyai cara berbeda dalam masalah ini. Pendekatan yang dilakukan adalah event driven berbasis infinite event loop dalam satu thread. Dengan solusi ini, penggunaan memori akan berkurang.
  • Operasi Non-Blocking
    Arsitektur Node yang dibangun dengan pendekatan non-blocking merupakan fitur utama dari framework Nodejs. Dengan pendekatan ini, ketika kita ingin mengakses database, membaca data pada file, atau mengirim data melalui Socket, kita harus membuat fungsi callback. Setelah melakukan eksekusi kode, Nodejs akan melakukan pekerjaan lain sampai data tersedia, baik pekerjaan itu sukses atau tidak, sehingga kita dapat mengontrolnya kembali.
  • Penggunaan CPU yang lebih kecil
    Nodejs sangat peduli terhadap kinerja CPU. Pada operasi yang melibatkan banyak thread, server akan meningkatkan penggunaan CPU ketika melayani permintaan dari user. Pendekatan inilah yang menimbulkan penggunaan CPU yang tinggi. Nodejs menghindari permasalah di atas dengan single thread yang memanfaatkan event loop dan callback. Nodejs dapat melakukan skalabilitas dengan memanfaatkan load balancer atau proxy server.
Instalasi
Nodejs mendukung platform Linux, Windows, Mac, dan Unix. Sebagai ilustrasi, berikut cara instalasi Nodejs pada Linux Ubuntu dan Windows.
Instalasi Linux.
  • Mula-mula kita harus menginstal kebutuhan library development termasuk compiler. Melalui console, lakukan instalasi library pendukung yang diperlukan.
    sudo apt-get  -y  install build essential g++ libssl-dev 
  • Selanjutnya, download file Nodejs. Misalnya, Anda akan menginstal di folder tmp, maka buat foldernya.
    mkdir  /tmp/nodejs 
    cd/tmp/nodejs        
  • Kemudian download file Nodejs. Misalnya, Anda mendownload Nodejs versi 0.6.14, berikut ini cara mendownload-nya (ganti versi sesuai dengan kebutuhan) dan mengekstraknya.
    wget  http://nodejs.org/dist/v0.6.14/node-v0.6.14.tar.gz  
    tar  -zxvf  node-v0.6.14.tar.gz   
  • Kemudian, lakukan konfigurasi dan instalasi
    cd node-v0.6.14  
    ./configure          
    make                     
    sudo make install  
  • Selanjutnya, sistem akan melakukan instalasi. Jika sukses, Anda dapat mengeceknya dengan mengetik script berikut:
    node  -v   
  • Kemudian akan ditampilkan versi dari Nodejs.
  • Langkah terakhir, instalasi npm. Tool ini berguna untuk menginstal module-module yang ada pada Nodejs. Kita lakukan dengan menggunakan curl. Jika Anda belum menginstalasi curl, Anda dapat melakukannya melalui console berikut.
    sudo apt-get install curl
  • Setelah itu, instalasi npm
    curl http://npmjs.org/install.sh | sudo sh                          
    jika sukses, Anda dapat mengeceknya dengan mengetik script berikut ini.
    npm  -v           
    intsalasi Nodejs pada Linux Ubuntu selesai. 
Khusus untuk platform Windows, Anda dapat mendownload instalasinya di websitehttp://nodejs.org/dist/v0.6.14/node-v0.6.14.msi. Sedangkan untuk Mac, Anda dapat mendownloadnya di website http://nodejs.org/dist/v0.6.14/node-v0.6.14.pkg.
Setelah selesai men-download file instalasi, jalankan file tersebut dan diikuti petunjuk instalasinya pada kotak dialog instalasi. Jika sukses, jalankan console dan ketik script berikut ini.
node -v 
Kemudian akan ditampilkan versi dari Nodejs. Artikel kali ini cukup membahas tentang apa itu nodejs dan instalasinya. Pada artikel mendatang, insya Allah akan kita bahas Nodejs lebih lanjut. Jadi, jangan sampai terlewatkan.
Oleh: Agus Kurniawan/PC Media 

Query Optimization Tips


Below listed are some of the most important query optimization tips.

  • The parameters query_cache_type and query_cache_size can be set in the my.cnffile to speed up the query performance.
    - Query_cache_size is suitable where the database has to repeatedly run the
    same queries on the same data set, returning the same results each time. Thus
    MySQL can cache the result set, avoiding the overhead of running through the
    data over and over.

    - Query_cache_size can differ depending upon the application’s requirements,
    the type of queries and RAM availability.

    - Possible values of query_cache_type
    o 0 = disabled
    o 1 = enabled (Recommended when the queries are slow and RAM
    available is more)
    o 2 = on demand (Queries are only cached if the Hint SQL_CACHE is
    used)
  • Avoid using DISTINCT when you have or could use GROUP BY.Example:
    Original: select distinct col1 from table1
    Alternative: select col1 from table1 group by col1
  • If you use DISTINCT, try to use LIMIT (MySQL stops as soon as it finds row_countunique rows) and avoid ORDER BY (it requires a temporary table in many cases).
  • Enhance Insert statement performance- INSERT statement includes the below activities:-
    o Connecting
    o Sending query to server
    o Parsing query
    o Inserting row
    o Inserting indexes
    o Closing
    - Batch INSERT and REPLACE should be used when inserting multiple rows at the
    same time.
    SYNTAX
    INSERT INTO tbl_name (col1, col2) VALUES (val1, val2);
    or
    INSERT INTO tbl_name SELECT...
    or
    INSERT INTO tbl_name VALUES (val1, val2), (val1, val2) …

    - For even better performance use LOAD DATA instead of INSERT. LOAD DATA
    INFILE reads rows from a text file into a table at a very high speed.
    SYNTAX
    LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
    [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [CHARACTER SET charset_name]
    [{FIELDS | COLUMNS}
    [TERMINATED BY 'string']
    [[OPTIONALLY] ENCLOSED BY 'char']
    [ESCAPED BY 'char']
    ]
    [LINES
    [STARTING BY 'string']
    [TERMINATED BY 'string']
    ]
    [IGNORE number LINES]
    [(col_name_or_user_var,...)]
    [SET col_name = expr,...]
  • LIMIT m, n may not be as fast as it sounds.Alternative: Precompute positions and then use POS BETWEEN (m+1) and (m+n)
    Example:
    Original: select * from orders limit 100, 10;
    Alternative: select * from orders where POS between 101 and 110;
  • Don't use ORDER BY RAND() if you have > ~2K recordsAlternative:
    - Add an indexed column called “random” and populate it with random values.
    - Do order by random instead of order by rand()
    - Once you’ve selected the row update “random” to new random value.
    - Periodically run process to reset random values.
  • use SQL_NO_CACHE hint when you are SELECTing frequently updated data orlarge sets of data.
  • Use SQL_CACHE if you have setup MySQL Query Caching to explicit mode (setquery_cache_type = 2) to tell MySQL which queries to cache.
  • The HIGH_PRIORITY hint can be used on SELECT or INSERT statements to letMySQL know that this is a high priority query.
  • The LOW_PRIORITY hint can be used on INSERT or UPDATE statements. If you usethe LOW_PRIORITY keyword, execution of the query is delayed until no other
    clients are reading from the table.
  • An INSERT LOW_PRIORITY statement will not return until the statement has beenexecuted, which could possibly be forever. Instead you can use an INSERT
    DELAYED statement. It will return immediately, but it will still wait until other
    clients have closed the table before executing the statement.
    Note: INSERT DELAYED only works on MyISAM, MEMORY, and ARCHIVE tables.
  • STRAIGHT_JOIN hint can be used to tell MySQL to join the tables in the order thatthey are specified in the FROM clause.
  • SQL_BUFFER_RESULT hint tells MySQL to put the result of the query into atemporary table. This will free up a table lock while the resultset is being sent to
    the client. So you would only want to use this on large result sets.
  • SQL_BIG_RESULT can be used with DISTINCT and GROUP BY SELECT statements. Ittells MySQL that the result set will be big. MySQL directly uses disk-based
    temporary tables if needed, and prefers sorting to using a temporary table with a
    key on the GROUP BY elements.
  • SQL_SMALL_RESULT uses fast temporary tables to store the resulting table insteadof using sorting. Since this is typically the default route of the optimizer, this hint is
    often not needed.
  • Avoid wildcards at the start of LIKE queries.
  • Avoid correlated subqueries. In “select” and “where” clause try to avoid “in” clause.
  • Avoid calculated comparisons and isolate indexed columns.Example:
    order_created is the indexed column.
    select * from orders where to_days(order_created) – to_days(current_date()) >=7;
    - Here the index is not used.
    select * from orders where order_created >= current_date() - interval 7day;
    - Here the index is used as the indexed column is isolated.
  • ORDER BY and LIMIT work best with equalities and covered indexes
  • Separate text/blobs from metadata, don't put text/blobs in results if you don'tneed them
  • Derived tables (subqueries in the FROM clause) can be useful for retrieving BLOBswithout sorting them. (Self-join can speed up a query if 1st part finds the IDs and
    uses then to fetch the rest).
  • ALTER TABLE...ORDER BY can take data sorted chronologically and re-order it by adifferent field -- this can make queries on that field run faster.
  • Do not make the queries very complex, rather join smaller ones.
  • Delete small amounts at a time if you can. The reason being Delete acquires a lockon the table blocking further access till the execution completes.
  • Make similar queries consistent so cache is used.
  • Have good SQL query standards.(http://dev.mysql.com/doc/refman/5.1/...atibility.html)
  • Don't use deprecated features.
  • Turning OR on multiple index fields (<5.0) into UNION may speed things up (withLIMIT), after 5.0 the index_merge should pick stuff up.
  • Don't use COUNT * on Innodb tables for every search, do it a few times and/orsummary tables, or if you need it for the total # of rows, use
    SQL_CALC_FOUND_ROWS first and then SELECT FOUND_ROWS().
  • If you often need to calculate COUNT or SUM based on information from a lot ofrows (articles rating, poll votes, user registrations count, etc.), it makes sense to
    create a separate table and update the counter in real time, which is much faster. If
    you need to collect statistics from huge log tables, take advantage of using a
    summary table instead of scanning the entire log table every time.
  • Don’t use REPLACE (which is DELETE+INSERT and wastes ids): use INSERT … ONDUPLICATE KEY UPDATE instead (i.e. it’s INSERT + UPDATE if conflict takes place).
    The same technique can be used when you need first make a SELECT to find out if
    data is already in database, and then run either INSERT or UPDATE.
  • Use groupwise maximum instead of subqueries.
  • Avoid using of HAVING clause — it’s rather slow.
  • If you have lots of DELETEs in your application or updates of dynamic format rows(rows containing VARCHAR, BLOB or TEXT column are dynamic format rows)
    schedule running OPTIMIZE TABLE query every weekend by crond
  • Use leftmost index prefix — in MySQL you can define index on several columns sothat left part of that index can be used as a separate one which results in lesser
    indices.
  • Do not use “! =” when you are about to compare two result set. Instead of it use“not exists” clause.
  • Disable unique and foreign key constraints during data import operations as wellas set Autocommit to false. Set it to true once the import is complete.