블로그 이미지
괴스트

예진이와 고고씽!!

Rss feed Tistory
Dev/php 2010/03/26 17:41

fopen이 안되는 서버에서 회피하는법

크리에이티브 커먼즈 라이선스
Creative Commons License
php.ini 파일에 allow_url_fopen=on으로 설정되어 있으면, URL 주소로 파일 읽어올 때 다음과 같이 처리하면 됩니다.

 


    <?php

    $fp = fopen($url, "r");

    

    while (!feof($fp)) {

        $retVal .= fgets($fp, 1024);

    }

    

    fclose($fp);

    echo($retVal);

    ?>

    

    하지만 allow_url_fopen=off로 설정되어 있는 경우,

    일단 php.ini 파일을 수정하면 됩니다.

    벗뜨~~ 웹 호스팅을 하는 경우 php.ini 파일을 직접 수정할 수 없는 경우가 있죠~

    

    이런 경우의 해결책을 찾아보니 다음과 같이 socket을 이용해 URL주소를 읽어오는 방법이 있었슴다..

    

    <?php

        $url = "URL 주소";

    

        $info = parse_url($url);

        $send = "POST " . $info["path"] . " HTTP/1.1\r\n"

            . "Host: " . $info["host"] . "\r\n"

            . "Content-type: application/x-www-form-urlencoded\r\n"

            . "Content-length: " . strlen($info["query"]) . "\r\n"

            . "Connection: close\r\n\r\n" . $info["query"];

    

        $fp = fsockopen($info[host], 80);

        fputs($fp, $send);

    

        $start = false;

        $retVal = "";

    

        while (!feof ($fp)) {

            $tmp = fgets($fp, 1024);

            if ($start == true) $retVal .= $tmp;

            if ($tmp == "\r\n") $start = true;

        }

    

        fclose($fp);

    

        echo($retVal);

    ?>




 

추가적으로 GET 방식 호출은 다음과 같이 할 수도 있습니다.

 

<?php

    $url = "URL 주소";   

    $info = parse_url($url);

 

    $host = $info["host"];

    $port = $info["port"];

    if ($port == 0) $port = 80;

 

    $path = $info["path"];

    if ($info["query"] != "") $path .= "?" . $info["query"];

 

    $out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";

 

    $fp = fsockopen($host, $port, $errno, $errstr, 30);

    if (!$fp) {

        echo "$errstr ($errno) <br>\n";

    }

    else {

        fputs($fp, $out);

        $start = false;

        $retVal = "";

 

        while(!feof($fp)) {

            $tmp = fgets($fp, 1024);

            if ($start == true) $retVal .= $tmp;

            if ($tmp == "\r\n") $start = true;

        }

 

        fclose($fp);

        echo $retVal;

    }
?>
저작자 표시
Dev/php 2010/03/24 15:54

리사이징 함수 사용법

크리에이티브 커먼즈 라이선스
Creative Commons License

UPDATE: I’ve added support for PNG alpha transparency which makes this class significantly more useful. Changelog in the class code below.

I keep misplacing this class so I figured I’d post it here so that I know where it is.

I wrote/assembled this class because I wasn’t happy with any of the image manipulation libraries out there. They are either way too complex with a steep learning curve or didn’t work all that great. (I didn’t see any reason to load up a class with 3,000 lines of code just to resize or rotate an image.)

So here it is, a simple class that allows you to open an image, perform common operations, and save. There are no bells and whistles or anything exciting here. Just a collection of commonly used image manipulation functions: Rotate, Flip, Resize, Thumbnail (square and regular), and Crop.

A lot of the class code is original but some of it has been gathered over my life as a programmer from long lost sources. If you recognize your work, leave a comment and I’d be happy to cite you!

The concept is pretty simple.  You open an image, and then perform your operations before saving the output, or writing it to a different file.  The code is not optimized for batch processing of images, so be warned.  It is mainly for when you are accepting uploads of profile photos or similar and need to resize it and generate thumbnails and all that shtuff.  Enjoy and comment any questions/improvements/problems/etc.!

Creation – Getting Started

Before you can start working on an image, you must create an instance of the Image class.

All of these examples use Ephective’s logo as the test image:

view source
print?
1 $I = new Image('ephective.png');

You can also create an empty instance of Image by doing “$I = new Image();” and open, or set the image at a later time:

  • $I->open( file ) – Open a file from disk
  • $I->resource( image resource ) – Set an image resource

Saving

Before I’ll go on to explaining all the functions, you should first know how to save your work.

If you have opened a file from disk, you will probably want to save your changes back to that file.

view source
print?
1 // this will save your changes back to the file that you've opened
2 // if you didn't open a file (passed a resource) this function will not work
3 $I->save()

The second option is to write your changes to a different file.

view source
print?
1 $I->write( 'my_new_file.png' )

You could also get the image resource and do some additional custom processing on your own:

view source
print?
1 // now contains the image resource, you could write it to disk if you'd like
2 $res = $I->resource();

Rotate: $I->rotate( $degrees [ , $bkg ] )

Now that we have the image loaded, we can begin using the simple functions to manipulate it.

