Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, September 30, 2020

Permutations php porting from python ( for fast and cheap cpu )

 taken from https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

for my note

python https://docs.python.org/2/library/itertools.html#itertools.permutations



I've ported the Python itertools code listed here (using generators). The advantage over the solutions posted so far is that it allows you to specify r (permutation size).

function permutations($pool, $r = null) {
    $n = count($pool);

    if ($r == null) {
        $r = $n;
    }

    if ($r > $n) {
        return;
    }

    $indices = range(0, $n - 1);
    $cycles = range($n, $n - $r + 1, -1); // count down

    yield array_slice($pool, 0, $r);

    if ($n <= 0) {
        return;
    }

    while (true) {
        $exit_early = false;
        for ($i = $r;$i--;$i >= 0) {
            $cycles[$i]-= 1;
            if ($cycles[$i] == 0) {
                // Push whatever is at index $i to the end, move everything back
                if ($i < count($indices)) {
                    $removed = array_splice($indices, $i, 1);
                    array_push($indices, $removed[0]);
                }
                $cycles[$i] = $n - $i;
            } else {
                $j = $cycles[$i];
                // Swap indices $i & -$j.
                $i_val = $indices[$i];
                $neg_j_val = $indices[count($indices) - $j];
                $indices[$i] = $neg_j_val;
                $indices[count($indices) - $j] = $i_val;
                $result = [];
                $counter = 0;
                foreach ($indices as $indx) {
                    array_push($result, $pool[$indx]);
                    $counter++;
                    if ($counter == $r) break;
                }
                yield $result;
                $exit_early = true;
                break;
            }
        }
        if (!$exit_early) {
            break; // Outer while loop
        }
    }
}

It works for me, but no promises! Example usage:

$result = iterator_to_array(permutations([1, 2, 3, 4], 3));
foreach ($result as $row) {
    print implode(", ", $row) . "\n";
}

from https://stackoverflow.com/a/43307800/6125958



Sunday, August 6, 2017

Prevent Duplicate in Msql

taken from here How to prevent Duplicate records from my table Insert ignore does not work here


alter the table by adding UNIQUE constraint
ALTER TABLE employee ADD CONSTRAINT emp_unique UNIQUE (ename,dno,mgr,sal)
but you can do this if the table employee is empty.
or if records existed, try adding IGNORE
ALTER IGNORE TABLE employee ADD CONSTRAINT emp_unique UNIQUE (ename,dno,mgr,sal)
UPDATE 1
Something went wrong, I guess. You only need to add unique constraint on column ename since eno will always be unique due to AUTO_INCREMENT.
In order to add unique constraint, you need to do some cleanups on your table.
The queries below delete some duplicate records, and alters table by adding unique constraint on column ename.
DELETE a
FROM Employee a
     LEFT JOIN
     (
        SELECT ename, MIN(eno) minEno
        FROM Employee
        GROUP BY ename
     ) b ON a.eno = b.minEno
WHERE b.minEno IS NULL;

ALTER TABLE employee ADD CONSTRAINT emp_unique UNIQUE (ename);
Here's a full demonstration

Sunday, December 7, 2014

PHP mcrypt and C# Encryptor - Encryption and decryption


For the past day I have been looking for a solution to transfer encrypted information between a PHP web application and a C# desktop application.
This requires that both systems use the same algorithm, key and init vector (IV)
This isn’t as easy as it sounds. The slightest difference in the setup of either system means that the encrypted information cannot be decoded on the other end and makes it basically useless.
(The following PHP code has been modified after some useful debugging and comments from Serge N.)
    
//Encryption function
function mc_encrypt($encrypt, $key, $iv)
{
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    mcrypt_generic_init($td, $key, $iv);
    $encrypted = mcrypt_generic($td, $encrypt);
    $encode = base64_encode($encrypted);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $encode;
}


//Decryption function
function mc_decrypt($decrypt, $key, $iv)
{
    $decoded = base64_decode($decrypt);
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
    mcrypt_generic_init($td, $key, $iv);
    $decrypted = mdecrypt_generic($td, $decoded);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return trim($decrypted);
}


