PHP include only on homepage URL - php

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');
}
?>

Related

Get Referer URL and FOLDER name in PHP

I have several folders on my domain, within each folder contains an index.php file that checks to see if the database connection passes or fails, if it fails, the page is redirected to a top level file (outside of all folders) called offline.php. This part works great. The basic format I'm using to redirect if the db is offline is:
if ( !$dbconnect ) {
header("Location: https://www.test.com/offline.php");
}
Then, within the offline.php page, I need to check to see which folder brought the user to the offline.php page, and display a unique message to the user - based on the folder that brought them to the offline.php page.
For example:
test.com/test1/index.php redirects to offline.php, the message would say 'test1 brought you to this page'
test.com/test2/index.php redirects to offline.php, the message would say 'test2 brought you to this page'.
In multiple browsers I've tried the following code, which always results in 'unknown uri':
$url = 'https://' . $_SERVER['HTTP_REFERER'] ;
if ( strpos($url,'test') !== false ) {
echo 'test';
} elseif ( strpos($url,'test1') !== false ) {
echo 'test1';
} elseif ( strpos($url,'test2') !== false ) {
echo 'test2';
} else {
echo 'unknown uri';
}
Suggestions?
EDIT
Due to the unreliable nature of HTTP_REFERER I've decided to put all of the conditions within the index.php page and forget about the offline.php page. A HUGE thank you to everyone who offered suggestions!
Why would you use redirects at all? They are heavy on the server, slow and just plain old unnecessary. Use a switch statement and have 1 controlling page instead of multiple folders and pages.
If you use the following code on your offline.php page, you can see all of the $_SERVER variables available (referring URL is in there)
echo '<pre>',print_r($_SERVER),'</pre>';
From there, you can take $_SERVER['HTTP_REFERER'] use a select case, or if then statement and accomplish your goal.
Based on some of your questions in the comments and people pointing out the use of $_SERVER['HTTP_REFERER'] being unreliable, you could do something like this instead.
On your index.php page with the dbconnect check, you could modify it to be something like this. header("Location: https://www.test.com/offline.php?org=".urlencode($_SERVER['REQUEST_URI']));
Then, on the offline.php,
$page = urldecode($_GET['org']);
$org = explode('/',$page);
echo $org[1] to get the first value after the slash, $org[2] would get the next value etc..

php page to redirect to another

I have a php page which should be included in otherpage but no directly. Lets assume it as 1.php and the other page as 2.php
1.php
<?php
if($_SERVER['REQUEST_URI'] == "/1.php"){
header("Location:2.php");
}
else
{
//some code here
}
?>
2.php
<?php
include("1.php");
?>
this worked well on localhost/1.php and have been redirected to localhost/2.php
but this had made a problem with localhost/1.php?somegetmethod=data I found that anyone can access this page by typing ?something=something at the end of 1.php url. How to change the code which can redirect all url which starts with localhost/1.php
you could check if a substring is at a given position like this
if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0) {
this checks if the REQUEST_URI starts with /1.php (= is at position 0)
Use $_SERVER['PHP_SELF'] instead of $_SERVER['REQUEST_URI'].
try it:
if($_SERVER['SCRIPT_NAME'] == "/1.php")
$_SERVER['REQUEST_URI'] contains URI of requeted page, in yoour case it's 1.php?somegetmethod=data.
Change code like:
if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0){
header("Location:2.php");
}else{
//some code here
}
What you often see, for instance in MediaWiki, WordPress and many other such applications, is this:
1.php
if ( !defined( 'YOURAPPCONSTANT' ) ) {
// You could choose to redirect here, but an exit would make just as much
// sense. Someone has deliberately chosen an incorrect url.
echo "Cannot directly call this file.";
exit( 1 );
}
2.php
define('YOURAPPCONSTANT', 'It is defined');
include('1.php');
That way, 2.php is the entry of your application, regardless of the url used to reach it. I think this is a much safer and more flexible way, and it is used so often for a reason.

Conditional PHP, if last segment of url = 'contact'

Is it possible to write conditional PHP that checks the last segment (or any segemnt) of the url?
The following can check if the first url segment
<?php if (arg(0) == 'contact'): ?>
stuff to do here
<?php endif; ?>
My issue is that I need to check for the last url segment, the problem being that the site is in the web root when live but in my localhost folder when being worked on locally. So I cant just go for the 2nd segment if my site will be mysite.com/contact when live, as when its locally it will be localhost/mysite/contact
Thanks
Why not use parse_url ?
There are numerous ways to achieve this but you probably want to stick to drupal-specific functions where possible. That way, if the underlying implementation changes, your code can still work. The drupal function arg() called without any parameters will return all components from the path, so you can just:
$args = arg();
<?php if ( $args[count($args)-1] ) == 'foo' ): ?>

Test if on a certain page with 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.

I don't know what to call it php/css error tho

whats going on is everything is loading just fine url is deigned.sytes.net except for the links when i click about us or services or contact they look like there loading but the content in body.tpl doesn't change from default. maybe you can help me with this why the links are not changing. you u want here are the ONLY php files
I have made phps files for view perpose's but if you insist on it i will post the require code.
designed.sytes.net/index.phps
designed.sytes.net/classes/file.class.phps
In the URLs you name the parameter p but in your files.class.php you actually test for $_GET['page']. So either change the URLs to use page as parameter or change the code to:
// in files.class.php instead of if(!isset($_GET['page']))
if(!isset($_GET['p'])){
// your code here...
} else {
// ...
}
In your original code, as $_GET['page'] does never exist, it always shows the index page.
Another thing that looks strange to me is the following (but maybe it is just how you set it up):
if(file_exists($_GET['page'].'.txt')){
// and lets include that then:
ob_start();
include("contents/". $_GET['page'] . '.php');
$content = ob_get_contents();
ob_end_clean();
}
You first check whether the text file e.g. about.txt exists but then include a PHP file contents/about.php. Is this intended? Does the PHP always exist if the text file exists?
UPDATE:
Also make sure that you properly check the value that you get from $_GET['page'] or however you call it in the end.
E.g. this call http://designed.sytes.net/index.php?page=../index seems to kill your server (sorry it was unintentionally :( )
UPDATE 2:
In order to provide "some" security you could check whether $_GET['page'] is one of predefined values instead of checking whether a file with this name exists. E.g:
$valid_pages = array('home', 'about', 'services', 'contact');
if(isset($_GET['page']) && in_array($_GET['page'], $valid_pages) {
// include page here
}
else {
// redirect to home page
}
That makes sure that $_GET['page'] is not of form of relative pathes like ../index. If it is not one of those values in $valid_pages you redirect to the home page.
I see in your http://designed.sytes.net/classes/file.class.phps file you have $_GET['page'] but on the query string you have p=
an example of what does not work is:
http://designed.sytes.net/index.php?p=about
and then changed to:
http://designed.sytes.net/index.php?page=about
seems to show something different.

Categories