Posted
Filed under PHP
$url = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
2010/11/07 15:08 2010/11/07 15:08
Posted
Filed under Linux

[원문 ] - http://towons.kr/blog/2

경우에 따라, 404에러에 대해 아파치가 기본적으로 보여주는 에러페이지가 아닌, 개별적인 커스터마이징을
하고자 하는 경우가 생기게 마련인데..
이때는 /etc/httpd/conf/httpd.conf 를 열어서 아래와 같이 바꿔주시기 바랍니다.

httpd.conf

<VirtualHost *>
    DocumentRoot /home/domain
    ServerName domain.co.kr
    ServerAlias www.domain.co.kr
    ErrorDocument 404 /home/domain/error404.php
</VirtualHost>

버추어호스트에 물려놓은 도메인마다 개별 설정하는게 좋습니다. 서버에 물려 있는 모든 도메인에 동일한 404를
보여주려는 목적이라면 그냥 기본 404에러페이지를 쓰는 것도 나쁘지 않으니깐요.

남은 일은 error404.php 라는 파일을 만들어서 서버에 올려두는 일뿐입니다.

error404.php
<html>
<body>
잘못 찾아오셨습니다.<br>You got 404 Error!!!! orz
</body>
</html>

404에러가 났을때 만약 에러페이지로 보내지 않고, index.html 과 같은 메인페이지로 보내고 싶다면
ErrorDocument 404 /home/domain/error404.php 를
2010/11/06 19:53 2010/11/06 19:53
Posted
Filed under asp,asp.net
[원문] -  http://support.microsoft.com/kb/q195951/

문서에서는 쿼리 및 ADO (ActiveX 데이터 개체) 에서 ASP (Active Server Pages) 페이지를 사용하는 Excel 스프레드시트의 정보를 업데이트하는 방법을 보여 줍니다. 이 문서에서는 또한 이러한 유형의 응용 프로그램에 관련된 제한 사항을 설명합니다.

중요: 다중 사용자 액세스 ASP/ADO 응용 프로그램을 지원하지 않지만 Excel 스프레드시트를 않습니다. 따라서 쿼리 및 정보를 업데이트하는 이 방법은 다중 사용자 동시 액세스가 지원하지 않습니다.

추가 정보
이 샘플의 Excel 스프레드시트의 데이터를 액세스하려면 Excel Microsoft ODBC 드라이버를 사용하십시오. Excel 스프레드시트에...

이 샘플의 Excel 스프레드시트의 데이터를 액세스하려면 Excel Microsoft ODBC 드라이버를 사용하십시오. Excel 스프레드시트에서 명명된 범위를 만들어 데이터에 액세스할 수 있는 테이블을 만듭니다.

