Test if on a certain page with php? - php

Using PHP, is there a way to test if the browser is accessing a certain page?
For example, I have a header file called header.php which is being pulled into a couple different pages. What I want to do is when I go to a different page, I want to append certain variable to the title.
Example.
Inside header.php:
<?php
$titleA = " Online Instruction";
$title B = "Offline";
?>
<h2>Copyright Info: <?php if ('onlineinstruction'.php) echo $titleA; ?> </h2>
edit: also if you believe there is a simpler way to do this, let me know!

You can use $_SERVER['REQUEST_URI'], $_SERVER['PHP_SELF'], or __FILE__ depending on your version of PHP and how you have your code setup. If you are in a framework it may have a much more developer-friendly function available. For example, CodeIgniter has a function called current_url()
Per PHP Docs:
$_SERVER['REQUEST_URI']: The URI which was given in order to access
this page; for instance, '/index.html'.
$_SERVER['PHP_SELF']: The filename of the currently executing script,
relative to the document root. For instance, $_SERVER['PHP_SELF'] in a
script at the address http://example.com/test.php/foo.bar would be
/test.php/foo.bar. The __ FILE__ constant contains the full path and
filename of the current (i.e. included) file. If PHP is running as a
command-line processor this variable contains the script name since
PHP 4.3.0. Previously it was not available.

<?php
$url = $_SERVER["REQUEST_URI"];
$pos = strrpos($url, "hello.php");
if($pos != false) {
echo "found it at " . $pos;
}
?>
http://www.php.net/manual/en/reserved.variables.server.php
http://php.net/manual/en/function.strrpos.php

You can use this variable to find out what page you're on:
$_SERVER['PHP_SELF']
http://www.php.net/manual/en/reserved.variables.server.php

read this: http://php.net/manual/en/language.constants.predefined.php

Any php page can include the following code, putting the applicable page title in the variable.
<?php
//Set Page Title for header template
$page_title = 'Welcome';
require_once("templates/header.php");
?>
In the header template:
<title><?php echo $pageTitle ?></title>
Any page called up will show your preferred title in the browser tab, and be usable as a variable on the specific page.

Related

PHP include only on homepage URL

I need to include external php file only on homepage of my website.
But, since all the pages on the site use the same page template (homepage template), I cant filter them based on that so I was wondering is there a way to include PHP file ONLY on homepage URL (which is www.domain.com/folder) and not to show it on any other page (for example www.domain.com/folder/lorem).
I tried using this snippet in my header.php file:
<?php
if ($_SERVER['PHP_SELF'] = '/')
include('some-file.php');
?>
and the file gets included on all other pages as well.
I am a PHP newbie so sorry if it is stupid question :)
UPDATE:
I did changed it to
<?php
if ($_SERVER['PHP_SELF'] == '/')
include('some-file.php');
?>
and it still isnt showing up.
You can use WordPress's is_front_page() function to check.
Thus, your code should be:
<?php
// if code does not work, adding the next line should make it work
<?php wp_reset_query(); ?>
if ( is_front_page() ) {
include('some-file.php');
}
?>
Source: https://codex.wordpress.org/Function_Reference/is_front_page
Alternatively, if the above is not working, you can try:
if ( $_SERVER["REQUEST_URI"] == '/' ) {
include('some-file.php');
}
As a last resort, try using plugins to insert PHP directly into the pages, one such plugin is https://wordpress.org/plugins/insert-php/.
UPDATE: After the elaboration in comments, I've come up with an alternate method, as shown below.
In your case, this might work. This code would get the URL first, then parse it to get the directory, and assign the directory to $directory. If it is a on the homepage, the $directory will not be set, thus include some-file.php.
<?php
// Get URL
$link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
// Get Directory (eg. will return 'folder' in example.com/folder/files)
$parts = explode('/', $link);
$directory = $parts[3];
// If $directory is null, include PHP (eg. example.com, there is no directory)
if ($directory == ''){
include('some-file.php');
}
?>
Hope the above methods help, thanks!
There's a couple of issues with your code:
<?php
if ($_SERVER['PHP_SELF'] = '/')
include('some-file.php');
?>
As already mentioned your comparison (==) isn't working as you are actually using assignment (=).
Second, the super global variable $_SERVER['PHP_SELF'] will never contain only / as that variable will contain a path and filename to the file that's currently executing, as stated in the documentation.
So you have to single out your file and of course use the correct way of comparison. So the script might look something like the following instead:
<?php
if (basename($_SERVER['PHP_SELF']) == 'index.php')
include('some-file.php');
?>
Of course, this won't work as expected if you have multiple index.php files in separate directories.
if-statements always break down to a true or false, one = is an assignment
Your error results in saying $_SERVER['PHP_SELF'] IS '/' and therefore true.
You must use == for comparison or === for typesafe comparison.
From:
http://php.net/manual/en/reserved.variables.server.php
'PATH_INFO' is probably what you want to use:
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.
For every wordpress page there is an id .So you can write this condition based on id so
(1)Please find your home page id
if 2 is your home page id then write the following code in template file after the header
<?php
if (get_the_ID() == 2)
include('some-file.php');
?>
for to know details about get_the_ID() read this https://developer.wordpress.org/reference/functions/get_the_ID/
Use is_front_page() in your conditional. This returns true when you're on the page you nominated as the home page. Don't use is_home(). That returns the blog post archive page.
I know ... confusing right? But that's WordPress for ya.
You should change your include to include_once, so the file will be included only one time.
$_SERVER['PHP_SELF'] comparison to '/' makes no sense. Instead of '/' try to use the path of your index file.
Another way would be to use the __FILE__ constant, but that will work only on your environment
<?php
if ($_SERVER['PHP_SELF'] == '/index.php'){
include_once('some-file.php');
}
?>

