I am requesting the source code of a website like this:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>
Bu I would like to replace the relative links with absolute ones! Basically,
<img src="/images/legend_15s.png"/> and <img src='/images/legend_15s.png'/>
should be replaced by
<img src="http://domain.com/images/legend_15s.png"/>
and
<img src='http://domain.com/images/legend_15s.png'/>
respectively. How can I do this?
This can be acheived with the following:
<?php
$input = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$domain = 'http://stats.pingdom.com/';
$rep['/href="(?!https?:\/\/)(?!data:)(?!#)/'] = 'href="'.$domain;
$rep['/src="(?!https?:\/\/)(?!data:)(?!#)/'] = 'src="'.$domain;
$rep['/#import[\n+\s+]"\//'] = '#import "'.$domain;
$rep['/#import[\n+\s+]"\./'] = '#import "'.$domain;
$output = preg_replace(
array_keys($rep),
array_values($rep),
$input
);
echo $output;
?>
Which will output links as follows:
/something
will become,
http://stats.pingdom.com//something
And
../something
will become,
http://stats.pingdom.com/../something
But it will not edit "data:image/png;" or anchor tags.
I'm pretty sure the regular expressions can be improved though.
This code replaces only the links and images:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$txt = str_replace(array('href="', 'src="'), array('href="http://stats.pingdom.com/', 'src="http://stats.pingdom.com/'), $txt);
echo $txt; ?>
I have tested and its working :)
UPDATED
Here is done with regular expression and working better:
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
$domain = "http://stats.pingdom.com";
$txt = preg_replace("/(href|src)\=\"([^(http)])(\/)?/", "$1=\"$domain$2", $txt);
echo $txt; ?>
Done :D
You dont need php, you only need to use the html5 base tag, and put your php code in html body, you only need to do the following
Example :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<base href="http://yourdomain.com/">
</head>
<body>
<? $txt = file_get_contents('http://stats.pingdom.com/qmwwuwoz2b71/522741');
echo $txt; ?>
</body>
</html>
and all the files will use the absolute url
Related
I am using simple-html-dom for my work. I want to get all PHP script (<?php ... ?>) form file using simple-html-dom.
if i have one file (name: text.php) with below code :
<html>
<head>
<title>Title</title>
</head>
<body>
<?php echo "This is test Text"; ?>
</body>
</html>
then how can i get this PHP script <?php echo "This is test Text"; ?> form above file of code using simple-html-dom.
$html = file_get_html('text.php');
foreach($html->find('<?php') as $element) {
//Sonthing code ...
}
i can not use like this, Is there any other option for this ?
Here's a solution using regex. Note that regex often is not advisable for parsing HTML files. That is, it might be okay in this case.
This will match each instance of a PHP code block and allow you to output (or do whatever else you want) either the entire block (including the tags) or the code that is contained within the block. See the documentation for preg_match_all().
<?php
$string = <<<'NOW'
<html>
<head>
<title>Title</title>
<?php echo "something else"; ?>
</head>
<body>
<?php echo "This is test Text"; ?>
</body>
</html>
NOW;
preg_match_all("/\<\?php (.*) \?\>/", $string, $matches);
foreach($matches[0] as $index => $phpBlock)
{
echo "Full block: " . $phpBlock;
echo "\n\n";
echo "Command: " . $matches[1][$index];
echo "\n\n";
}
DEMO
I am trying to remove script tags from HTML using PHP but it doesn't work if there's HTML inside the javascript.
For example, if the script tags contain something like this:
function tip(content) {
$('<div id="tip">' + content + '</div>').css
It will stop at </div> and the rest of the script will still be taken into account.
This is what I have been using to remove the script tags:
foreach ($doc->getElementsByTagName('script') as $node)
{
$node->parentNode->removeChild($node);
}
How about some regex-based pre-processing?
Example input.html:
<html>
<head>
<title>My example</title>
</head>
<body>
<h1>Test</h1>
<div id="foo"> </div>
<script type="text/javascript">
document.getElementById('foo').innerHTML = '<span style="color:red;">Hello World!</span>';
</script>
</body>
</html>
Script tag removing php script:
<?php
// unformatted source output:
header("Content-Type: text/plain");
// read the example input file given above into a string:
$input = file_get_contents('input.html');
echo "Before:\r\n";
echo $input;
echo "\r\n\r\n-----------------------\r\n\r\n";
// replace script tags including their contents by ""
$output = preg_replace("~<script[^<>]*>.*</script>~Uis", "", $input);
echo "After:\r\n";
echo $output;
echo "\r\n\r\n-----------------------\r\n\r\n";
?>
You can use strip_tags function. In which you can allow the HTML attributes which you want allowed.
I think this is 'here and now' problem, and you need no something special. Just do something like this:
$text = file_get_content('index.html');
while(mb_strpos($text, '<script') != false) {
$startPosition = mb_strpos($text, '<script');
$endPosition = mb_strpos($text, '</script>');
$text = mb_substr($text, 0, $startPosition).mb_substr($text, $endPosition + 7, mb_strlen($text));
}
echo $text;
Only set encoding for 'mb_' like functions
page.php:
<?php
include("header.php");
$title = "TITLE";
?>
header.php:
<title><?php echo $title; ?></title>
I want my title to be set after including the header file. Is it possible to do this?
expanding on Dainis Abols answer, and your question on output handling,
consider the following:
your header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.
then, you can use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
and that should do it.
EDIT
I believe Guy's idea works better since it gives you a default if you need it, IE:
The title is now <title>Backup Title</title>
Code is now:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
1. Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
2. Add following code into header.php
<title><?php echo $title; ?></title>
What you can do is, you store the output in a variable like:
header.php
<?php
$output = '<html><title>%TITLE%</title><body>';
?>
PS: You need to remove all echos/prints etc so that all possible output is stored in the $output variable.
This can be easely done, by defining $output = ''; at the start of the file and then find/replace echo to $output .=.
And then replace the %TITLE% to what you need:
<?php
include("header.php");
$title = "TITLE";
$output = str_replace('%TITLE%', $title, $output);
echo $output;
?>
Another way is using javascript in your code, instead of:
<title><?php echo $title; ?></title>
Put this in there:
<script type="text/javascript">
document.title = "<?=$title;?>"
</script>
Or jQuery, if you prefer:
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "<?=$title;?>");
});
</script>
Expanding a little on we.mamat's answer,
you could use a preg_replace instead of the simple replace and remove the need for a %title% altogether. Something like this:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
you can set using JavaScript
<script language="javascript">
document.title = "The new title goes here.";
</script>
Add this code on top your page
<?php
$title="This is the new page title";
?>
Add this code on your Template header file (include)
<title><?php echo $title; ?></title>
It's very easy.
Put this code in header.php
<?
$sitename = 'Your Site Name'
$pagetitle;
if(isset($pagetitle)){
echo "<title>$pagetitle." | ". $sitename</title>";
}
else {
echo "<title>$sitename</title>";
}
?>
Then in the page put there :
<?
$pagetitle = 'Sign up'
include "header.php";
?>
So if you are on Index.php , The title is Your Site Name.
And for example if you are on sign up page , The title is Sign up | Your Site Name
Every Simple just using a function , I created it .
<?
function change_meta_tags($title,$description,$keywords){
// This function made by Jamil Hammash
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/","<meta name='description' content='(.*)'>","<meta name='keywords' content='(.*)'>");
$replacements = array("<title>$title</title>","meta name='description' content='$description'","meta name='keywords' content='$keywords'");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
First of all you must create function.php file and put this function inside ,then make require under the MetaTags in Header.php .
To use this function change_meta_tags("NEW TITLE","NEW DESCRIPTION",NEW KEYWORDS); .
Don't use this function in Header.php !! just with another pages .
Use a jQuery function like this:
$("title").html('your title');
suppose i have a variable in a seperate php file i.e
$imgfile = "images/img.jpg";
now i have a php file where i am including a html or another php file i.e
<?php
include("foo.html");
?>
and in foo.html i have the following code..
<html>
<head>
<title>foo site</title>
</head>
<body>
<img src="<?php echo $imgfile; ?>">
and it is works but i am including that $imgfile many times so i want not to type
<?php echo $imgfile; ?> again and again.. i have seen many scripts that include such files by just typing {$imgfile} but i don't know how to use it please let me know how can i use such a format..??
PHP is a template engine already.
so, it has shorter form for echo statement, especially for this purpose:
<?=$imgfile?>
considerable shorter and comparable to {$imgfile}
Note that to make use of brackets, you'll have to devise alternatives for loops, conditions and other statements, which will complicate your life.
while using PHP as a template, you'll be able to use built-in PHP operators, like foreach or if or include.
So, it would be better to stick to <?=$imgfile?> syntax.
Just make sure you have short_open_tags setting turned on
I think Smarty, a templating engine, is what you are looking for. See this link: http://smarty.net/
In order to achieve this behavior you should use a template engine like Smarty or write your own interpreter that will replace such expressions with the appropriate values.
e.g.
$buffer = 'Hello {$world}';
$world = "World";
if(preg_match_all("/{([^}]+)}/im", $buffer, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
$expression = $match[0];
$exactMatch = $match[1];
if(defined($exactMatch)) {
$buffer = str_replace($expression, constant($exactMatch), $buffer);
} else {
if(strrpos($exactMatch, "$") !== false) {
$vars = get_defined_vars();
$var = str_replace("$", "", $exactMatch);
if(isset($vars[$var])) {
$buffer = str_replace($expression, $vars[$var], $buffer);
}
}
if(is_callable($exactMatch)) {
$buffer = str_replace($expression, call_user_func($exactMatch), $buffer);
}
}
}
}
echo $buffer;
There are three options for you here.
1) assign <img src="<?php echo $imgfile; ?>"> to a shorter string
$a = "<img src='$imgfile'>";
Then in your templates
<html>
<head>
<title>foo site</title>
</head>
<body>
<img src="<?php echo $imgfile; ?>">
2) Use a placeholder then buffer and post process your output.
In your templates
<?php echo ob_start('myReplacementCallback') ?>
<html>
<head>
<title>foo site</title>
</head>
<body>
{{imgfile}}
<?php ob_end_flush (); ?>
Define myReplacementCallback somewhere:
function myReplacementCallback($contents) {
$replacements = array(
'{{imgfile}}' => "<img src='/path/to/image'>",
);
return str_replace(array_keys($replacements), $replacements, $contents);
}
3) Use a template engine like twig or smarty. (Prefered method)
I am trying to dynamically populate the title tag on a website. I have the following code in my index.php page
<?php $title = 'myTitle'; include("header.php"); ?>
And the following on my header page
<title><?php if (isset($title)) {echo $title;}
else {echo "My Website";} ?></title>
But no matter what I do, I cannot get this code to work. Does anyone have any suggestions?
thanks
This works (tested it - create a new folder, put your first line of code in a file called index.php and the second one in header.php, run it, check the title bar).
You should double check if those two files are in the same folder, and that you're including the right header.php from the right index.php. And ensure that $title is not being set back to null somewhere in your code.
Learn more about Variable Scope here.
Edit: Examples of visible changes would be:
TEST1<?php $title = 'myTitle'; include("header.php"); ?>
<title>TEST2<?php if ...
Are you including the header file before or after you set the title variable? If you're including it before, then of course it won't be set.
if you're doing something like this in your index.php:
<?php
include('header.php');
$title = "blah blah blah";
?>
then it won't work - you include the header file and output the title text before the $title variable is ever set.
try to declare the variable before using it
$title = '123';
require 'includes/header.php';
Hi Try this old school method ..
In your Header file (for e.g. header.php)
<?php
error_reporting(E_ALL);
echo '<!DOCTYPE html>
<!--[if IE 7 ]><html class="ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="ie8" lang="en"><![endif]-->
<!--[if IE 9 ]><html class="ie9" lang="en"><![endif]-->
<!--[if (gte IE 10)|!(IE)]><!-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<!--<![endif]-->
<head>';
?>
<?php
if($GLOBALS['title']) {
$title = $GLOBALS['title'];
} else {
$GLOBALS['title'] = "Welcome to My Website";
}
if($GLOBALS['desc']) {
$desc = $GLOBALS['desc'];
} else {
$desc = "This is a default description of my website";
}
if($GLOBALS['keywords']) {
$keywords = $GLOBALS['keywords'];
} else {
$keywords = "my, site, key, words";
}
echo "\r\n";
echo "<title> ". $title ." | MyWebsite.com </title>";
echo "\r\n";
echo "<meta name=\"description\" content='". $GLOBALS['title']."'>";
echo "\r\n";
echo "<meta name=\"keywords\" content='".$GLOBALS['title']."'>";
echo "\r\n";
?>
In you PHP Page file do like this (for example about.php)
<?php
$GLOBALS['title'] = 'About MyWebsite -This is a Full SEO Title';
$GLOBALS['desc'] = 'This is a description';
$GLOBALS['keywords'] ='keyword, keywords, keys';
include("header.php");
?>
I assume your header is stored in a different file (could be outside the root directory) then all the above solutions will not work for you because $title is set before it is defined.
Here is my solution:
in your header.php file you need to set the $title to be global by: global $title; then echo it in your title so:
<?php global $title; ?>
<title><?php echo isset($title) ? $title : "{YOUR SITE NAME}"; ?></title>
Then in every page now you can define your title after you have included your header file so for example in your index.php file:
include_once("header.php");
$title = "Your title for better SEO"
This is tested and it is working.
We can also use functions and its a good way to work on real time web sites.
Do simple:
create an index.php file and paste these lines:
<?php include("title.php");?>
<!doctype html>
<html>
<head>
<title><?php index_Title(); ?></title>
<head>
</html>
-- Then
Create a title.php file and paste these lines:
<?php
function index_Title(){
$title = '.:: itsmeShubham ::.';
if (isset($title)){
echo $title;
}else{
echo "My Website";
};
}
?>
It will work perfectly as you want and we can also update any title by touching only one title.php file.
<?php
echo basename(pathinfo($_SERVER['PHP_SELF'])['basename'],".php");
?>
This works. Since I'm using PHP I don't check for other extensions; use pathinfo['extension'] in case that's required.
You can achieve that by using define(); function.
In your header.php file add following line :
<title><?php echo TITLE; ?></title>
And on that page where you want to set dynamic title, Add following lines:
EX : my page name is user-profile.php where I want to set dynamic title
so I will add those lines that page.
<?php
define('TITLE','User Profile'); //variable which is used in header.php
include('header.php');
include('dbConnection.php');
?>
So my user-profile/.php file will be having title: User Profile
As like this you can add title on any page on your site
Example Template.php
<?php
if (!isset($rel)) {$rel = './';}
if (!isset($header)) {
$header = true;
?><html>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<?php } else { ?>
</body>
</html><?php } ?>
Pages Your Content
<?php
$rel = './'; // location of page relative to template.php
$pageTitle = 'This is my page title!';
include $rel . 'template.php';
?>
Page content here
<?php include $rel . 'template.php'; ?>
I'm using your code in my project and it works properly
My code in header:
<title>
<?php
if (isset($title)) {echo $title;}
else {echo "عنوانی پیدا نشد!";}
?>
</title>
and my code in index.php:
<?php
$title = "سرنا صفحه اصلی";
include("./include/header-menu.php");
?>