샘플 응용 프로그램 만드는 단계

  • Excel 파일을 ADOtest.xls sheet1 다음 데이터에 만들기:

    표 축소표 확대
    column1 column2 column3
    rr 15
    bb Test 20
    ee 작동 25

    참고 Excel 스프레드시트의 열을 텍스트와 숫자를 모두 포함되어 있으면 Excel ODBC 드라이버 열이어야 합니다 데이터 형식을 올바르게 해석할 수 없습니다. 열의 모든 셀에 같은 데이터 형식의 있는지 확인하십시오. 열의 각 셀 형식이 없거나 형식 혼합 사이에 "텍스트" 및 "일반" 권한이 다음과 같은 세 가지 오류가 발생할 수 있습니다.
    1. Microsoft OLE DB 공급자에 대한 ODBC 드라이버 오류 '80040e21'
      요청 속성은 이 ODBC 드라이버에서 지원되지 않을 수 있습니다.
    2. Microsoft OLE DB 공급자와 ODBC 드라이버 오류는 '80004005'
      즐겁고 키로 사용할 검색 가능한 열이 포함되어 있기 때문에 쿼리를 업데이트할 수 없습니다.
    3. Microsoft OLE DB 공급자와 ODBC 드라이버 오류는 '80004005'
      쿼리 기반 업데이트하지가 못했습니다. 업데이트할 행을 찾을 수 없습니다.
  • 명명된 범위, myRange1을 사용하여 스프레드시트를 만듭니다.

    1. 데이터가 상주하는 행 및 열을 영역을 강조 표시하십시오.
    2. 삽입 메뉴에서 이름을 가리킨 다음 정의를 클릭하십시오.
    3. 해당 이름 범위 이름을 myRange1 입력하십시오 이름.
    4. 확인을 클릭하십시오.
    명명된 범위 myRange1 다음 데이터가 포함되어 있습니다.

    표 축소표 확대
    column1 column2 column3
    rr 15
    bb Test 20
    ee 작동 25


    참고 ADO Excel 쿼리의 첫 번째 행에 열 머리글이 들어 있다고 가정합니다. 따라서, 명명된 범위 열 머리글이 포함되어야 합니다. DAO에서 동작이 있습니다.

    참고 열 머리글을 숫자를 사용할 수 없습니다. Excel 드라이버는 해석할 수 및 대신 셀 참조를 반환합니다. 예를 들어, "F1" 열 머리글 해석될 것입니다.
  • ODBC 시스템 데이터 원본 이름 (ADOTest.xls 파일을 가리키는 DSN)을 만듭니다.
    1. 제어판에서 ODBC 열 관리자.
    2. 시스템 DSN 탭에서 추가 클릭하십시오.
    3. Microsoft Excel 드라이버 (*.xls) 선택하고 마침 을 클릭하십시오. 이 옵션은 존재하지 않을 경우 Excel 설정에서 Excel Microsoft ODBC 드라이버를 설치해야 합니다.
    4. ADOExcel에 대한 데이터 원본 이름을 선택하십시오.
    5. 올바른 버전의 Excel 버전 설정되어 있는지 확인하십시오.
    6. 선택 통합... 를 클릭하고 해당 ADOTest.xls 찾은 파일과 확인을 클릭합니다.
    7. 사용하여 "옵션 >>" 단추 및 "읽기 전용" 확인란의 선택을 취소합니다.
    8. 확인을 클릭한 다음 다시 확인을 클릭하십시오.
  • ADOTest.xls 파일에 대한 사용 권한을 설정하십시오.