How to get current page URL in Drupal?

I'm trying to output the current page URL on a Drupal site (Drupal 7), I've tried the following...
<?php print current_path(); ?>
Which outputs the page name but not the URL, any ideas on how to output the full URL too?
In straight PHP you can use this:
$curPathName = $_SERVER["DOCUMENT_ROOT"];
$currentURL = $_SERVER["HTTP_HOST"];
I don't see why that wouldn't work. That will give you the path and the URL.
You can use
<?php
global $base_url;
print $base_url . '/' . current_path();
?>
If you want to keep things done "the drupal way", you can use current_path() or request_path().
https://api.drupal.org/api/drupal/includes!path.inc/function/current_path/7
https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/request_path/7
You can also use $base_url instead of relying on $_SERVER.
The solution durbpoisn gave will give you the URL in the browser. If that is an alias, you can use drupal_get_normal_path() to get the internal path
https://api.drupal.org/api/drupal/includes!path.inc/function/drupal_get_normal_path/7
in drupal9
$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
On D7 if you want to get the current path you can use:
$path = drupal_get_path_alias();
So if your current URL is:
www.test.com/hello/world
You will get:
'hello/world'

How can I get current page name including $_GET variable in URL?

Let's say I have the page:
index.php?page=page-title-here
I want to get the current page name including the $_GET variable in the URL.
I am currently using this:
basename(__FILE__)
It outputs "index.php", the actual file name. Any idea how to also include the $_GET variable so that it will output "index.php?page=page-title-here"?
The variable $_SERVER["REQUEST_URI"] gives you the file with GET parameters. Also includes folders in the url.
Edit: Use $page = end(explode('/', $_SERVER["REQUEST_URI"])); if you want to get rid of the folders from the url.
You can do so using the REQUEST_URI:
echo $_SERVER['REQUEST_URI'];
From the manual:
REQUEST_URI: The URI which was given in order to access this page; for instance
Try...
$page = (__FILE__) . '?' . $_GET['page'];
Try $_SERVER['REQUEST_URI'] (there are lots of interesting things in $_SERVER)
Use:
basename($_SERVER['REQUEST_URI'])

Is there any method to replace iframe?

