Code snippets

Insert watersign to all your images using php

Create wm.php and insert:


<?php
//we tell the server to treat this file as if it wore an image
header('Content-type: image/jpeg');
//image file path
$img = $_GET['src'];
//watermark position
$p = $_GET['p']; if(!$p) $p = 'br';
/*
p can be anything from the following list:
tl = top left
tc = top center
tr = top right
cl = center left
c = center of the image
cr = center right
bl = bottom left
bc = bottom center
br = bottom right
*/
//watermarked image quality
$q = $_GET['q'];
//if the quality field is missing or is not on the 0 to 100 scale then we set the quality to 93
if(!$q || $q<0 || $q>100) $q = '93';
$filetype = substr($img,strlen($img)-4,4);
$filetype = strtolower($filetype);
if($filetype == ".gif") $image = @imagecreatefromgif($img);
if($filetype == ".jpg") $image = @imagecreatefromjpeg($img);
if($filetype == ".png") $image = @imagecreatefrompng($img);
if (!$image) die();
//getting the image size for the original image
$img_w = imagesx($image);
$img_h = imagesy($image);
//if the filename has 150x150 in it's name then we don't apply the watermark
if (eregi("150x150", $img)) {
    imagejpeg($image, null, $q); die();
} else {
    $watermark = @imagecreatefrompng('bwmark.png');
}
/*
//if you want to use the watermark only on bigger images then use this instead of the condition above
if ($img_w < "150") {//if image width is less then 150 pixels     imagejpeg($image, null, $q); die(); } else {     $watermark = @imagecreatefrompng('bwmark.png'); } */ //getting the image size for the watermark $w_w = imagesx($watermark); $w_h = imagesy($watermark); if($p == "tl") {     $dest_x = 0;     $dest_y = 0; } elseif ($p == "tc") {     $dest_x = ($img_w - $w_w)/2;     $dest_y = 0; } elseif ($p == "tr") {     $dest_x = $img_w - $w_w;     $dest_y = 0; } elseif ($p == "cl") {     $dest_x = 0;     $dest_y = ($img_h - $w_h)/2; } elseif ($p == "c") {     $dest_x = ($img_w - $w_w)/2;     $dest_y = ($img_h - $w_h)/2; } elseif ($p == "cr") {     $dest_x = $img_w - $w_w;     $dest_y = ($img_h - $w_h)/2; } elseif ($p == "bl") {     $dest_x = 0;     $dest_y = $img_h - $w_h; } elseif ($p == "bc") {     $dest_x = ($img_w - $w_w)/2;     $dest_y = $img_h - $w_h; } elseif ($p == "br") {     $dest_x = $img_w - $w_w;     $dest_y = $img_h - $w_h; } imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $w_w, $w_h); imagejpeg($image, null, $q); imagedestroy($image); imagedestroy($watermark); ?>

Create index.php and insert:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<img src="wm.php?p=bl&q=100&src=INSERT-YOUR-IMAGE.jpg">
</body>
</html>

source: http://dolcepixel.com/how-to-watermark-all-your-uploaded-images/

By michael schouman on February 22, 2012 | Code snippets | A comment?

Lilupophilupop multiple domain infection checker script

The following script can be used to check multiple domains for infection of the lilupophilupop.com SQL injection attacks. If you are a resposible webdeveloper then you might want to use this to check if one of your sites are infected.

First of all create a domains.txt file where you have a list of all the domains that you want to check, seperated by an enter.

Then find a webserver running php with the curl extension installed.

Paste the following code in a check.php file and upload this and the domains.txt to you webserver.

[edit]
Due to some problems with the encoding that wordpress does the following code might not work corretly. So i would recomend that you copy paste from the following link: checker.txt

<?php
// define variables
$file = "domains.txt";
$lines = file($file);

foreach($lines as $line) {
        // this string replace is done to remove the breaks from the textfile please replace the BACKSLASH with a real backslash
        $line = str_replace("BACKSLASH n", "", $line);
        $url = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site%3A'.$line.'+"<script+src%3D"http%3A%2F%2Flilupophilupop.com%2F"';         // sendRequest
         $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_REFERER, 'schouman.info');
                $body = curl_exec($ch);
                curl_close($ch);
                // now, process the JSON string
         $json = json_decode($body);
         if (empty($json->responseData->results)){
                echo "<b>".$line."</b>";
                echo "";
                echo "clean";
        } else {
                echo "<b>".$line."</b>";
                echo "";
                echo "Number of results: ";
                print_r($json->responseData->cursor->estimatedResultCount);
                echo "";
                echo "Check all the results: <a href='";
                print_r($json->responseData->cursor->moreResultsUrl);
                echo "'>";
                print_r($json->responseData->cursor->moreResultsUrl);
                echo "</a>";
        }

        echo "";
}
?>

Run the script in your browser and see if your website was infected by the lilupophilupop.com SQL injection attacks.

For more info check:

http://isc.sans.edu/diary/Lilupophilupop+tops+1million+infected+pages/12304

http://tweakers.net/nieuws/79079/sql-besmetting-infecteert-meer-dan-een-miljoen-paginas.html

Leave a comment if there are faults or errors.

Quick mysql database back up for webdevelopers

<?php 

// Stuff for db connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';

