vbscript / classic ASP- 자신의 파일 이름을 프로그래밍 방식으로 얻을 수있는 방법이 있습니까?

StackOverflow https://stackoverflow.com/questions/450552

  •  19-08-2019
  •  | 
  •  

문제

나는 단지 오래된 코드를 검토하고 다음을 발견했습니다 (foo.asp 내부).

Const ASP_FILENAME = "foo.asp"  ' TODO: Update this to the name of this file (if changed)

변수는 로깅 오류에만 사용됩니다. (예 : "foo.asp의 오류 - xxxxx 객체를 만들 수 없습니다.") 이것을 피할 수있는 방법이 있습니까?

감사!

도움이 되었습니까?

해결책

현재 정의 된 aspfaq.com에서 (감사합니다 archive.org):

현재 URL / 페이지의 이름을 어떻게 얻습니까?

이것은 매우 쉽지만 두 부분이 있습니다.

현재 파일의 이름을 검색하려면 다음 중 하나를 사용할 수 있습니다.

<% 
    Response.Write Request.ServerVariables("SCRIPT_NAME") & "<br>" 
    Response.Write Request.ServerVariables("PATH_INFO") & "<br>" 
    Response.Write Request.ServerVariables("URL") & "<br>" 
%>

해당 경로를 로컬로 만들려면 (예 : FileSystemObject와 함께 사용하려면) Server.mappath () 메소드를 결과에 적용하십시오.

http : // 또는 https : // prefix를 포함하여 전체 URL을 얻으려면 다음을 수행 할 수 있습니다.

<% 
    prot = "http" 
    https = lcase(request.ServerVariables("HTTPS")) 
    if https <> "off" then prot = "https" 
    domainname = Request.ServerVariables("SERVER_NAME") 
    filename = Request.ServerVariables("SCRIPT_NAME") 
    querystring = Request.ServerVariables("QUERY_STRING") 
    response.write prot & "://" & domainname & filename & "?" & querystring 
%>

페이지 이름 만 얻으려면 다음과 같은 것을 사용하십시오.

<% 
    scr = Request.ServerVariables("SCRIPT_NAME") & "<br>" 
    if instr(scr,"/")>0 then 
        scr = right(scr, len(scr) - instrRev(scr,"/")) 
    end if 
    response.write scr 
%>

또는 IF 논리없이 :

<% 
    scr = Request.ServerVariables("SCRIPT_NAME") & "<br>" 
    loc = instrRev(scr,"/") 
    scr = mid(scr, loc+1, len(scr) - loc) 
    response.write scr 
%>

지금. 파일이 다른 파일 내에서 #include 인 경우 위의 스크립트는 호출 파일의 이름을 생성합니다 (포함 된 파일이 먼저 호출 스크립트에 통합되므로 해당 내부의 ASP는 모두 '부모의 맥락에서 실행됩니다. '파일). 이 문제를 해결할 수있는 한 가지 방법은 각각 포함 파일을로드하기 전에 current_filename 변수를 다시 채우는 것입니다.

<% 
      current_filename = "filetoinclude.asp" 
 %> 

<!--#include file='filetoinclude.asp'-->