//Usage in PHP
$original = "original message";
$key = "abcdefg_abcdefg_abcdefg_abcdefg_";
$iv = "abcdefg_abcdefg_";
$keysize = 128;


$enced = mc_encrypt(stripslashes($original), $key, $iv);
echo "Encrypted:
".$enced."
";
$unced = mc_decrypt($enced, $key, $iv);
echo "Decrypted:
".$unced."
"; 

That is the PHP code done. We can generate a key and then at any point use the decrypt function to unencode it.
Now the trick is getting the exact same functionality in .NET (with C#)
I found that the class below does it pretty well (this uses the default Rijndael algorithm which is 128 in C#)
    
public static class Encrypter
{
          public static String EncryptIt(String s, byte[] key, byte[] IV)
          {


             String result;
              RijndaelManaged rijn = new RijndaelManaged();
              rijn.Mode = CipherMode.ECB;
              rijn.Padding = PaddingMode.Zeros;
              using (MemoryStream msEncrypt = new MemoryStream())
              {
                  using (ICryptoTransform encryptor = rijn.CreateEncryptor(key, IV))
                  {
                      using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                     {
                         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                         {


                             swEncrypt.Write(s);
                          }
                      }
                  }
                  result = Convert.ToBase64String(msEncrypt.ToArray());
              }
              rijn.Clear();
              return result;
          }
          public static String DecryptIt(String s, byte[] key, byte[] IV)
          {
              String result;
              RijndaelManaged rijn = new RijndaelManaged();
              rijn.Mode = CipherMode.ECB;
              rijn.Padding = PaddingMode.Zeros;
              using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(s)))
              {
                  using (ICryptoTransform decryptor = rijn.CreateDecryptor(key, IV))
                  {
                      using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                      {
                          using (StreamReader swDecrypt = new StreamReader(csDecrypt))
                          {
                              result = swDecrypt.ReadToEnd();
                          }
                      }
                  }
              }
              rijn.Clear();
              return result;
          }
}

//Usage


Encoding byteEncoder = Encoding.UTF8;
byte[] rijnKey = byteEncoder.GetBytes("abcdefg_abcdefg_abcdefg_abcdefg_");
byte[] rijnIV = byteEncoder.GetBytes("abcdefg_abcdefg_");


String message = "original message";
String encrypted = Encrypter.EncryptIt(message, rijnKey, rijnIV);
String decrypted = Encrypter.DecryptIt(encryption, rijnKey, rijnIV);


Console.WriteLine("Original: "+message);
Console.WriteLine("Encrypted: "+encrypted);
Console.WriteLine("Decrypted: "+decrypted);

I hope this shortens someone’s search process when trying to do this.
PS. Yes this is my first try at using the [ code ]  containers in Posterous (not the easiest thing in the world but after some tweaking eventually got the code to appear here nicely)


TAKEN from http://blog.nikoroberts.com/post/45834708375/php-mcrypt-and-c-encryptor  , all credits goes there

Wednesday, February 20, 2013

Using cURL in PHP to access HTTPS (SSL/TLS) protected sites

From PHP, you can access the useful cURL Library (libcurl) to make requests to URLs using a variety of protocols such as HTTP, FTP, LDAP and even Gopher. (If you’ve spent time on the *nix command line, most environments also have the curl command available that uses the libcurl library)
In practice, however, the most commonly-used protocol tends to be HTTP, especially when using PHP for server-to-server communication. Typically this involves accessing another web server as part of a web service call, using some method such as XML-RPC or REST to query a resource. For example, Delicious offers a HTTP-based API to manipulate and read a user’s posts. However, when trying to access a HTTPS resource (such as the delicious API), there’s a little more configuration you have to do before you can get cURL working right in PHP.

The problem

If you simply try to access a HTTPS (SSL or TLS-protected resource) in PHP using cURL, you’re likely to run into some difficulty. Say you have the following code: (Error handling omitted for brevity)
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
If $url points toward an HTTPS resource, you’re likely to encounter an error like the one below:
Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
The problem is that cURL has not been configured to trust the server’s HTTPS certificate. The concepts of certificates and PKI revolves around the trust of Certificate Authorities (CAs), and by default, cURL is setup to not trust any CAs, thus it won’t trust any web server’s certificate. So why don’t you have problems visiting HTTPs sites through your web browser? As it happens, the browser developers were nice enough to include a list of default CAs to trust, covering most situations, so as long as the website operator purchased a certificate from one of these CAs.