Rotate can rotate the image by any number of degrees. If you rotate by anything except a multiple of 90, you will end up with the image appearing on an angle. This will automatically resize the dimensions of the image and set background color using the optional $bkg (defaults to black).  The color must be allocated with imagecolorallocate or whatever it is… an example exists at the end of this page.

view source
print?
1 // rotates the image 38 degrees
2 $I->rotate(38);

Before: After:

Notice how the image is larger and has a black background fill.

There are several shortcut functions to rotate an image and an additional special auto_rotate function.

  • $I->rotate( $degrees [ , $bkg=0 ] )
  • $I->rotate_left()
  • $I->rotate_right()
  • $I->rotate_180() – This turns the image upside down
  • $I->auto_rotate() – There is also a special function called auto_rotate. auto_rotate will check to see if there is any orientation information in the exif data for the image. If there is, the image will automatically be rotated to the correct orientation. Note: This function only works if you have the PHP exif extension.

Here is an example of rotate_left:

view source
print?
1 $I->rotate_left();

rotate_left: rotate_right: rotate_180:

Full Snippet:

view source
print?
1 require 'Image.php';
2   
3 $I = new Image('ephective.png');
4   
5 $I->rotate(38);
6 $I->save(); // will save the changes back to the file
7 $I->destroy(); // free the memory

Flip: $I->flip( $bFlipH [ , $bFlipV=false ] )

Flip will mirror an image in a certain direction—either horizontally or vertically.

There are a few shortcut functions to flip an image.

  • $I->flip( $bFlipH [ , $bFlipV=false ] )
  • $I->flip_h()
  • $I->flip_v()
  • $I->flip_both() – This is the same as rotate_180 only much more processor intense. Just use rotate_180
view source
print?
1 require 'Image.php';
2   
3 $I = new Image('ephective.png');
4   
5 $I->flip_v();
6 $I->save(); // will save the changes back to the file

Before: flip_v: flip_h: flip_both:

Resize: $I->resize( $newdim [ , $square=false [ , $bHeight=false [ , $resample=true ] ] ] )

You can only resize images and maintain proportions. I figured, in most day-to-day image operations you are resizing photos and such, so why would you want to squish the picture? So, to resize, you will only need to specify the largest dimension you want to allow. To make that a little more clear, think of Facebook profile photos. They always resize to a width of around 200 pixels. This results in some photos being much taller than others, but they are always 200 px wide.

The basic code to do something similar with Image is:

view source
print?
1 $I->resize ( 200 );

There are the following resize functions:

  • $I->resize( $newdim [ , $square=false [ , $bHeight=false [ , $resample=true ] ] ] ) – By default, resize performs the same operation as width. Setting bHeight to true would make resize perform the same as height.
  • $I->width( $newdim [ , $square=false [ , $resample=true ] ] )
  • $I->height( $newdim [ , $square=false [ , $resample=true ] ] )
  • $I->resize_1600()
  • $I->resize_1200()
  • $I->resize_1024()
  • $I->resize_800()
  • $I->resize_640()

When settings the $newdim, you can give an actual pixel count ($newdim=200;), a decimal percentage less than 1 ($newdim=0.5;), or a string percentage ($newdim=’50%’;).

Before: width(60) pixels: width(‘50%’) string percent: width(.3) decimal:

Thumbnail: $I->thumbnail( $dest, $newdim [ , $square=NULL [ , $bHeight=false [ , $out=false [ , $resample=true ] ] ] ] )

Thumbnail is identical to resize except thumbnail does not alter the classes image resource at all. This means that the original image is left untouched.

Crop: $I->crop( $top [ , $right=0 [ , $bottom=0 [ , $left=0 ] ] ] )

Instead of specifying a selection inside the current image, crop works by letting you specify how much to trim off the edges. So if you wanted to trim 50 pixels off the top and bottom sides of the image, you could do the following:

view source
print?
1 $I->crop(50, 0, 50);

There are the following resize functions:

  • $I->crop( $top [ , $right=0 [ , $bottom=0 [ , $left=0 ] ] ] )
  • $I->crop_top( $px )
  • $I->crop_right( $px )
  • $I->crop_bottom( $px )
  • $I->crop_left( $px )
  • $I->crop_h( $px ) – Top and bottom
  • $I->crop_v( $px ) – Left and right
  • $I->crop_all( $px ) – All sides (contract)

Before: crop_all(10): crop(18, 25, 28, 20): crop_v(20): crop_h(20): crop_all(20):

Combining Modifications

You can combine as many modifications as you’d like:

view source
print?
01 $I = new Image('ephective.png');
02   
03 // loop through and incrementally change the color and rotate
04 for ( $i=0; $i < 255; $i+=10 )
05 {
06     $color = imagecolorallocatealpha( $I->resource(), 255, $i, $i, 0 );
07     $I->rotate(5, $color);
08 }
09   
10 // each rotation increases the images dimensions, shrink it down to a reasonable size
11 $I->width(.3);
12   
13 // write the output to a separate file
14 $I->write('ephective-combine.png');
15   
16 // free the memory
17 $I->destroy();