(그리고 아니오, current_filename을 #include 지시문으로 변수로 전달하지 마십시오. 기사 #2042 참조).

그런 다음 filetoinclude.asp에서 :

<% 
    Response.Write "Current file: " & current_filename 
%>

물론 각 파일 내부의 파일 이름을 쉽게 하드 코딩 할 수 있습니다. 그러나 나는 해결책이 그 정보를 적어도 다소 동적으로 검색하는 목적을 다소 물리 칠 것이라고 생각합니다.

다른 팁

당신은 구문 분석 할 수 있습니다 Request.ServerVariables("url") 파일 이름 부분을 얻습니다. Google 검색이 발견되었습니다 이 코드, 신용을 청구하지 않는다. 실제로 더 의미가있는 것처럼 보이는 Script_name 서버 변수를 사용하는데, 또한 URL을 다시 작성하여 다음과 같은 계정을 가져옵니다.

function getFileName(fpath, returnExtension)
        tmp = fpath
        if instrRev(tmp,"/") > 0 then
              tmp = mid(tmp, instrRev(tmp,"/")+1)
        end if
        if returnExtension = false then
              if instrRev(tmp,".") > 0 then
                    tmp = left(tmp, instrRev(tmp,".")-1)
              end if
        end if
        getFileName = tmp
  end function

  filename = request.ServerVariables("SCRIPT_NAME")
  Const ASP_FILENAME = getFileName(filename, true)

Server.mappath가 기존 ASP에 존재하는지 모르겠지만, 그렇다면 페이지 파일 이름을 알 수 있습니다.

여기에있는 사람은 [이산 목구멍 청소 기침을 삽입]이 여전히 레거시 애플리케이션을 유지하고 지원하기 위해 클래식 ASP를 사용한다고 말하지는 않지만 최근에는 비슷한 일을해야했습니다. "클래식 ASP로 불가능하다"는 응답을 거부하면서 나는 길을 찾아 다음 해결책을 생각해 냈습니다.

이 접근법은 기본적으로 기본 OS 명령을 활용하여 문자 그대로 결정합니다. 현재 파일 이름 (그 결과는 사용과 동일합니다 __FILE__ 파일이 포함되는지 여부에 관계없이 PHP의 Magic Constant)*.inc) 또는 스크립트 자체 (*.asp).

먼저, 일부 소독을 지원하려면 (원하는 경우 다른 "최적의"방법을 수행 할 수 있음) :

'Regex helpers
Function NewRegex(ByVal pattern, ByVal ignore_case, ByVal global)
  Set NewRegex = New RegExp
  NewRegex.Pattern = pattern
  NewRegex.IgnoreCase = ignore_case
  NewRegex.Global = global
End Function

Function RegexMatch(ByVal pattern, ByVal subject)
  RegexMatch = RegexMatches(subject, pattern, True, False)
End Function

Function RegexMatches(ByVal subject, ByVal pattern, ByVal ignore_case, ByVal global)
  RegexMatches = NewRegex(pattern, ignore_case, global).Test(subject)
End Function

그리고 이제 "반사 :"의 시간 동안

Function GetCurrentFilename(ByVal uniqueId)
  '1. Enforce uniqueId format
  If Not RegexMatch("^[0-9a-f]+$", uniqueId) Then
    Exit Function
  End If

  '2. Use findstr to scan "readable" files in current directory for uniqueId
  Dim shell, cmd, process, fs, filename
  Set shell = Server.CreateObject("WScript.Shell")

  'See findstr /? for details on switches used below
  'cmd = C:\Windows\system32\cmd.exe /c findstr /P /M /C:"uniqueId" "C:\Inetpub\wwwroot\includes\*"
  cmd = shell.ExpandEnvironmentStrings("%COMSPEC%") & " /c findstr /P /M /C:""" & uniqueId & """ """ & Server.MapPath(".") & "\*"""
  Set process = shell.Exec(cmd)

  '3. Use Scripting.FileSystemObject to return the filename portion of the first result returned
  Set fs = Server.CreateObject("Scripting.FileSystemObject")
  GetCurrentFilename = fs.GetFileName(process.StdOut.ReadLine())

  Set fs = Nothing
  Set process = Nothing
  Set shell = Nothing
End Function

그런 다음 현재 파일 이름을 "검사"하려는 파일 내부에서 다음 줄을 삭제하여 현재 디렉토리의 다른 파일에 존재하지 않아야 할 고유 식별자를 전달합니다.

'myfile.inc
Response.Write "This is in " & GetCurrentFilename("908ab098c")

결과:

This is in somefile.inc

아, 그리고 내가 이것을 사용하는 데 필요한 것에 관심이 있다면, 간단한 브레이크 포인트 기능에 사용되는 것과 같습니다.

Function Breakpoint(ByVal line_no, ByVal uniqueId, ByVal msg)
  Dim fn
  fn = GetCurrentFilename(uniqueId)

  Response.Write "[!] Breakpoint hit at Line " & CLng(line_no) & " in " & fn & ": " & Server.HtmlEncode(msg) & vbNewLine
  Response.End
End Function

내 코드의 20 행에서 나 자신의 중단 점을 추가하고 싶다면 다음과 같이 보일 것입니다.

Breakpoint 20, "B0001", "Some debug output here"

산출:

[!] Breakpoint hit at Line 20 in somefile.inc: Some debug output here

행복한 코딩!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top