The quick fix

There are two ways to solve this problem. Firstly, we can simply configure cURL to accept any server(peer) certificate. This isn’t optimal from a security point of view, but if you’re not passing sensitive information back and forth, this is probably alright. Simply add the following line before calling curl_exec():
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This basically causes cURL to blindly accept any server certificate, without doing any verification as to which CA signed it, and whether or not that CA is trusted. If you’re at all concerned about the data you’re passing to or receiving from the server, you’ll want to enable this peer verification properly. Doing so is a bit more complicated.

The proper fix

The proper fix involves setting the CURLOPT_CAINFO parameter. This is used to point towards a CA certificate that cURL should trust. Thus, any server/peer certificates issued by this CA will also be trusted. In order to do this, we first need to get the CA certificate. In this example, I’ll be using the https://api.del.icio.us/ server as a reference.
First, you’ll need to visit the URL with your web browser in order to grab the CA certificate. Then, (in Firefox) open up the security details for the site by double-clicking on the padlock icon in the lower right corner:

Then click on “View Certificate”:

Bring up the “Details” tab of the cerficates page, and select the certificate at the top of the hierarchy. This is the CA certificate.



 Then click “Export”, and save the CA certificate to your selected location, making sure to select the X.509 Certificate (PEM) as the save type/format.




Now we need to modify the cURL setup to use this CA certificate, with CURLOPT_CAINFO set to point to where we saved the CA certificate file to.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt"); 
The other option I’ve included,CURLOPT_SSL_VERIFYHOST can be set to the following integer values:
  • 0: Don’t check the common name (CN) attribute
  • 1: Check that the common name attribute at least exists
  • 2: Check that the common name exists and that it matches the host name of the server
If you have CURLOPT_SSL_VERIFYPEER set to false, then from a security perspective, it doesn’t really matter what you’ve set
CURLOPT_SSL_VERIFYHOST
to, since without peer certificate verification, the server could use any certificate, including a self-signed one that was guaranteed to have a CN that matched the server’s host name. So this setting is really only relevant if you’ve enabled certificate verification.
This ensures that not just any server certificate will be trusted by your cURL session. For example, if an attacker were to somehow redirect traffic from api.delicious.com to their own server, the cURL session here would not properly initialize, since the attacker would not have access to a server certificate (i.e. would not have the private key) trusted by the CA we added. These steps effectively export the trusted CA from the web browser to the cURL configuration.

More information

If you have the CA certificate, but it is not in the PEM format (i.e. it is in a binary or DER format that isn’t Base64-encoded), you’ll need to use something like OpenSSL to convert it to the PEM format. The exact command differs depending on whether you’re converting from PKCS12 or DER format.
There is a CURLOPT_CAPATH option that allows you to specify a directory that holds multiple CA certificates to trust. But it’s not as simple as dumping every single CA certificate in this directory. Instead, they CA certificates must be named properly, and the OpenSSL c_rehash utility can be used to properly setup this directory for use by cURL.

Taken from HERE : http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

Logging in to HTTPS websites using PHP cURL



To log in to a HTTPS website using PHP cURL you need to do the following:

enable cURL by uncommenting the line extension=php_curl.dll in your php.ini file.

Set up cURL to either accept all certificates or add the needed certificate authority to cURLs CA list (check out http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/)

Then you need to load the page to get the session cookie:
// Create temp file to store cookies
$ckfile = tempnam ("/tmp", "CURLCOOKIE");

// URL to login page
$url = "https://www.securesiteexample.com";

// Get Login page and its cookies and save cookies in the temp file
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile); // Stores cookies in the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch); 


Now you have the cookie, you can POST login values (check the source of the login page to check if you need any other fields too)
$fields = array(
$fields = array(
'username' => 'yourusername',
'password' => 'yourpassword',
);
$fields_string = '';
foreach($fields as $key=>$value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');

// Post login form and follow redirects
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); //Uses cookies from the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Tells cURL to follow redirects
$output = curl_exec($ch); 
Now you should be able to access any pages within the password-restricted area by just including the cookies for each call:

$url = "https://www.securesiteexample.com/loggedinpage.html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Accepts all CAs
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); //Uses cookies from the temp file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);