view source
print?
001 // v.0.2.1
002 /*
003 CHANGELOG
004   
005 0.2.1       -Added output() screen, in addition to save/write
006             -Added support for PNG transparency
007             -Made contenttype the PNG by default
008   
009 */
010 class Image
011 {
012     var $res            = NULL;
013     var $source         = NULL;
014     var $contenttype    = IMAGETYPE_PNG;
015   
016     /***
017      * Constructor
018      * $src_or_resource: src is the path to an image.  If it exists, the image will be automatically opened
019      *      can also be an already created image resource
020      */
021     function Image ($src_or_resource=NULL)
022     {
023         if( ! is_null($src_or_resource) )
024             if ( is_resource($src_or_resource) )
025                 $this->resource($src_or_resource);
026             else
027                 $this->open($src_or_resource);
028     }
029   
030     /***
031      * Rotate the active image
032      * $degrees: number of degrees to spin the image, if this is something like
033      *      45, it will leave gaps in the frame which will be filled in by $bkg
034      * $bkg: If image is rotated in a way that does not fill the frame, this is the color that will be used
035      */
036     function rotate ($degrees, $bkg='0')
037     {
038         $im = imagerotate( $this->res, $degrees, $bkg );
039         imagedestroy($this->res);
040         $this->res = $im;
041     }
042   
043     /***
044      * Rotate image right
045      * Shortcut function that will rotate the image to the right
046      */
047     function rotate_right() { $this->rotate(270); }
048   
049     /***
050      * Rotate image 180 degrees
051      * Shortcut function that will rotate the image 180 degrees
052      */
053     function rotate_180() { $this->rotate(180); }
054   
055     /***
056      * Rotate image left
057      * Shortcut function that will rotate the image to the left
058      */
059     function rotate_left() { $this->rotate(90); }
060   
061     /***
062      * Attempt to automatically rotate the image based on exif data
063      *  a lot of digital cameras store orientation data of the camera
064      *      this will use that to automatically fix an images orientation
065      *
066      *      Note: This will only work if you have the function exif_read_data
067      *          which is part of PHPs exif data extension
068      */
069     function auto_rotate() {
070         if( ! function_exists('exif_read_data') ) return false;
071         $exif = exif_read_data($this->source);
072   
073         $ort = $exif['IFD0']['Orientation'];
074          switch($ort) // http://www.impulseadventure.com/photo/exif-orientation.html
075          {
076             case 1: // regular, do nothing
077                 break;
078             case 2:
079                 return $this->flip_h();
080             case 3:
081                 return $this->rotate_180();
082             case 4:
083                 return $this->flip_v();
084             case 5:
085                 return ($this->flip_h() && $this->rotate_right());
086             case 6:
087                 return $this->rotate_right();
088             case 7:
089                 return ($this->flip_h() && $this->rotate_left());
090             case 8:
091                 return $this->rotate_left();
092          }
093     }
094   
095     /***
096      * Will flip an image (mirror it)
097      *
098      * $bFlipH: flip horizontal  (true/false)
099      * $bFlipV: flip vertical (true/false)
100      *
101      */
102     function flip($bFlipH, $bFlipV=false)
103     {
104         $imgsrc = $this->res;
105         $width = imagesx($imgsrc);
106         $height = imagesy($imgsrc);
107         $imgdest = imagecreatetruecolor($width, $height);
108         $this->prepare($imgdest);
109   
110         for ($x=0 ; $x<$width ; $x++)
111         {
112             for ($y=0 ; $y<$height ; $y++)
113             {
114                 if ($bFlipH && $bFlipV) imagecopy($imgdest, $imgsrc, $width-$x-1, $height-$y-1, $x, $y, 1, 1);
115                 else if ($bFlipH) imagecopy($imgdest, $imgsrc, $width-$x-1, $y, $x, $y, 1, 1);
116                 else if ($bFlipV) imagecopy($imgdest, $imgsrc, $x, $height-$y-1, $x, $y, 1, 1);
117             }
118         }
119   
120         $this->res = $imgdest;
121         imagedestroy($imgsrc);
122     }
123   
124     /***
125      * Shortcut functions to flip
126      */
127     function flip_h() { $this->flip(true, false); }
128     function flip_v() { $this->flip(false, true); }
129     function flip_both() { $this->flip(true, true); }
130   
131     /***
132      * Resizes an image to fit in a certain size
133      *
134      * $newdim:  This is the largest dimension the image can contain in
135      *      pixels.  If either of the measurements are larger than this size,
136      *      the image will be scaled
137      *
138      * $square: (true/false) make the new image square instead of keeping the dimensions
139      *
140      * $resample: high quality resize?  it is good to turn this off if you are doing
141      *      lots of conversions and quality isn't a huge issue
142      *      resample on/off is a noticeable difference in time
143      */
144     function resize($newdim, $square=false, $bHeight=false, $resample=true) {
145         $src_width  = imagesx( $this->res );
146         $src_height = imagesy( $this->res );
147         $src_w      = $src_width;
148         $src_h      = $src_height;
149         $src_x      = 0;
150         $src_y      = 0;
151   
152         $percent = false;
153         if ( $newdim < 1 )
154             $percent = $newdim;
155         elseif ( substr($newdim, -1) == '%' )
156             $percent = substr($newdim, 0, -1)/100;
157   
158         if ( false !== $percent )
159             $newdim = round( ($bHeight ? ($src_height*$percent) : ($src_width*$percent) ) );
160   
161         if ($square)
162         {
163             $dst_w = $newdim;
164             $dst_h = $newdim;
165             if ( ! $bHeight )
166             {
167                 $src_x = ceil( ( $src_width - $src_height ) / 2 );
168                 $src_w = $src_height;
169                 $src_h = $src_height;
170             }
171             else
172             {
173                 $src_y = ceil( ( $src_height - $src_width ) / 2 );
174                 $src_w = $src_width;
175                 $src_h = $src_width;
176             }
177         }
178         else
179         {
180             if ( ! $bHeight )
181             {
182                 $dst_w = $newdim;
183                 $dst_h = floor( $src_height * ($dst_w / $src_width) );
184             }
185             else
186             {
187                 $dst_h = $newdim;
188                 $dst_w = floor( $src_width * ($dst_h / $src_height) );
189             }
190         }
191         $dst_im = imagecreatetruecolor($dst_w,$dst_h);
192         $this->prepare($dst_im);
193         if ($resample)
194             imagecopyresampled($dst_im, $this->res, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
195         else
196             imagecopyresized($dst_im, $this->res, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
197   
198         imagedestroy($this->res);
199         $this->res = $dst_im;
200     }
201   
202     /***
203      * Shortcut functions to resize an image to certain, standard sizes
204      */
205     function width($newdim, $square=false, $resample=true) { $this->resize($newdim, $square, false, $resample); }
206     function height($newdim, $square=false, $resample=true) { $this->resize($newdim, $square, true, $resample); }
207     function resize_1600($square=false) { $this->resize(1600, $square); }
208     function resize_1200($square=false) { $this->resize(1200, $square); }
209     function resize_1024($square=false) { $this->resize(1024, $square); }
210     function resize_800($square=false) { $this->resize(800, $square); }
211     function resize_640($square=false) { $this->resize(640, $square); }
212   
213     /***
214      * Generate a thumbnail from the loaded image
215      *
216      * $dest:  The destination file on disk to save new thumbnail
217      *
218      * $out: The type of image to create (uses PHPs standard image constants for PNG, JPG, GIF)
219      *
220      * $newdim:  This is the largest dimension the image can contain in
221      *      pixels.  If either of the measurements are larger than this size,
222      *      the image will be scaled
223      *
224      * $square: create a square thumbnail
225      *
226      * $resample: high quality resize?  it is good to turn this off if you are doing
227      *      lots of conversions and quality isn't a huge issue
228      */
229     function thumbnail($dest, $newdim, $square=false, $bHeight=false, $out=NULL, $resample=true) {
230         $src_width  = imagesx($this->res);
231         $src_height = imagesy($this->res);
232         $src_w      = $src_width;
233         $src_h      = $src_height;
234         $src_x      = 0;
235         $src_y      = 0;
236   
237         $percent = false;
238         if ( $newdim < 1 )
239             $percent = $newdim;
240         elseif ( substr($newdim, -1) == '%' )
241             $percent = substr($newdim, 0, -1)/100;
242   
243         if ( false !== $percent )
244             $newdim = round( ($bHeight ? ($src_height*$percent) : ($src_width*$percent) ) );
245   
246         if ($square)
247         {
248             $dst_w = $largest_dim;
249             $dst_h = $largest_dim;
250             if ( ! $bHeight )
251             {
252                 $src_x = ceil( ($src_width - $src_height) / 2 );
253                 $src_w = $src_height;
254                 $src_h = $src_height;
255             }
256             else
257             {
258                 $src_y = ceil( ($src_height - $src_width) / 2 );
259                 $src_w = $src_width;
260                 $src_h = $src_width;
261             }
262         }
263         else
264         {
265             if ( ! $bHeight )
266             {
267                 $dst_w = $largest_dim;
268                 $dst_h = floor( $src_height * ($dst_w / $src_width) );
269             }
270             else
271             {
272                 $dst_h = $largest_dim;
273                 $dst_w = floor( $src_width * ($dst_h / $src_height) );
274             }
275         }
276         $dst_im = imagecreatetruecolor($dst_w,$dst_h);
277         $this->prepare($dst_im);
278         if ($resample)
279             imagecopyresampled($dst_im, $this->res, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
280         else
281             imagecopyresized($dst_im, $this->res, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
282   
283         if ( is_null($out) )
284             $out = $this->contenttype;
285         switch($out)
286         {
287             case IMAGETYPE_PNG:
288               imagepng($dst_im, $dest);
289             break;
290             case IMAGETYPE_GIF:
291               imagegif($dst_im, $dest);
292             break;
293             case IMAGETYPE_JPEG:
294   
295               imagejpeg($dst_im, $dest);
296             break;
297         }
298         imagedestroy($dst_im);
299     }
300   
301     /***
302      * Shortcut functions to some standard thumbnail sizes
303      */
304     function thumbnail_xsmall($dest, $out, $square=false) { $this->thumbnail($dest, $out, 60, $square); }
305     function thumbnail_small($dest, $out, $square=false) { $this->thumbnail($dest, $out, 80, $square); }
306     function thumbnail_medium($dest, $out, $square=false) { $this->thumbnail($dest, $out, 160, $square); }
307     function thumbnail_large($dest, $out, $square=false) { $this->thumbnail($dest, $out, 300, $square); }
308     function thumbnail_xlarge($dest, $out, $square=false) { $this->thumbnail($dest, $out, 512, $square); }
309   
310     /***
311      * Crop an image by N pixels
312      *
313      * Same order as CSS property
314      *
315      * This will crop an image by the number of pixels you specify.
316      *      For example, to crop 10 pixels off the bottom and left sides
317      *      you would do crop(10, 0, 10)
318      */
319     function crop ($top, $right=0, $bottom=0, $left=0)
320     {
321         $w  = imagesx($this->res);
322         $h  = imagesy($this->res);
323         $nw = $w - ($left+$right);
324         $nh = $h - ($top+$bottom);
325         $im = imagecreatetruecolor( $nw, $nh );
326         $this->prepare($im);
327   
328         imagecopy($im, $this->res, 0, 0, $left, $top, $nw, $nh );
329   
330         imagedestroy($this->res);
331         $this->res = $im;
332     }
333   
334     /***
335      * Shortcut functions to crop
336      */
337     function crop_top($px) { $this->crop($px); }
338     function crop_right($px) { $this->crop(0, $px, 0, 0); }
339     function crop_bottom($px) { $this->crop(0, 0, $px, 0); }
340     function crop_left($px) { $this->crop(0, 0, 0, $px); }
341     function crop_h($px) { $this->crop($px, 0, $px, 0); }
342     function crop_v($px) { $this->crop(0, $px, 0, $px); }
343     function crop_all($px) { $this->crop($px, $px, $px, $px); }
344   
345     /***
346      * Open an image from a file on disk
347      */
348     function open($src)
349     {
350         $this->source = $src;
351         switch( ( $this->contenttype = exif_imagetype($src) ) )
352         {
353             case IMAGETYPE_PNG:
354               $this->res = imagecreatefrompng($src);
355             break;
356             case IMAGETYPE_GIF:
357               $this->res = imagecreatefromgif($src);
358             break;
359             case IMAGETYPE_JPEG:
360               $this->res = imagecreatefromjpeg($src);
361             break;
362         }
363   
364         $this->prepare($this->res);
365     }
366   
367     // takes an image resource and a content type and prepares the resource
368     function prepare($res, $contenttype=NULL)
369     {
370         if ( is_null($contenttype) ) $contenttype = $this->contenttype;
371   
372         if ( $contenttype == IMAGETYPE_PNG )
373         {
374             imagesavealpha($res, true);
375             imagealphablending($res, false);
376         }
377     }
378   
379     /***
380      * Get/set image resource
381      */
382     function resource ($res=NULL)
383     {
384         if ( is_null($res) )
385             return $this->res;
386         else
387             $this->res = $res;
388     }
389   
390     /***
391      * Save the image back to the original file
392      */
393     function save($out=NULL)
394     {
395         if ( ! is_null($this->source) )
396             $this->write($this->source, $out);
397     }
398   
399     /***
400      * Save the image to a different location
401      */
402     function write($dest, $out=NULL)
403     {
404         if(is_null($out))
405             $out = $this->contenttype;
406   
407         switch($out)
408         {
409             case IMAGETYPE_PNG:
410               imagepng($this->res, $dest);
411             break;
412             case IMAGETYPE_GIF:
413               imagegif($this->res, $dest);
414             break;
415             case IMAGETYPE_JPEG:
416               imagejpeg($this->res, $dest);
417             break;
418         }
419     }
420   
421     /***
422      * Output the image to the stream (browser)
423      */
424     function output($out=NULL)
425     {
426         switch($out)
427         {
428             default:
429             case IMAGETYPE_PNG:
430               $contenttype = 'png';
431             break;
432             case IMAGETYPE_GIF:
433               $contenttype = 'gif';
434             break;
435             case IMAGETYPE_JPEG:
436               $contenttype = 'jpeg';
437             break;
438         }
439   
440         header('Content-type: image/'.$contenttype);
441         $this->write(NULL, $out);
442     }
443   
444     /***
445      * Kill self
446      */
447     function destroy()
448     {
449         imagedestroy($this->res);
450         $this->source=NULL;
451         $this->contenttype = NULL;
452     }
453 }
454   
455 if( ! function_exists('exif_imagetype') )
456 {
457     function exif_imagetype ( $f )
458     {
459         if ( false !== ( list(,,$type,) = getimagesize( $f ) ) )
460             return $type;
461         return IMAGETYPE_PNG; // meh
462     }
463 }
저작자 표시
Dev/linux 2010/03/13 13:26

리눅스 보안체크

크리에이티브 커먼즈 라이선스
Creative Commons License

 
 1) find /dev -type -f -exec ls -l {}\;

     -f 는 일반 파일을 뜻함
            /dev 밑에 디렉토리에 일반 파일이 있다면 의심을 해 봐야 함

 2) /etc/passwd 에서 uid 가 0 설정된 부분과 기타 낮설은 계정을 체크
           /etc/shadow 점검

 3) 텔넷과 FTP를 사용하는 사용자가 있는지에 대한 여부를 체크한다.
            telnet 사용중일때 명령어 :w
            ftp 사용중일때 명령어 : ftpwho

 4) 열려있는 수상한 포트 확인
             ps -ef 혹은 netstat -na |grep LISTEN 확인
             nmap -sS -O -V <IP주소> 명령어로 확인
             nmap -sS -p80 <IP주소> -O -v www.hackerscollege.com
             lsof | grep LISTEN

 5) /root/.bash_history 체크
            체크방법 (줄수가 800줄 이상)
            cat /root/.bash_history |wc -l

 6) 각 계정별로 사용한 명령어 기록 체크
    find / -name .bash_history -exec ls -al{}\;
    find / -name .bash_history -exec cat{}\;