Active Server Page 익명으로 액세스할 경우 익명 계정 (IUSR_ <machinename>) 이상이 확인해야 할 스프레드시트 RW (읽기/쓰기 액세스를. 스프레드시트에서 정보를 삭제할 경우 그에 따라 사용 권한을 부여해야 합니다.

사용자의 Active Server Page 액세스를 인증하는 경우 응용 프로그램이 액세스하는 모든 사용자에게 적절한 권한이 있는지 확인해야 합니다.

참고 스프레드시트의 적절한 사용 권한을 설정한 경우 사용자가 오류 다음과 유사한 메시지가:

Microsoft OLE DB 공급자와 ODBC 드라이버 오류는 '80004005'

[Microsoft][ODBC Excel 드라이버] Microsoft Jet 데이터베이스 엔진이 '(알 수)' 파일을 열 수 없습니다. 이미 다른 사용자가 독점적으로 열려 또는 해당 데이터를 볼 수 있는 권한이 있어야 합니다.
  1. 새 ASP 페이지를 만들고 다음 코드를 붙여 넣습니다.
          <!-- Begin ASP Source Code -->
          <%@ LANGUAGE="VBSCRIPT" %>
          <%
            Set objConn = Server.CreateObject("ADODB.Connection")
            objConn.Open "ADOExcel"
    
            Set objRS = Server.CreateObject("ADODB.Recordset")
            objRS.ActiveConnection = objConn
            objRS.CursorType = 3                    'Static cursor.
            objRS.LockType = 2                      'Pessimistic Lock.
            objRS.Source = "Select * from myRange1"
            objRS.Open
       %>
       <br>
       <%
          Response.Write("Original Data")
    
          'Printing out original spreadsheet headings and values.
    
          'Note that the first recordset does not have a "value" property
          'just a "name" property.  This will spit out the column headings.
    
          Response.Write("<TABLE><TR>")
          For X = 0 To objRS.Fields.Count - 1
             Response.Write("<TD>" & objRS.Fields.Item(X).Name & "</TD>")
          Next
          Response.Write("</TR>")
          objRS.MoveFirst
    
          While Not objRS.EOF
             Response.Write("<TR>")
             For X = 0 To objRS.Fields.Count - 1
                Response.write("<TD>" & objRS.Fields.Item(X).Value)
             Next
             objRS.MoveNext
             Response.Write("</TR>")
          Wend
          Response.Write("</TABLE>")
    
          'The update is made here
    
          objRS.MoveFirst
          objRS.Fields(0).Value = "change"
          objRS.Fields(1).Value = "look"
          objRS.Fields(2).Value = "30"
          objRS.Update
    
          'Printing out spreadsheet headings and values after update.
    
          Response.Write("<br>Data after the update")
          Response.Write("<TABLE><TR>")
          For X = 0 To objRS.Fields.Count - 1
             Response.Write("<TD>" & objRS.Fields.Item(X).Name & "</TD>")
          Next
          Response.Write("</TR>")
          objRS.MoveFirst
    
          While Not objRS.EOF
             Response.Write("<TR>")
             For X = 0 To objRS.Fields.Count - 1
                Response.write("<TD>" & objRS.Fields.Item(X).Value)
             Next
             objRS.MoveNext
             Response.Write("</TR>")
          Wend
          Response.Write("</TABLE>")
    
          'ADO Object clean up.
    
          objRS.Close
          Set objRS = Nothing
    
          objConn.Close
          Set objConn = Nothing
       %>
       <!-- End ASP Source Code -->
    					
  2. 및 Active Server Page 이름을 저장하고 브라우저에서 봅니다. 다음 표시됩니다:
          Original Data:
    
          column1    column2    column3
          -----------------------------
    
          rr         this       30
          bb         test       20
          tt         works      25
    
    
          Data after the update:
    
          column1    column2    column3
          -----------------------------
    
          change     look       30
          bb         test       20
          tt         works      25
    					
참고 업데이트 이름 범위 첫 번째 행에 머리글이 후 수행되었습니다.

참조
자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오. 190195  (http://support.microsoft.com/kb...

자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
190195  (http://support.microsoft.com/kb/190195/ ) ExtractInformation DAO 사용하여 Excel 시트 시작 방법

본 문서의 정보는 다음의 제품에 적용됩니다.
  • Microsoft ActiveX Data Objects 1.0
  • Microsoft ActiveX Data Objects 1.5
  • Microsoft ActiveX Data Objects 2.0
  • Microsoft ActiveX Data Objects 2.1 서비스 팩 2
  • Microsoft ActiveX Data Objects 2.5
  • Microsoft Active Server Pages 4.0
  • Microsoft Data Access Components 2.5
키워드: 
kbmt kbcode kbhowto kbmdacnosweep KB195951 KbMtko
2010/10/19 17:29 2010/10/19 17:29
Posted
Filed under asp,asp.net
[원문 ] http://www.freeaspupload.net/freeaspupload/download.asp [다운로드 페이지]

To learn how to use this class in your site, read the instructions in the documentation page or download the example form that comes with the code.

Do not copy the code from this page, use the Download option. If you copy and paste, some lines of text may be broken by the browser because of their length.

Contents of freeASPUpload.asp:

<%
' For examples, documentation, and your own free copy, go to:
' http://www.freeaspupload.net
' Note: You can copy and use this script for free and you can make changes
' to the code, but you cannot remove the above comment.

'Changes:
'Aug 2, 2005: Add support for checkboxes and other input elements with multiple values
'Jan 6, 2009: Lars added ASP_CHUNK_SIZE
'Sep 3, 2010: Enforce UTF-8 everywhere; new function to convert byte array to unicode string

const DEFAULT_ASP_CHUNK_SIZE = 200000

const adModeReadWrite = 3
const adTypeBinary = 1
const adTypeText = 2
const adSaveCreateOverWrite = 2

Class FreeASPUpload
  Public UploadedFiles
  Public FormElements

  Private VarArrayBinRequest
  Private StreamRequest
  Private uploadedYet
  Private internalChunkSize

  Private Sub Class_Initialize()
    Set UploadedFiles = Server.CreateObject("Scripting.Dictionary")
    Set FormElements = Server.CreateObject("Scripting.Dictionary")
    Set StreamRequest = Server.CreateObject("ADODB.Stream")
    StreamRequest.Type = adTypeText
    StreamRequest.Open
    uploadedYet = false
    internalChunkSize = DEFAULT_ASP_CHUNK_SIZE
  End Sub
 
  Private Sub Class_Terminate()
    If IsObject(UploadedFiles) Then
      UploadedFiles.RemoveAll()
      Set UploadedFiles = Nothing
    End If
    If IsObject(FormElements) Then
      FormElements.RemoveAll()
      Set FormElements = Nothing
    End If
    StreamRequest.Close
    Set StreamRequest = Nothing
  End Sub

  Public Property Get Form(sIndex)
    Form = ""
    If FormElements.Exists(LCase(sIndex)) Then Form = FormElements.Item(LCase(sIndex))
  End Property

  Public Property Get Files()
    Files = UploadedFiles.Items
  End Property
 
Public Property Get Exists(sIndex)
Exists = false
If FormElements.Exists(LCase(sIndex)) Then Exists = true
End Property

Public Property Get FileExists(sIndex)
FileExists = false
if UploadedFiles.Exists(LCase(sIndex)) then FileExists = true
End Property

Public Property Get chunkSize()
    chunkSize = internalChunkSize
  End Property

  Public Property Let chunkSize(sz)
    internalChunkSize = sz
  End Property

  'Calls Upload to extract the data from the binary request and then saves the uploaded files
  Public Sub Save(path)
    Dim streamFile, fileItem, filePath

    if Right(path, 1) <> "\" then path = path & "\"

    if not uploadedYet then Upload

    For Each fileItem In UploadedFiles.Items
      filePath = path & fileItem.FileName
      Set streamFile = Server.CreateObject("ADODB.Stream")
      streamFile.Type = adTypeBinary
      streamFile.Open
      StreamRequest.Position=fileItem.Start
      StreamRequest.CopyTo streamFile, fileItem.Length
      streamFile.SaveToFile filePath, adSaveCreateOverWrite
      streamFile.close
      Set streamFile = Nothing
      fileItem.Path = filePath
     Next
  End Sub
 
  public sub SaveOne(path, num, byref outFileName, byref outLocalFileName)
    Dim streamFile, fileItems, fileItem, fs

set fs = Server.CreateObject("Scripting.FileSystemObject")
    if Right(path, 1) <> "\" then path = path & "\"

    if not uploadedYet then Upload
    if UploadedFiles.Count > 0 then
      fileItems = UploadedFiles.Items
      set fileItem = fileItems(num)
   
      outFileName = fileItem.FileName
      outLocalFileName = GetFileName(path, outFileName)
   
      Set streamFile = Server.CreateObject("ADODB.Stream")
      streamFile.Type = adTypeBinary
      streamFile.Open
      StreamRequest.Position = fileItem.Start
      StreamRequest.CopyTo streamFile, fileItem.Length
      streamFile.SaveToFile path & outLocalFileName, adSaveCreateOverWrite
      streamFile.close
      Set streamFile = Nothing
      fileItem.Path = path & filename
    end if
  end sub

  Public Function SaveBinRequest(path) ' For debugging purposes
    StreamRequest.SaveToFile path & "\debugStream.bin", 2
  End Function

  Public Sub DumpData() 'only works if files are plain text
    Dim i, aKeys, f
    response.write "Form Items:<br>"
    aKeys = FormElements.Keys
    For i = 0 To FormElements.Count -1 ' Iterate the array
      response.write aKeys(i) & " = " & FormElements.Item(aKeys(i)) & "<BR>"
    Next
    response.write "Uploaded Files:<br>"
    For Each f In UploadedFiles.Items
      response.write "Name: " & f.FileName & "<br>"
      response.write "Type: " & f.ContentType & "<br>"
      response.write "Start: " & f.Start & "<br>"
      response.write "Size: " & f.Length & "<br>"
     Next
  End Sub

  Public Sub Upload()
    Dim nCurPos, nDataBoundPos, nLastSepPos
    Dim nPosFile, nPosBound
    Dim sFieldName, osPathSep, auxStr
    Dim readBytes, readLoop, tmpBinRequest
   
    'RFC1867 Tokens
    Dim vDataSep
    Dim tNewLine, tDoubleQuotes, tTerm, tFilename, tName, tContentDisp, tContentType
    tNewLine = String2Byte(Chr(13))
    tDoubleQuotes = String2Byte(Chr(34))
    tTerm = String2Byte("--")
    tFilename = String2Byte("filename=""")
    tName = String2Byte("name=""")
    tContentDisp = String2Byte("Content-Disposition")
    tContentType = String2Byte("Content-Type:")

    uploadedYet = true

    on error resume next
      ' Copy binary request to a byte array, on which functions like InstrB and others can be used to search for separation tokens
      readBytes = internalChunkSize
      VarArrayBinRequest = Request.BinaryRead(readBytes)
      VarArrayBinRequest = midb(VarArrayBinRequest, 1, lenb(VarArrayBinRequest))
      Do Until readBytes < 1
        tmpBinRequest = Request.BinaryRead(readBytes)
        if readBytes > 0 then
          VarArrayBinRequest = VarArrayBinRequest & midb(tmpBinRequest, 1, lenb(tmpBinRequest))
        end if
      Loop
      StreamRequest.WriteText(VarArrayBinRequest)
      StreamRequest.Flush()
      if Err.Number <> 0 then
        response.write "<br><br><B>System reported this error:</B><p>"
        response.write Err.Description & "<p>"
        response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
        Exit Sub
      end if
    on error goto 0 'reset error handling

    nCurPos = FindToken(tNewLine,1) 'Note: nCurPos is 1-based (and so is InstrB, MidB, etc)

    If nCurPos <= 1 Then Exit Sub
    
    'vDataSep is a separator like -----------------------------21763138716045
    vDataSep = MidB(VarArrayBinRequest, 1, nCurPos-1)

    'Start of current separator
    nDataBoundPos = 1

    'Beginning of last line
    nLastSepPos = FindToken(vDataSep & tTerm, 1)

    Do Until nDataBoundPos = nLastSepPos
     
      nCurPos = SkipToken(tContentDisp, nDataBoundPos)
      nCurPos = SkipToken(tName, nCurPos)
      sFieldName = ExtractField(tDoubleQuotes, nCurPos)

      nPosFile = FindToken(tFilename, nCurPos)
      nPosBound = FindToken(vDataSep, nCurPos)
     
      If nPosFile <> 0 And nPosFile < nPosBound Then
        Dim oUploadFile
        Set oUploadFile = New UploadedFile
       
        nCurPos = SkipToken(tFilename, nCurPos)
        auxStr = ExtractField(tDoubleQuotes, nCurPos)
' We are interested only in the name of the file, not the whole path
' Path separator is \ in windows, / in UNIX
' While IE seems to put the whole pathname in the stream, Mozilla seem to
' only put the actual file name, so UNIX paths may be rare. But not impossible.
osPathSep = "\"
if InStr(auxStr, osPathSep) = 0 then osPathSep = "/"
        oUploadFile.FileName = Right(auxStr, Len(auxStr)-InStrRev(auxStr, osPathSep))

        if (Len(oUploadFile.FileName) > 0) then 'File field not left empty
          nCurPos = SkipToken(tContentType, nCurPos)
         
auxStr = ExtractField(tNewLine, nCurPos)
' NN on UNIX puts things like this in the stream:
' ?? python py type=?? python application/x-python
          oUploadFile.ContentType = Right(auxStr, Len(auxStr)-InStrRev(auxStr, " "))
          nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
         
          oUploadFile.Start = nCurPos+1
          oUploadFile.Length = FindToken(vDataSep, nCurPos) - 2 - nCurPos
         
          If oUploadFile.Length > 0 Then UploadedFiles.Add LCase(sFieldName), oUploadFile
        End If
      Else
        Dim nEndOfData, fieldValueUniStr
        nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
        nEndOfData = FindToken(vDataSep, nCurPos) - 2
        fieldValueuniStr = ConvertUtf8BytesToString(nCurPos, nEndOfData-nCurPos)
        If Not FormElements.Exists(LCase(sFieldName)) Then
          FormElements.Add LCase(sFieldName), fieldValueuniStr
        else
FormElements.Item(LCase(sFieldName))= FormElements.Item(LCase(sFieldName)) & ", " & fieldValueuniStr
end if

      End If

      'Advance to next separator
      nDataBoundPos = FindToken(vDataSep, nCurPos)
    Loop
  End Sub

  Private Function SkipToken(sToken, nStart)
    SkipToken = InstrB(nStart, VarArrayBinRequest, sToken)
    If SkipToken = 0 then
      Response.write "Error in parsing uploaded binary request. The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
      Response.End
    end if
    SkipToken = SkipToken + LenB(sToken)
  End Function

  Private Function FindToken(sToken, nStart)
    FindToken = InstrB(nStart, VarArrayBinRequest, sToken)
  End Function

  Private Function ExtractField(sToken, nStart)
    Dim nEnd
    nEnd = InstrB(nStart, VarArrayBinRequest, sToken)
    If nEnd = 0 then
      Response.write "Error in parsing uploaded binary request."
      Response.End
    end if
    ExtractField = ConvertUtf8BytesToString(nStart, nEnd-nStart)
  End Function

  'String to byte string conversion
  Private Function String2Byte(sString)
    Dim i
    For i = 1 to Len(sString)
     String2Byte = String2Byte & ChrB(AscB(Mid(sString,i,1)))
    Next
  End Function

  Private Function ConvertUtf8BytesToString(start, length)  
    StreamRequest.Position = 0
 
   Dim objStream
   Dim strTmp
  
   ' init stream
   Set objStream = Server.CreateObject("ADODB.Stream")
   objStream.Charset = "utf-8"
   objStream.Mode = adModeReadWrite
   objStream.Type = adTypeBinary
   objStream.Open
  
   ' write bytes into stream
   StreamRequest.Position = start+1
   StreamRequest.CopyTo objStream, length
   objStream.Flush
  
   ' rewind stream and read text
   objStream.Position = 0
   objStream.Type = adTypeText
   strTmp = objStream.ReadText
  
   ' close up and return
   objStream.Close
   Set objStream = Nothing
   ConvertUtf8BytesToString = strTmp  
  End Function
End Class

Class UploadedFile
  Public ContentType
  Public Start
  Public Length
  Public Path
  Private nameOfFile

' Need to remove characters that are valid in UNIX, but not in Windows
Public Property Let FileName(fN)
nameOfFile = fN
nameOfFile = SubstNoReg(nameOfFile, "\", "_")
nameOfFile = SubstNoReg(nameOfFile, "/", "_")
nameOfFile = SubstNoReg(nameOfFile, ":", "_")
nameOfFile = SubstNoReg(nameOfFile, "*", "_")
nameOfFile = SubstNoReg(nameOfFile, "?", "_")
nameOfFile = SubstNoReg(nameOfFile, """", "_")
nameOfFile = SubstNoReg(nameOfFile, "<", "_")
nameOfFile = SubstNoReg(nameOfFile, ">", "_")
nameOfFile = SubstNoReg(nameOfFile, "|", "_")
End Property

Public Property Get FileName()
FileName = nameOfFile
End Property

'Public Property Get FileN()ame
End Class


' Does not depend on RegEx, which is not available on older VBScript
' Is not recursive, which means it will not run out of stack space
Function SubstNoReg(initialStr, oldStr, newStr)
Dim currentPos, oldStrPos, skip
If IsNull(initialStr) Or Len(initialStr) = 0 Then
SubstNoReg = ""
ElseIf IsNull(oldStr) Or Len(oldStr) = 0 Then
SubstNoReg = initialStr
Else
If IsNull(newStr) Then newStr = ""
currentPos = 1
oldStrPos = 0
SubstNoReg = ""
skip = Len(oldStr)
Do While currentPos <= Len(initialStr)
oldStrPos = InStr(currentPos, initialStr, oldStr)
If oldStrPos = 0 Then
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, Len(initialStr) - currentPos + 1)
currentPos = Len(initialStr) + 1
Else
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, oldStrPos - currentPos) & newStr
currentPos = oldStrPos + skip
End If
Loop
End If
End Function

Function GetFileName(strSaveToPath, FileName)
'This function is used when saving a file to check there is not already a file with the same name so that you don't overwrite it.
'It adds numbers to the filename e.g. file.gif becomes file1.gif becomes file2.gif and so on.
'It keeps going until it returns a filename that does not exist.
'You could just create a filename from the ID field but that means writing the record - and it still might exist!
'N.B. Requires strSaveToPath variable to be available - and containing the path to save to
Dim Counter
Dim Flag
Dim strTempFileName
Dim FileExt
Dim NewFullPath
dim objFSO, p
Set objFSO = CreateObject("Scripting.FileSystemObject")
Counter = 0
p = instrrev(FileName, ".")
FileExt = mid(FileName, p+1)
strTempFileName = left(FileName, p-1)
NewFullPath = strSaveToPath & "\" & FileName
Flag = False

Do Until Flag = True
If objFSO.FileExists(NewFullPath) = False Then
Flag = True
GetFileName = Mid(NewFullPath, InstrRev(NewFullPath, "\") + 1)
Else
Counter = Counter + 1
NewFullPath = strSaveToPath & "\" & strTempFileName & Counter & "." & FileExt
End If
Loop
End Function

%>

2010/10/19 17:21 2010/10/19 17:21
Posted
Filed under Linux
#!/bin/sh

# 초기화
iptables -F

# 포트 스캔 방지
iptables -A INPUT -d 0.0.0.0/0 -p icmp -j DROP

# DoS 공격 방지
iptables -N syn-flood
iptables -A syn-flood -m limit --limit 12/second --limit-burst 24 -j RETURN
iptables -A syn-flood -j DROP

# ssh 정책(root, webpage 계정만 접속 가능)
# ssh 포트 : 22, root 번호: 0, webpage 번호:500
iptables -A INPUT -p tcp --dport 22 -m owner --uid-owner 0 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m owner --gid-owner 0 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -m owner --uid-owner 0 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -m owner --gid-owner 0 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m owner --uid-owner 500 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m owner --gid-owner 500 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -m owner --uid-owner 500 -j DROP
iptables -A OUTPUT -p tcp --dport 22 -m owner --gid-owner 500 -j DROP

# 1초에 15번 이상의 HTTP 접근을 할 경우 차단
iptables -A INPUT -p tcp --dport 80 -m recent --update --seconds 1 --hitcount 15 --name HTTP -j DROP

#--------------------------------------------------------------------
# 커널 컴파일 및 iptables 패치 후, connlimit 사용이 가능한 경우
# 1초에 15번 이상의 HTTP 접근을 할 경우 차단
#iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 15 -connlimit-mask 24 -j DROP

#메일서버의 경우 동시에 5개이상 SMTP 접근일 경우 5분동안 접근 제한
#iptables -A INPUT -m recent --name spammer --rcheck --seconds 300 -j DROP
#iptables -A INPUT -p tcp --syn --dport 25 -m connlimit --connlimit-above 5 -m recent --name spammer --set -j DROP
#---------------------------------------------------------------------

#----------------------------------------------------------------------
# STRING 필터기능
# MSN 문자열이 들어간 패킷 차단
#iptables -A FORWARD -m string --string "messenger.msn.com" -j DROP

# 싸이월드 접속차단
#iptables -A FORWARD -p tcp --dport 80 -m string --string "Host: cyworld.nate.com" -j DROP
#----------------------------------------------------------------------

# 서버가 해킹당했을 때 DoS공격지로 사용될 경우에 적용.
# DNS 쿼리 이외 UDP 패킷 전송 방지
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -p udp ! --dport 53 -m state --state NEW -j DROP


스크립트 실행 후

# service iptables save

# service iptables restart


당연한 이야기지만, 이 스크립트는 root 권한으로 실행시켜야 한다.
시스템이 부팅될 때 이를 실행하고자 한다면, /etc/rc.local 에 등록해두자.

이를 해제하기 위해서는

iptables -F
iptables -F syn-flood
iptables -X syn-flood


[원문] - http://adminplay.com/board/?mid=Lsecurity&page=1&document_srl=12226
2010/10/12 11:29 2010/10/12 11:29
Posted
Filed under PHP
function utf8_urldecode($str) {
   
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str
));
    return
html_entity_decode($str,null,'UTF-8'
);;
}

2010/10/08 16:24 2010/10/08 16:24
Posted
Filed under C#

[출처]- http://dragonwind.egloos.com/4849313

1. ASP.net 1.0 기준으로 web form 에서 이미지를 합쳐서 저장하기.
---------------------------------------------------------------------------
Bitmap bmap = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bmap);

System.Drawing.Image img = Bitmap.FromFile("d:\\hoonslogo.gif");
System.Drawing.Image img2 = Bitmap.FromFile("d:\\btn_individual.gif");

g.DrawImage(img, 0, 0);
g.DrawImage(img2, 50, 50);

bmap.Save("d:\\MyTest.gif", System.Drawing.Imaging.ImageFormat.Jpeg);
---------------------------------------------------------------------------

http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=17&MAEULNo=8&no=49092&ref=49092

2. win form 에서 이미지 합치고, picturebox 에 쓰기
---------------------------------------------------------------------------
        private void menuItem2_Click(object sender, System.EventArgs e)
        {
            //select files...
            openFileDialog1.ShowDialog();          

            if( openFileDialog1.FileNames.Length > 0 )
            {
                Bitmap canvas = new Bitmap(50,50*openFileDialog1.FileNames.Length);
                int index = 0;
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(canvas);
                foreach( string filename in openFileDialog1.FileNames )
                {
                    System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
                    g.DrawImage(img,0,50*index,50,50);
                    index++;
                }          

                Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(thumbnailCallback);

                pictureBox1.Image = canvas.GetThumbnailImage(50,50*openFileDialog1.FileNames.Length,myCallback,IntPtr.Zero);

                canvas.Save("temp.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
            }          
        }

        public bool thumbnailCallback()
        {
            return false;
        }


2010/10/08 15:45 2010/10/08 15:45
Posted
Filed under C#
[원문] - http://firstpolaris.tistory.com/?page=7

private
string[] ArrayDistinct(string[] source)

        {

            // generic버전

            //List<string> temp = new List<string>();

            //temp.AddRange(source);

            //IEnumerable<string> distinct = temp.Distinct();

            //return distinct.ToArray<string>();

 

            // .. 버전

            string destination = string.Empty;//임시 필드

            // 중복제거

            for (int i = 0; i < source.Length; i++)

            {

                for (int j = 0; j < source.Length; j++)

                {

                    if (source[i] == source[j] && i != j) source[j] = string.Empty;

                }

            }

 

            // ,를 구분자로 문자열 생성

            for (int i = 0; i < source.Length; i++)

            {

                if (!source[i].Equals(string.Empty)) destination += source[i] + ",";

            }

 

            // 마지막에 붙은 ,하나 제거

            destination = destination.Substring(0, destination.Length - 1);


            return destination.Split(',');

 

        }

2010/10/08 15:43 2010/10/08 15:43
Posted
Filed under Mysql
 REPLACE(content,'b>','strong>'); 

mysql을 이용해서 문자열 변경시 사용 하면 된다.
2010/10/07 17:25 2010/10/07 17:25
Posted
Filed under Linux


- 시간설정


# date [MMDDhhmm[[CC]YY][.ss]

맞추려는 시간이 2004년 07월 15일 오후 4시 15분 50초라면

# date 071516152004.50

타임서버

time.bora.net
time.kriss.re.kr -- 주로 refuse .


타임서버 시간 보기
# rdate -p time.bora.net


타임서버 시간을 로컬 시간으로
# rdate -s time.bora.net


확인
# date

2010/10/02 13:41 2010/10/02 13:41