Source from:
http://www.herikstad.net/2011/06/logging-to-https-websites-using-php.html

Thursday, November 29, 2012

Menghindari Duplicate Entry dengan Distinct


MySQL – Menghindari Record Kembar dengan Distinct Posted by Aa on Nov 5, 2012 in MySQL | 0 comments Berhubung ini ada pertanyaan dari salah satu teman murid bimbingan, jadinya harus nulis disini deh biar semuanya bisa membaca dan belajar :) Ehm..bingung neh mau ngasih pendahuluannya seperti apa. Biar lebih jelasnya, yuk langsung praktek aja :) Misalnya kita buat Database dan Tabel baru. Berikut log-nya:
    mysql> create database guru; use guru;
    Query OK, 1 row affected (0.02 sec)

    Database changed
    mysql> create table profilguru(
    -> id int(2) auto_increment primary key,
    -> nama varchar(50) not null,
    -> matpel varchar(30) not null
    -> );
    Query OK, 0 rows affected (0.13 sec)

    mysql> desc profilguru;
    +——–+————-+——+—–+———+—————-+
    | Field | Type | Null | Key | Default | Extra |
    +——–+————-+——+—–+———+—————-+
    | id | int(2) | NO | PRI | NULL | auto_increment |
    | nama | varchar(50) | NO | | NULL | |
    | matpel | varchar(30) | NO | | NULL | |
    +——–+————-+——+—–+———+—————-+
    3 rows in set (0.01 sec)
Oke, jadi table diatas untuk menampung profil guru di sekolah, tapi dibuat lebih simpel saja. Hanya ada kolom id, nama dan mata pelajaran yang dibawanya. Lalu, masalahnya dimana? Oh nanti dulu dunk :p Yuk kita lanjut dengan menginput record-nya. Berikut log-nya:
    mysql> insert into profilguru values(”,’Aa Ezha’,’PHP’);
    Query OK, 1 row affected, 1 warning (0.07 sec)

    mysql> insert into profilguru values(”,’Aa Ezha’,’B.Arab’);
    Query OK, 1 row affected, 1 warning (0.02 sec)

    mysql> insert into profilguru values(”,’Ana Rita Yuli’,’Kebidanan’);
    Query OK, 1 row affected, 1 warning (0.04 sec)

    mysql> insert into profilguru values(”,’Uba Ler’,’Networking’);
    Query OK, 1 row affected, 1 warning (0.03 sec)

    mysql> insert into profilguru values(”,’Deni Mikrocpu’,’Networking’);
    Query OK, 1 row affected, 1 warning (0.04 sec)

    mysql> insert into profilguru values(”,’Deni Mikrocpu’,’Visual Basic’);
    Query OK, 1 row affected, 1 warning (0.04 sec)
Oke, disana terlihat ada beberapa “guru” yang mengajar lebih dari 1 mata pelajaran. Lalu masalahnya adalah, ketika kita ingin memunculkan daftar-daftar guru yang mengajar. Berikut contohnya:
    mysql> select nama from profilguru;
    +—————+
    | nama |
    +—————+
    | Aa Ezha |
    | Aa Ezha |
    | Ana Rita Yuli |
    | Uba Ler |
    | Deni Mikrocpu |
    | Deni Mikrocpu |
    +—————+
    6 rows in set (0.00 sec)
Nah, lihat kan disana jadi namanya dobel-dobel begitu :D Padahal kita kan pengennya..1 guru ya 1kali tampil. Terus, gimana dunk menanggulangi agar recordnya tidak dobel, mengulang atau kembar? Begini neh jadinya :)
    mysql> select distinct nama from profilguru;
    +—————+
    | nama |
    +—————+
    | Aa Ezha |
    | Ana Rita Yuli |
    | Uba Ler |
    | Deni Mikrocpu |
    +—————+
    4 rows in set (0.00 sec)