7) 공격 징후를 체크 한다.
          파일 위치 : /var/log/messages
           파일 보기 : more /var/log/messages

8) 현재 접속하고 있는 사용자에 대한 정보를 모두 체크 한다
    /var/run/utmp
    strings utmp | more

9) 접속했던 사용자에 대한 정보를 모두 체크
    /var/log/wtmp

10) 가장 최근에 로그인한 사용자에 대한 정보 체크
   /var/log/lastlog
  파일보기 : last

11) 루트 권한 가진 사용자들을 모두 체크
   cat /etc/passwd |grep 0:0

12) su 명령어 사용한 모든 사용자를 체크
    cat /var/log/messages |grep root

13) 보안 사용자에 관한 인증을 체크(/var/log/secure)
   cat /var/log/secure

14) 웹서버에 접근했거나 에러를 유발한 사용자 체크
   var/log/httpd
   파일보기 : more /var/log/httpd/access_log
                   more /var/log/httpd/error_log

15) tmp 디렉토리에 수상한 프로세스가 있는지를 체크한다.
   ls -asl /tmp

16) pstree 명령어로 데몬 체크

17) 파일의 무결성 여부를 체크
    http://weblog/websea.co.kr/tripwrite/tripwire

18) lsattr 명령어를 사용하여 속성 변경여부 체크
      /usr/bin/lsattr /bin
       /usr/bin/lsattr /sbin
       /usr/bin/lsattr /usr/bin
       /usr/bin/lsattr /usr/sbin
       ----l------- /bin/ls  <-- 변조

