匹配包含头标记的第一行,并将其作为字符串存储在变量中


Match first line containing head tag and store in variable as a string

我正试图从同一目录下的外部php文件中编写一个新的元标记到html文件。我将用jQuery测试我的元标签的存在,然后通过ajax调用php函数,如果元不存在。因此,在随后的页面加载我很好。

我试图建立一个函数来做到这一点,但可以使用它的一个方面的一点帮助。我不能保证如何包含打开头标签的行将被写入,所以我想这将需要是某种形式的正则表达式。请参阅下面的代码:

// So the line with the opening head tag may for arguments sake look like this one below :
// <!DOCTYPE html><html lang="en" data-cast-api-enabled="true"><head>  <link id="css-680430062" rel="stylesheet" href="http://s.ytimg.com/yts/cssbin/www-core-vfl8iz0yT.css">
function insert_into_file($file_path, $text, $after = true) {
    $contents = file_get_contents($file_path);
    $insert_marker = ""; // this should be the line containing the opening head tag saved to the variable as a string
    $new_contents = preg_replace($insert_marker, ($after) ? '$0' . $text : $text . '$0', $contents);
return file_put_contents($file_path, $new_contents);

}

为了隐藏路径,我们将对其进行base64编码。任何知道这是什么的人,当他们识别它时,可能会尝试base64解码并注入类似。htaccess的东西,这至少会让他们在试图破解您的处理页面时工作。对于本例,您需要通过ajax将编码的var pathname = window.location.pathname; base64传递给处理器。

jquery base64

注意这没有经过测试,它取决于几个因素,包括系统上Apache用户对目录的写权限。(我也假设你使用apache时,我正在检查。htaccess)。如果我在一个实时网站上运行这个,我也会做一些检查,以确保它运行的IP是我自己的和白名单,这样如果Googlebot或Yandex点击你的网站,你不会开始对你的服务器征税。

你也可以让它更新一个日志,所以如果页面已经被更改,让它检查日志,看看它是否在那里,这样你就不会运行两次脚本。(这只是有点挑剔。)

处理器

<?php
//this assumes the page is base64 encoded in javascript or jquery.
if(!empty($_GET['p'])){
    $path_to_page = base64_decode($_GET['p']);
    if(preg_match('!'.(php|htm[l]?)$!',$path_to_page)){
        $path_to_file = $_SERVER['DOCUMENT_ROOT']."/$path_to_page";
        if(!is_file($path_to_file)){
            //if they passed something else, then 
            exit();
        } else {
            //we're trying to prevent injection
            if(!empty($_GET['id'])&&preg_match('!^'d+$!',$_GET['id'])){
                $user_id = $_GET['id'];
            } else {
                exit(); 
            }
            //open the file in read/write mode
            if($fp = fopen($path_to_file, 'w+')){
            //pull the page into a var for checking
            $page = fread($fp, filesize($path_to_file));
            if(!preg_match('!property's*='s*["'']fb:admins!is',$page)){
            //if it doesn't exist, then add it.
                $page = preg_replace('!</head>!i',"<meta property='"fb:admins'" content='"$user_id'">'n'n</head>",$page);
                if(fwrite($fp, $page))
                {
                    echo 'success';
                } else {
                    echo 'failure';}
                }
            fclose($fp);
           } else {
             echo 'failure';
           }
        }
    }
}
?>

要把它直接放在head标签后面,你可以使用:

$page = preg_replace('!(<head[^>]+>)!i',"$1'n'n<meta property='"fb:admins'" content='"$user_id'">'n",$page);