Yups, hanya ditambahkan query DISTINCT saja setelah SELECT. Jadi fungsi dari query DISTINCT adalah mencegah suatu record yang sama untuk muncul lebih dari 1 kali. Terlihat jelas bedanya ketika menjalankan query SELECT tanpa DISTINCT, bukan? Ehm..mungkin sekian dulu tutorial pendeknya :) Semoga bermanfaat untuk semuanya. di colong dari http://www.aaezha.com/2012/11/mysql-menghindari-record-kembar-dengan-distinct.html

Thursday, October 25, 2012

Permalink Layaknya Wordpress Dengan cara yang paling bodoh Part 2


Menyambung tulisan gw tentang Permalink Layaknya Wordpress Dengan cara yang paling bodoh
Jadi masih ingat khan dengan ini.


[QUERY_STRING] =>
[REQUEST_URI] => /permaling/woi-cobain-permalinkdonk

Sebenarnya dengan gw kasih salah satu core permalink gw harusnya udah pada ngarti tapi untuk lebih jelas ini dia...

Gw akan mulai dengan permalink seperti ini
http://localhost/permaling/id/334/woi-cobain-permalinkdonk 

kita print dulu REQUEST_URInya
echo $_SERVER['REQUEST_URI'];

hasilnya adalah jreng jreng...

/permaling/id/334/woi-cobain-permalinkdonk

karena ini gw di subdirectory maka directorynya juga muncul yaitu permaling.
Logikanya seperti ini, tangkap apapun setelah directory /permaling/ codenya adalah

$localpath = '/permaling/'; //namasubdirectory
$gettingpath = explode ($localpath, $_SERVER['REQUEST_URI']);
print_r($gettingpath); 
hasilnya adalah

Array ( [0] => [1] => id/334/woi-cobain-permalinkdonk )

Kenapa kok gw kasih id? karena ntar itu untuk membedakan, jadi elu bisa macem macem slug, yaitu media, images, pdf, atau apalah. kedua itu ntar bisa sangat ringan kalau buat nyari ke dalam database.. karena dalam database itu ruar biasa buanyak....

sekarang kita buat pembeda antara root directory ( tempat di mana cms atau subdirectory dari script ini ) atau post, atau media lain yang mungkin elu akan buat nanti...

$localpath = '/permaling/'; //namasubdirectory
$gettingpath = explode ($localpath, $_SERVER['REQUEST_URI']);

$gettingid = explode ('/',$gettingpath[1]);

/*
print_r ($gettingid);
Array
(
    [0] => id
    [1] => 334
    [2] => woi-cobain-permalinkdonk
)
*/

if ($gettingid[0] == "id") {
//maka disini adalah post ( single post kalau di wordpress )
// kalau gw sih begini dah scriptnya...
//$rsa = "SELECT * FROM `isi` WHERE `ftubeid` = '$gettingid[1]' LIMIT 1";
//code seterusnya dari sql itu... ( very light, dan sangat makan kecil dari resouce )

echo "ini single post";
}elseif(($_SERVER['REQUEST_URI'] == $localpath) OR ($gettingid[0] == "index.php") )
{
//maka disini adalah index, 
// Usahakan index ini yang paling akhir dari logicnya soalnya ntar kalau elu bikin search ala wordpress, atau media lain seperti mungkin pdf, atau video, atau apalah jaminan belibet ntar...
echo "index.php";
} else {
//disini elu bisa bikin search query atau 404 error aja...
echo "error ";
}

sekarang coba elu akses ke

http://localhost/permaling
atau
http://localhost/permaling/index.php

pasti muncul tulisan index.php khan?

trus coba lagi ke
http://localhost/permaling/id/333/manga

akan muncul ini single post
trus coba lagi ke

http://localhost/permaling/?nejfneuifuanufuefrne8biubeufbffb

akan muncul error, karena permalink tidak di ketahui... lumayanlah bisa buat protektif dari sql injection... jadi dia cuma bekerja sesuai dengan syarat dan peraturan yang kita buat...

Okeh done sementara itu mungkin bisa kita sambung lagi kapan kapan

Tuesday, October 23, 2012

Permalink Layaknya Wordpress Dengan cara yang paling bodoh


Nah kali ini gw pengen nulis soal gimana sih di php tentunya.... sebenarnya teorinya adalah guampang poll. Gw nggak akan bahas mod_rewrite yang jelas jelas udah banyak di bahas di internet.