19) 패키지 변조 여부 체크
   rpm -Va apache
   rpm -V apache

    결과)
    S,5....T /bin/ls
    5 = MD5 쳇섬
    S = 파일 크기
    L = 심볼릭
    T = 최신 갱신 일시(MTIME)
    D = 장치
    U = 사용자
    G = 그룹
    M = 허가모드(허가권과 파일 유형)

20) 실행 파일 변조 여부를 체크 한다
    cd /bin/
    ls -alct |more
    netstat -alct |more
    ps -alct |more
    strace -e trace=open ps
    strace -e trace=open ls

21) setuid setgid 파일 체크
    find / -user root -perm -4000 -print > suidlist
    find / -user root -perm -2000 -print > sgidlist
    find / -user root -perm -4000 -xdev

22) setuid 나 setgid 막기
    chmod a-s <찿아낸파일명>

23) 숨겨진 파일 체크
    find / -name "..*" -print

24) 스팸메일 여부 체크(메일큐)
    var/spool/mqueue

25) 비밀번호없이 원격 접속하기 위한 .rhosts 파일 체크
    find / -name .rhost -exec ls -al {}\;
    find / -name .rhost -exec cat {}\;

26) 소유자가 없는 파일과 디렉토리를 체크 한다.
    find / -nouser -o -nogroup -print