backup_tables($dbhost,$dbuser,$dbpass,$dbname);

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*') {
    $link = mysql_connect($host,$user,$pass);
    mysql_select_db($name,$link);

    //get all of the tables
    if($tables == '*') {
        $tables = array();
        $result = mysql_query('SHOW TABLES');

        while($row = mysql_fetch_row($result)) {
            $tables[] = $row[0];
        }
    } else {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    //cycle through
    foreach($tables as $table) {
        $result = mysql_query('SELECT * FROM '.$table);
        $num_fields = mysql_num_fields($result);

        $return.= "DROP TABLE IF EXISTS '.$table.';";
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
        $return.= "nn".$row2[1].";nn";

        for ($i = 0; $i < $num_fields; $i++) {
            while($row = mysql_fetch_row($result)) {

                $return.= 'INSERT INTO '.$table.' VALUES(';

                for($j=0; $j<$num_fields; $j++) {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("n","\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }                 }                 $return.= ");n";             }         }         $return.="nnn";     }     //save file     //$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');     //fwrite($handle,$return);     //fclose($handle);     // Or just echo the output     echo $return; } ?>
By michael schouman on November 30, 2011 | Code snippets | A comment?

Uw website beveiligen met een .htaccess

Met htaccess is het mogelijk om de toegang tot een directory te ‘sturen’ (Linux webruimte). Dit doet u door een ascii-file genaamd .htaccess (let op de punt) te plaatsen in de betreffende directory. In deze file worden opdrachten opgenomen. Een htaccess file werkt voor de directory waarin de file geplaatst wordt en de directories daaronder. Binnen een website mogen meerdere files gebruikt worden.
Afsluiten directory-listing

In veel gevallen is het niet wenselijk dat bezoekers de inhoud van directories kunnen bekijken. Dit kan opgelost worden door in iedere directory het bestand index.html te zetten. Index.html wordt nl. altijd automatisch door de browser geopend, waardoor een directory listing voorkomen wordt. Voor een uitgebreide website is dit omslachtig. Daarnaast is het zeer omslachtig deze pagina’s aan te passen. Htaccess is een efficiëneter oplossing.

    Maak een .htaccess file
    zet hierin het commando options -indexes

Het is nu niet meer mogelijk om de directory-inhoud van de huidige en de ondergelegen directory’s op te vragen. Plaats de .htaccess file in de www-directory en uw hele site is beschermd. Variaties:

    options +indexes
    zet de listing aan.
    IndexIgnore *.gif *.jpg
    Sta directory listing toe, maar geef geen gif en jpg-files weer.

Bezoekers doorsturen naar een andere pagina

Met de toevoeging: Redirect /dir/page1.htm http://mydomain/somedir/page2.htm. Is het mogelijk om bezoekers van pagina1.htm door te sturen naar http://mydomain/somedir/page2.htm.
Afvangen fouten

U kent ongetwijfeld de lelijke 404 foutmelding die u ziet als een bepaald pagina niet meer bestaat. Deze fouten zijn op te vangen. Op het moment dat er een dergelijke fout ontstaat, kan de bezoeker doorgestuurd worden naar een door u te bepalen pagina. Voeg (een van de) regels toe aan uw .htaccess file:

ErrorDocument 403 /somedir/page1.html
ErrorDocument 404 /somedir/page2.html
200 OK
201 Created
202 Accepted
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Moved Temporarily
303 See Other
304 Not Modified
305 Use Proxy
400 Bad Request
401 Authorization Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable (encoding)
407 Proxy Authentication Required
408 Request Timed Out
409 Conflicting Request
410 Gone
411 Content Length Required
412 Precondition Failed
413 Request Entity Too Long
414 Request URI Too Long
415 Unsupported Media Type
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

Afsluiten directory met een wachtwoord

Met htaccess is het mogelijk om een bepaalde directoy af te sluiten met een wachtwoord. Wilt u een of meerdere gebruikers toegang geven, plaats dan een .htaccess file met de volgende inhoud:

AuthUserFile /home/gebruiker/home/gebruiker/www/toegang/.htpasswd
AuthGroupFile /dev/null
AuthName SecretWebsite
AuthType Basic

require valid-user

In dit voorbeeld wordt het wachtwoord en gebruikersnaam van de mensen die toegang mogen krijgen, opgeslagen in de directory /home/gebruiker/home/gebruiker/www/toegang/. Om een gebruiker toe te voegen moet u met ssh (secure telnet) inloggen op de server om een wachtwoordfile (.htpasswd) te creeren. De inloggegevens voor ssh zijn gelijk aan de inloggegevens voor ftp. Ga naar de juiste directory (in dit geval /home/gebruiker/home/gebruiker/www/toegang/) en voer het volgende commando uit:

htpasswd -c .htpasswd username

Vervang username met de naam waarmee u wilt inloggen. De server vraagt nu om een wachtwoord en slaat dit gecodeerd op. De directory is nu beveiligd. Wilt u meerdere gebruikersnamen toevoegen? Gebruik dan na de eerste keer:

htpasswd .htpasswd username

Als u gebruikersnamen wilt wissen, opent u .htpasswd en verwijderd de gewenste regel(s).
Beveiligen van de .htaccess file zelf

Natuurlijk moet ook de .htaccess file beveiligd worden. Als iemand deze file kan benaderen, zou deze persoon meteen weten waar bijvoorbeeld de .htpasswd file staat. Voeg daarom toe:

order allow,deny
deny from all

De eerste regel geeft aan dat het commando ‘deny’ alleen geldt voor de file .htaccess. De derde regel geeft aan dat niemand toegang heeft (iedere toegang wordt geweigerd). Het opvragen van deze file zal nu resulteren in een error 403 (Forbidden).

Als extra beveiliging kan aan de file via ssh de permissie 644 gegeven worden (chmod 644).

By michael schouman on November 28, 2011 | Code snippets | A comment?

php echo only a filename without extension


$file = checkoutthisfile.exe

echo str_replace(strstr($file, '.'), '', $file);
By michael schouman on October 13, 2011 | Code snippets | A comment?