Saran gw elu musti apa yang gw katain yaitu
  1. Mod_rewrite dengan apache ( hampir semua hostingan yang mendukung wordpress udah pasti support, lha wong wordpress yang super ribet itu aja bisa di handle. Masak kode kita yang menjiplak  teorinya wordpress nggak bisa di install khan lucu )
  2.  Sedikit pengetahuan tentang HTACCESS dan PHP

Okeh lanjut... Elu musti nginstall xampp, notepad++, ke Senjata Tajam sajalah. kecuali elu custom install php dan mysql sendiri.. but bagi gw sendiri gw nggak ingin menambah beban komputer gw dengan service autorun  dsbnya...walaupun toh sebenarnya bisa di disable juga. tapi I hate it.. jawabannya itu ajalah untuk sementara.. ( OS windows aja  ya, maklum lagi malas buka linux )

 liat dulu neeh wordpess htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress
Tuh khan simple banget...  btw itu urlnya http://localhost/wordpress/ begitu yak... jadi di subdirectory..

Nggak perlu di bahas kode di atas khan?
 lha wong intinya cuma apapun yang di request(query ya lebih enak nyebutnya ) oleh http setelah directory /wordpress/ akan di handle oleh dalemannya wordpress dan gw jamin dalemannya si wordpress ini lebih rumit daripada dalemannya cewek  but its oke karena akan gw simple khan... ( maklum gw nggak pengen ribet :P )

Pilihan pertama adalah elu membedah seluruh dalemannya si wordpress, bhnya, celdam, dsbnya , abis itu elu teliti lebih jauh dan jauh, satu persatu dah... inci demi inci... ( mabok mabok dah lu )...

Pilihan kedua...
Cukup elu PRINT $_SERVER[], ntar khan ketahuan tuh :D isinya.. jaminan lebih asik daripada buka daleman yang lain.

contoh gw ciptain folder di folder htdocs di xampp namanya permaling, di dalamnya gw ciptain 1 file
  1. index.php
  2. .htaccess
isinya cuma gini doank .htaccess
RewriteEngine On
RewriteBase /permaling/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /permaling/index.php [QSA,L]
index.php
<?php

print_r ($_SERVER);
nah kita coba deh kasih gini, localhost/permaling/woi-cobain-permalinkdonk
nampak tulisan kacau khan... biar lebih enak bacanya buka source codenya dengan ctrl+u di mozilla atau elu klik kanan di pagenya lalu cari deh kata kata source code.

hasilnya adalah ini