26) 최근 10일 동안 변경된 파일이나 디렉토리 체크
    find / -ctime -10 -type f or d

27) 코어를 체크 한다
    find / -name core -exec ls -al {}\;

28) 커널패닉의 원인이 되는 부팅과 관계되는 디렉토리를 체크 한다.
     ls -asl /etc/rc.d/

29) 인터넷 서비스 파일이 있는 xini 디렉토리를 체크
    ls -asl /etc/xinetd.d/
 
30) 파일의 용량을 체크 한다
     repquota -av -ag

31) 파티션별로 사용된 디스크 용량 체크
    df -h
 
32) free 와 top 가 참조하는 /proc/meminfo 를 이용하여 메모리 용량 체크
    cat /proc/meminfo
    top -d2
    free -m
 
33) chmod 700 체크
    조사하고 가져오지 못하게!!
  /usr/bin/find
  /usr/bin/top
  /usr/bin/cc
  /usr/bin/wget
  /usr/bin/suidperl
  /usr/bin/sperl5.00503
  /usr/bin/whereis
  /usr/bin/ftoplynx

34) chmod 700 체크
    보지 못하게
  /usr/bin/finger
  /usr/bin/nslookup

35) chmod 700 체크
    컴파일 못하게
  /usr/bin/make
  /usr/bin/gcc
  /usr/c++

