首页 \ 问答 \ PHP time()和.htaccess%{TIME}之差(PHP time() and .htaccess %{TIME} difference)

PHP time()和.htaccess%{TIME}之差(PHP time() and .htaccess %{TIME} difference)

我正在使用PHP自动生成.htaccess文件,我需要能够输出RewriteCond语句的时间。 我能够做到这一点,但.htaccess %{TIME}和PHP time()之间似乎存在5小时的差异。 所以,如果我使用PHP生成以下内容:

$time = time();     // Get the current time
$time = $time + 30; // Add 30 seconds
$expires = date("YmdHis", $time); // Convert to .htaccess time format

$htaccess_contents = "RewriteEngine on" . PHP_EOL; 
$htaccess_contents .= "RewriteCond %{TIME} >$expires" . PHP_EOL; // Check time
$htaccess_contents .= "RewriteRule ^(.*)$ http://google.com/" // Redirect

file_put_contents( $htaccess_path, $htaccess_contents ); // Overwrite .htaccess

上述方法不起作用,因为PHP输出的时间比.htaccess认为时间早5个小时。 我宁愿不在5小时的差异中进行硬编码。 是否可以输出时间,以便PHP和.htaccess中的时间相同?


I am using PHP to auto-generate an .htaccess file, and I need to be able to output the time for a RewriteCond statement. I'm able to do this, but there appears to be a 5-hour difference between .htaccess %{TIME} and PHP time(). So if I use PHP to generate the following:

$time = time();     // Get the current time
$time = $time + 30; // Add 30 seconds
$expires = date("YmdHis", $time); // Convert to .htaccess time format

$htaccess_contents = "RewriteEngine on" . PHP_EOL; 
$htaccess_contents .= "RewriteCond %{TIME} >$expires" . PHP_EOL; // Check time
$htaccess_contents .= "RewriteRule ^(.*)$ http://google.com/" // Redirect

file_put_contents( $htaccess_path, $htaccess_contents ); // Overwrite .htaccess

The above doesn't work because the time that PHP outputs is 5 hours ahead of what .htaccess thinks the time is. I would prefer not to hardcode in the 5 hour difference. Is it possible to output the time so that times in PHP and .htaccess will be the same?


原文:https://stackoverflow.com/questions/22234840
更新时间:2021-10-17 15:10

最满意答案

我找到了问题的解决方案。 使用PIL包时,在安装过程中无法正确编译。 之后我有一个依赖问题。 我用以下方式修复它:

import PIL.EpsImagePlugin
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

然后我在命令中看到了这个:

"- >/dev/null 2>/dev/null"

代码是shell的代码,它在我的系统上不起作用,因为python试图读取一个字面名为- >/dev/null 2>/dev/null ,它不存在。

我换了

"- >/dev/null 2>/dev/null"

"-" 

现在程序从stdin读取。

最终的代码是:

def mioGhostscript(tile, size, fp):
    """Render an image using Ghostscript (Unix only)"""

    # Unpack decoder tile
    decoder, tile, offset, data = tile[0]
    length, bbox = data

    import tempfile, os

    file = tempfile.mktemp()

    # Build ghostscript command
    command = ["gs",
        "-q",                    # quite mode
        "-g%dx%d" % size,        # set output geometry (pixels)
        "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
        "-sDEVICE=ppmraw",       # ppm driver
        "-sOutputFile=%s" % file,# output file
        "-"
    ]

    #command = shlex.split(string.join(command))
    # push data through ghostscript

    try:
        #gs = os.popen(command, "w")

        args = command#['gs','-dSAFER','-dNOPAUSE','-dBATCH','-sDEVICE=jpeg','-sOutputFile=/home/user/output2.jpg /home/user/downloads/test.pdf']
        gs = subprocess.Popen( args, stdout = PIPE, stderr = STDOUT, stdin=PIPE )
        # adjust for image origin
        if bbox[0] != 0 or bbox[1] != 0:
            #gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
            gs.stdin.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
        fp.seek(offset)
        while length > 0:
            s = fp.read(8192)
            if not s:
                break
            length = length - len(s)
            gs.stdin.write(s)
        gs.communicate()[0]
        status = gs.stdin.close()
        #status = gs.close()
        #if status:
        #   raise IOError("gs failed (status %d)" % status)
        im = Image.core.open_ppm(file)
    finally:
        try: os.unlink(file)
        except: pass

    return im

import PIL.EpsImagePlugin
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

我希望这些帖子可以帮助别人。


I found the solution at the problem. It was with the PIL package, something didn't compile right during the installation. After that i had a dependencies problem. I fixed it in the following way:

import PIL.EpsImagePlugin
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

Then I saw this in the command:

"- >/dev/null 2>/dev/null"

the code is a shell's code and it didn't work on my system because python tried to read a file literally named - >/dev/null 2>/dev/null and it doesn't exist.

I replaced

"- >/dev/null 2>/dev/null"

with

"-" 

and the program now read from the stdin.

The final code is:

def mioGhostscript(tile, size, fp):
    """Render an image using Ghostscript (Unix only)"""

    # Unpack decoder tile
    decoder, tile, offset, data = tile[0]
    length, bbox = data

    import tempfile, os

    file = tempfile.mktemp()

    # Build ghostscript command
    command = ["gs",
        "-q",                    # quite mode
        "-g%dx%d" % size,        # set output geometry (pixels)
        "-dNOPAUSE -dSAFER",     # don't pause between pages, safe mode
        "-sDEVICE=ppmraw",       # ppm driver
        "-sOutputFile=%s" % file,# output file
        "-"
    ]

    #command = shlex.split(string.join(command))
    # push data through ghostscript

    try:
        #gs = os.popen(command, "w")

        args = command#['gs','-dSAFER','-dNOPAUSE','-dBATCH','-sDEVICE=jpeg','-sOutputFile=/home/user/output2.jpg /home/user/downloads/test.pdf']
        gs = subprocess.Popen( args, stdout = PIPE, stderr = STDOUT, stdin=PIPE )
        # adjust for image origin
        if bbox[0] != 0 or bbox[1] != 0:
            #gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
            gs.stdin.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
        fp.seek(offset)
        while length > 0:
            s = fp.read(8192)
            if not s:
                break
            length = length - len(s)
            gs.stdin.write(s)
        gs.communicate()[0]
        status = gs.stdin.close()
        #status = gs.close()
        #if status:
        #   raise IOError("gs failed (status %d)" % status)
        im = Image.core.open_ppm(file)
    finally:
        try: os.unlink(file)
        except: pass

    return im

import PIL.EpsImagePlugin
PIL.EpsImagePlugin.Ghostscript = mioGhostscript

I hope this posts can help someone.

相关问答

更多
  • 是字符串错了。含有\的字符串,应该使用转义符,或者改成raw string。cmd=r"E:\javaproject\python01\autoInstall\bak\win_finance\win_finance\DMB-BS3.1.28.24425-finance-win-x86.exe"
  • adb shell grep crashlog /data/xxx |awk '{print $2}' 是一条Linux下的Shell指令,adb、grep这些命令在windows中都是没有的吧
  • 我找到了问题的解决方案。 使用PIL包时,在安装过程中无法正确编译。 之后我有一个依赖问题。 我用以下方式修复它: import PIL.EpsImagePlugin PIL.EpsImagePlugin.Ghostscript = mioGhostscript 然后我在命令中看到了这个: "- >/dev/null 2>/dev/null" 代码是shell的代码,它在我的系统上不起作用,因为python试图读取一个字面名为- >/dev/null 2>/dev/null ,它不存在。 我换了 "- ...
  • popen已弃用。 改用子进程 。 例如,在你的情况下: p1 = Popen(["cat", "log.txt"], stdout=PIPE) p2 = Popen(["grep", "ERROR"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] popen is deprecated. Use subprocess instead. For example, in your case: p1 = Popen(["cat", "l ...
  • IIRC, popen返回的错误与system()库调用相同。 要提取实际错误,您必须使用WEXITSTATUS宏。 幸运的是,您有os.WEXITSTATUS这个功能。 >>> import os >>> os.WEXITSTATUS(68864) 13 我不确定它的意思,它可能会在终止之前向控制台输出一些错误。 您是否尝试手动运行该程序? 一个疯狂的猜测是,这13数字实际上是导致失败的错误。 如果是这样的话,那么: >>> os.sterror(13) 'Permission denied' IIR ...
  • 您需要从变量中组合字符串。 首选的方法是使用format方法: cmd = "{BB} {BBDISP} \"status {NODE}.thisIsATest {COLOR} str({NOW}) {MSG} \"".format( BB = os.environ["BB"], BBDISP = os.environ["BBDISP"], NOW = datetime.datetime.now(), COLOR="green", MSG="Widgets loade ...
  • 这可能是一个编码问题,您的输入与文件系统的输出预期不完全匹配。 首先,您需要告诉Python您的输入使用的编码,然后是popen()调用所需的编码。 >>> filename = "C:\\testüüüdirectory\\".decode("utf-8") >>> res = os.popen("dir " + filename.encode("cp1252")) 您可能需要尝试各种编码组合才能获得正确的配对。 UTF-8,UTF-16和cp1252最适合Windows,但您的系统可能设置为使用其他编 ...
  • 据我所知,你不能。 颜色是控制台的属性,而不是输出文本本身的属性。 它不像在Linux中那样你在文本中获得转义字符设置颜色并将其读回控制台保留颜色。 另一个副作用是你不能为STDOUT和STDERR提供单独的颜色,如本问题所示: 在Windows中设置stdout / stderr文本颜色 You can't, as far as I know. The color is a property of the console and not of the output text itself. It's no ...
  • ruby正在缓冲数据。 使用类似的东西 $stdout.flush 让它齐平。 我不确定这是否是正确的ruby命令。 强制性: 使用subprocess模块。 os.popen 已被它取代 。 import subprocess import sys cmd = ["ruby", "/Users/smcho/Desktop/testit.rb"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in iter(p.stdout.rea ...
  • */仅在执行globbing时有效; 在os.popen ,整个字符串由一个包含实际ls进程的shell进行评估,而shell正在执行扩展。 当你使用基于list的Popen ,它将文字字符串*/传递给ls ,并且ls不会自己扩展globs。 您可以将str和shell=True传递给Popen ,但这只是重新打开os.popen具有的性能,安全性和稳定性漏洞。 更容易避免子os.scandir ,只需使用glob模块或os.listdir / os.scandir / os.walk而不是使用子os.sc ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)