Array ( [REDIRECT_UNIQUE_ID] => UIXW6MCoAggAACI4Z8QAAAD5 [REDIRECT_STATUS] => 200 [UNIQUE_ID] => UIXW6MCoAggAACI4Z8QAAAD5 [HTTP_HOST] => localhost [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20120424 Firefox/12.0 PaleMoon/12.0 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip, deflate [HTTP_CONNECTION] => keep-alive [PATH] => C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\EmEditor;C:\xampp-php5.2\phantomjs [SystemRoot] => C:\WINDOWS [COMSPEC] => C:\WINDOWS\system32\cmd.exe [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH [WINDIR] => C:\WINDOWS [SERVER_SIGNATURE] => <address>Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 Server at localhost Port 80</address> [SERVER_SOFTWARE] => Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 [SERVER_NAME] => localhost [SERVER_ADDR] => 127.0.0.1 [SERVER_PORT] => 80 [REMOTE_ADDR] => 127.0.0.1 [DOCUMENT_ROOT] => C:/xampp-php5.2/htdocs [SERVER_ADMIN] => admin@localhost [SCRIPT_FILENAME] => C:/xampp-php5.2/htdocs/permaling/index.php [REMOTE_PORT] => 4318 [REDIRECT_URL] => /permaling/woi-cobain-permalinkdonk [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /permaling/woi-cobain-permalinkdonk [SCRIPT_NAME] => /permaling/index.php [PHP_SELF] => /permaling/index.php [REQUEST_TIME] => 1350948584 [argv] => Array ( ) [argc] => 0 )




yang perlu kita lihat cuma ini ajalah...
[QUERY_STRING] => 
[REQUEST_URI] => /permaling/woi-cobain-permalinkdonk
sebenarnya ntar kalau lebih lanjut kita akan mainan query string, tapi untuk sementara nggak usahlah. Gw akan mainan
[REQUEST_URI] => /permaling/woi-cobain-permalinkdonk

jadi teorinya adalah, kita cut folder pemaling abis itu gantiin abis itu bisa kita cari di dalam database kita apakah ada slug yang  woi-cobain-permalinkdonk .
jadi kita akan mengatur slugnya di database...di simpan tepatnya...

Ohya tadi blum gw kasih teorinya ya kelupaan hehehehe...
begini:

htaccess -> [baca:dilempar] ke index.php, di index.php ntar tangkep slugnya lalu check apakah di database ada ID atau slug yang di cari. liat bagan:

.htaccess-> index.php -> catchslug -> checkslugdidatabase -> jika ada tampilkan isi 
 Piece of cake, huh?

Kalau gw sih lebih enak slug itu gw bikin dengan dengan format seperti ini, /permaling/UNIQUEID/baru-permalink  ( kenapa musti ID, jadi ntar slugnya bisa di mainkan dengan enak.. heheheheh :D )

Ini adalah source code gw untuk project filestube, core dari inti yang memegang peranan penting dalam permalink

Messy code, but works... :D

//print $fulldomain;

//print_r ($_SERVER);

$gettingpath = explode ($localpath, $_SERVER['REQUEST_URI']);

//-- pecah berdasarkan /

//print_r ($gettingpath);

//$gettingid = explode ('/',$gettingpath[1]);

//-- cobain dengan preg_replace untuk menganti semua karakter kecuali angka

//$testpreg = preg_replace("/[^0-9-]/", '' ,$gettingpath );

//print_r ($testpreg);

//-- Pecah dengan karakter dashed (-)

//echo $gettingid[0];

//print_r($_SERVER);

//-- Mungkin di coba apakah explode lebih ringah daripada preg_replace

$gettingid = explode ('/',$gettingpath[1]);

//ob_start("ob_gzhandler"); //harus di hapusya

//print_r ($gettingid);

if (isset($SfSE) && $SfSE == true) {

//Ini bagian search engine

}elseif( isset($_GET['s']) && $_GET['s'] != NULL) {

//sanitaze dengan built-in php filter   

$s = filter_var($_GET['s'], FILTER_SANITIZE_STRING);

//fuck with everything they have called html

$s = strip_tags($s);

//Be more freaks, sanitaze that

$s = cleanInput($s);

$sa = Slug($s);

//print ''.$fulldomain.'search/'.$s.'';

//ob_start();

header("Location: ".$fulldomain."s/".$sa."");

//ob_end_flush();

}elseif($gettingid[0] == "s") {

$s = str_replace(array('_','-','%20'), '+',$gettingid[1]);

include ('themes/search.php');

}elseif ($gettingid[0] == "id") {

//if ID

include ('themes/singledownload.php');

}elseif(preg_match('([^/]+$)',$_SERVER['REQUEST_URI'], $bc)){

$s = str_replace(array('_','-','%20'), ' ',$bc[0]);

$s = filter_var($s, FILTER_SANITIZE_STRING);

$sa = Slug($s);

header("Location: ".$fulldomain."s/".$sa."");

}elseif(($_SERVER['REQUEST_URI'] == $localpath) OR ($gettingid[0] == "index.php") )

{

include ('themes/index.php');

}

Okeh tutornya selesai dulu sampai disini, ntar di lanjut dengan bagian database dan sebagainya, mungkin creating custom themes di cms..







Warm regards
radiaku

vnPButils [Update v1.2] – Side-load and Managing Applications on PlayBook


vnPButils – PlayBook Utilities, you can manage applications on your PlayBook with friendly user interface.
Main features:
  • Side-load bar files into PlayBook
  • Managing Applications installed on PlayBook: list, check status, launch, terminate or uninstall
  • Create BAR file from BDM backup files
Requirements:
  • On Windows: has installed Java Runtime Environment (JRE)
  • On PlayBook: enable Development Mode (Options -> Security -> Development Mode: ON)
Some images




Download vnPButils v1.2