36) chmod 700 체크
  /usr/bin/w
  /usr/bin/who
  /usr/bin/which
  /usr/bin/rlog
  /usr/bin/rlogin
  /usr/bin/pstree
  /usr/bin/mail
  /usr/bin/ps
  /usr/bin/hosts
  /usr/bin/hosts.deny
  /usr/bin/hosts.allow

37) 핑과 핑을 이용한 도스 공격 방어하기
  차단하기
   echo 1 >/proc/sys/net/ipv4/icmp_echo_ignore_all

  해제하기
   echo 0 >/proc/sys/net/ipv4/icmp_echo_ignore_all

38) 핑(ping) 과 핑을 이용한 도스 공격을 방어한다.
  핑 도스 공격 차단하기
   vi /etc/sysctl.conf
   net.ipv4.icmp_echo_igonore_broadcasts =1
   sysctl -w
   /etc/rc.d/init.d/network restart
   sysctl -a | grep igonore_broadcasts

39) ssh를 이용하여 root로의 원격 접속을 금지
   /etc/ssh/sshd_config
   PermitRootLogin no

40) FTP를 이용하여 Root 로의 원격 접속을 금지
   /etc/proftpd.conf
   RootLogin off

41) 부팅시 실행되는 서비스를 체크
   사용파일 chkconfig
   파일 위치 :/sbin
   리스트 보기
   chkconfig --list
   도움말 보기
   chkconfig --help

42) 부팅시 실행되는 서비스를 체크한다.
  atd 서비스 끄기
  chkconfig --level 3 atd off
  - 위의 예제에서 레벨3을 사용하는 이유는 부팅은 레벨3 모드로 진행되기 때문

  chkconfig --list
   서비스별 켬과 끔이 나옴
   필수적으로 켜놓아야 할 파일들
  -keytable, inet, network,random, kudzu,sendmail,syslog,crond,proftpd

저작자 표시
Dev/php 2010/03/05 09:43

mod_rewrite 사용하기

크리에이티브 커먼즈 라이선스
Creative Commons License
mod_rewrite (Rewrite engine)  는 전달 받은 URL 을 재 작성 을 하거나 URL을 최적화 할때 사용하는 모듈입니다.

예들 들어서
원 주소 : http://www.example.com/Blogs/Posts.php?Year=2006&Month=12&Day=10
적 용 주소 : http://www.example.com/Blogs/2006/12/10/


위 와 같은 모습으로 URL을 간단히 처리 할 수 있습니다.

위 예제를  설정하는 룰은 아래와 같습니다.
 (실제 동작은 테스트 하지 않음 : 이해를 돕기 위한 구문임)
RewriteCond %{REQUEST_URI} /Blogs/([0-9]+)/([0-9]+)/([0-9]+)$
RewriteRule . http://www.example.com/Blogs/Posts.php?Year=$1&Month=$2&Day=$3


위 와 같이 설정을 할 수 있습니다.

이제 rewrite 의 설정 및 각 문법에 대해서 알아 보겠습니다.
  1. RewriteBase
  2. RewriteCond
  3. RewriteEngine
  4. RewriteLock
  5. RewriteLog
  6. RewriteLogLevel
  7. RewriteMap
  8. RewriteOptions
  9. RewriteRule

1. RewriteBase (Rewrite 에 사용될 기본 URL 디렉토리를 설정)
사용법 : RewriteBase /Example
적용할수 있는 곳 :  Directory, .htaccess

2. RewriteCond (URL 의 재작성할 부분을 선언하거나 지정한다.)
사용법 : RewriteCond [검사할 문자열] [패턴]
적용할 수 있는 곳 : Server Config, Virtual Host,  Directory, .htaccess

사용할 수 있는 서버 변수

HTTP Headers... 닫기

HTTP_USER_AGENT
HTTP_REFERER
HTTP_COOKIE
HTTP_FORWARDED
HTTP_HOST
HTTP_PROXY_CONNECTION
HTTP_ACCEPT

HTTP Headers... 닫기

connection & request 닫기

REMOTE_ADDR
REMOTE_HOST
REMOTE_PORT
REMOTE_USER
REMOTE_IDENT
REQUEST_METHOD
SCRIPT_FILENAME
PATH_INFO
QUERY_STRING
AUTH_TYPE

connection & request 닫기

server internals: 닫기

DOCUMENT_ROOT
SERVER_ADMIN
SERVER_NAME
SERVER_ADDR
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE

server internals: 닫기

date and time 닫기

TIME_YEAR
TIME_MON
TIME_DAY
TIME_HOUR
TIME_MIN
TIME_SEC
TIME_WDAY
TIME

date and time 닫기

specials 닫기

API_VERSION
THE_REQUEST
REQUEST_URI
REQUEST_FILENAME
IS_SUBREQ
HTTPS

specials 닫기


플래그 (작성중..)
C
CO
F
G
L
N
NC
NE
[P] 재작성한 외부 페이지(웹사이트) 를 재작성 이름으로 대응한다.
PT
QSA
[R] 브라우저에게 변경 사실을 통보한다. (주소창이 변한다)
S
T