I just meet an important problem as I have a lot of sources from another domain which means if I use iframe, I have to resize all of these contents. But the problem is that I can not modify or insert code to source web page.
Because of these, I would like to ask if there are any other solutions to skip useing iframe?
Tips: I need the entire contents (include images, css and so on) from the url. Not part of the contents.
Quick idea - you could try to write a proxy on server side and serve the content in the iframe, but with src pointing to the proxy page instead of the real page (i.e. controlled with passed parameters)
PHP's include function might be the best place to start. Is it just the markup you're unable to change, or are you able to use PHP and JavaScript?
EDIT:
Try using include('http://www.google.com') to include a URL in your page without using an iFrame. Any non-absolute directory references in the code (like <img src='/img.png'> will not display or load correctly.
If you need to fix up these references and don't have the ability to change the markup itself, you can use the file_get_contents function and modify things like this:
$page = file_get_contents('http://www.google.com');
$page = preg_replace('/(href|src)=([\'"])\//',"$1=$2http://google.com/",$page);
echo $page;
Make an AJAX call using the JSONP data type to return the contents of the other page. You would need to make modifications to the code on both domains though to make this work. http://en.wikipedia.org/wiki/JSONP
Modified answer of #beanland, my /proxy.php file, with caching:
$host = parse_url($_GET['url'], PHP_URL_HOST);
$dir = $_SERVER[DOCUMENT_ROOT].'/cache_proxy/'.$host;
if(!is_dir($dir))
mkdir($dir);
$filepath = $dir.'/'.md5($_GET['url']);
if(is_file($filepath)){
include($filepath);
}else{
$page = file_get_contents($_GET['url']);
$page = preg_replace('/(a href)=[\'\"](http.*)[\'\"]/', '$1="http://buy/proxy.php?url=$2"', $page);
$page = preg_replace('/(a href)=[\'"][^http](.*)[\'"]/', '$1="http://buy/proxy.php?url=http://'.$host.'/$2"', $page);
$page = preg_replace('/(href|src)=[\'"][^http+](.*)[\'"]/', '$1="http://'.$host.'/$2"', $page);
file_put_contents($filepath, $page);
echo $page;
}
First replace all <a href=""> links to your proxy, then replace all relative <img src="/path..."> etc. to absolute <img src="http://...">
jQuery Load into a div http://api.jquery.com/load/

Get current page URL and title in WordPress?

How to get current page URL and title in WordPress?
Here are few super global variables for getting url info:
$_SERVER['PHP_SELF'];
$_SERVER['REQUEST_URI'];
$_SERVER['SCRIPT_NAME']
$_SERVER['SCRIPT_NAME']
$_SERVER['SCRIPT_NAME'] will be same - /index.php. It is irrespective of the actual URI ($_SERVER['REQUEST_URI']) used to access the site.
As it returns the actual script name, it fails provide additional path information that may be present. So if the $_SERVER['REQUEST_URI'] is /index.php/big/directory/ then too the $_SERVER['SCRIPT_NAME'] will be same - /index.php.
$_SERVER['SCRIPT_NAME'] is supported on all platforms
$_SERVER['PHP_SELF']
This is the filename of the currently executing script, relative to the document root. However, unlike $_SERVER['SCRIPT_NAME'], it provides additional path information like $_SERVER['REQUEST_URI'] when the actual php file is present in the path. So when the $_SERVER['REQUEST_URI'] is /index.php/big/directory/ then $_SERVER['PHP_SELF'] will be /index.php/big/directory/.
However if all the URI's under http://www.example.com/ is mapped to http://www.example.com/index.php, then, for example, http://www.example.com/abc/def will return /index.php like $_SERVER['SCRIPT_NAME']. Note that $_SERVER['REQUEST_URI'] data is ignored for this request.
$_SERVER['REQUEST_URI']
It will give you entire url including query string vars.
Title of the page:
There is no built-in functionality to get title of the page, however, you can use the HTML Simple DOM to read the contents of <h2.
Example:
$title = str_get_html('<title></title>');
Now, you can use $title however, you like. Visit the their site for more info about it.
If you are using wordpress, and you want to print the post title you can use,
<?php echo get_the_title(); ?>
documentation here: http://codex.wordpress.org/get_the_title
you can get the URL by
'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']
or
$_SERVER['SCRIPT_URI']
might work on some platforms.
the title is something that the PHP program gives back to the browser via HTML:
<html><head><title>title is here</title> ...
so it is not something that you "get" unless you get something from the DB and send back to the browser.
Update... do you mean the title of page that leads to your php file? (the user clicks on that page to get to your php file.) in that case, you can use $_SERVER['HTTP_REFERER'] but it is not guaranteed to contain any data (but most of the time it will).

Categories