사용 예시
Rewrite ^/TestDir/(.*)$ /Web/Test/$1 [L] 은
http://example.com/TestDir/ 으로 들어오면 http://example.com/Web/Test/ 로 처리한다.

Rewrite %{HTTP_USER_AGENT} ^Mozilla.*
RewriteRule ^/$ /browser/mozilla.html [L]

브라우저 UserAgent 에  Mozilla 가 포함되어 잇으면 /browser/mozilla.html 으로 처리한다.

3. RewriteEngine
사용법 : RewriteEngine on|off
기본 : RewriteEngine off
적용할 수 있는 곳 : Server Config, Virtual Host,  Directory, .htaccess
설명 : Rewrite 엔진을 사용하는 여부를 설정한다.

4. RewriteLog
사용법 : RewriteLog [파일패스]
적용할 수 있는 곳 : server conf, virtual host
예 : RewriteLog "/usr/local/apache/log/rewritelog.log"
설 명 : Rewrite 동작에 대한 로그를 남긴다.

5. RewriteLogLevel
사용법 : RewriteLogLevel  [Level]
예 RewriteLogLevel 0
적용할 수 있는 곳 : Server Conf, Virtual Host
설명 : RewirteLog 를 이용하여 기록할 로그 레벨을 지정한다.

6. RewriteMap

7. RewriteOptions

8. RewriteRule
저작자 표시
Dev/php 2010/03/03 18:57

mod_rewrite 의 활용

크리에이티브 커먼즈 라이선스
Creative Commons License

mod_rewrite

# 이 문서는 오라클클럽에서 작성하였습니다.
# 이 문서를 다른 블로그나 홈페이지에 게재하실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^
# 출처 : http://wiki.oracleclub.com/display/SWDEV/mod_rewrite?



mod_rewrite

1 mod_rewrite 설치

  • apache 설치시 Configure 실행시에 --enable-rewrite 옵션을 추가한다.
  • apache 설치 이후 추가 설치시
    • 아파치 압축 푼 디렉토리로 이동 : cd /usr/local/httpd-2.0.63/modules/mappers
    • apxs를 이용해 새 모듈 추가 : /usr/local/apache2/bin/apxs -aic mod_rewrite.c

2 Rewrite 모듈 지시자

2.1 RewriteEngine

  • Rewriteing 엔진을 사용할지 여부를 설정
  • 디폴트 설정은 Off, RewriteEngine On 으로 설정하지 않는 이상 Rewritng 엔진을 사용할 수 없다.
  • 설정문법 : RewriteEngine On|Off

2.2 RewriteRule

  • Rewrite 모듈의 실질적인 Rewrite 규칙들을 적용 한다.
  • Input URL을 Return URL로 변경하기 위한 규칙들을 설정 한다.
  • 아래는 RewriteRule을 이용해 퍼머링크를 만드는 예제다.
 <IfModule mod_rewrite.c>  
RewriteEngine On
RewriteRule ^/$ /main.ok [R]
RewriteRule ^/community/([0-9]+)$ /articlelist.ok?article.communityId=$1 [PT]
RewriteRule ^/article/([0-9]+)$ /articleview.ok?article.articleId=$1 [PT]
</IfModule>

  • RewriteRule 플래그
    • F(forbidden) : 요청하는 페이지를 403 에러로 redirect 시킵니다.
    • G(gone) : 요청하는 페이지를 410 에러로 redirect 시킵니다.
    • R(redirect) : Return URL로 redirect 한다.
    • PT(passthrough) : Input URL을 그대로 유지하며 Return URL을 실행한다.
    • http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

2.3 RewriteCond

참고4. 정규표현식 기초
. : 다수의 한문자
? : 0개 이상의 한문자
* : 0개 이상의 문자 또는 문자열
+ : 1개 이상의 문자 또는 문자열
^ : 문자열의 첫문(열)을 지정합니다.
$ : 문자열의 끝 문자(열)을 지정합니다.
(역슬래쉬) : 정규표현식에서 특별한 의미로 사용되는 문자의 특수기능을 제거합니다.(예:(, ), [, ] . 등)
{n} : 정확히 n번 반복
{n,} : n번 이상 반복
{n,m} : n 이상 m 이하 반복
[chars] : 문자들의 범위 또는 표현할 수 있는 문자들을 설정합니다.
예) [a-z] : a 부터 z 까지의 소문자, [tT] : 소문자 t 또는 대문자 T

정규표현식 단축표현들
[:alpha:] : 알파벳. [a-zA-Z] 와 같은 표현
[:alnum:] : 알파벳과 숫자. [a-zA-Z0-9] 와 같은 표현
[:digit:] : 숫자 [0-9] 와 같은 표현
[:upper:] : 대문자. [A-Z] 와 같은 표현

# 이 문서는 오라클클럽에서 작성하였습니다.
# 이 문서를 다른 블로그나 홈페이지에 게재하실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^
# 출처 : http://wiki.oracleclub.com/display/SWDEV/mod_rewrite?
저작자 표시
TOTAL 114,290 TODAY 48