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' ): ?>
Related
My url is www.mysite.com/properties/property-1-someplace
The /property-1-someplace/ is dynamically generated.
I'm writing an if statement that asks if the url is properties/property-1-someplace then execute code, but property-1-someplace is generated by wordpress and thus is constantly changing.
How can I target pages that are in the properties directory, but access the url afterwards if I don't know what that url is?
I can use the PHP variable $pagename but that does not address the properties part of the url.
If I could do <?php if (is_page( 'property/*.*' ) ): that would be perfect.
Any ideas?
EDIT:
Sorry I misunderstood your question, here is what you are probably looking for. Note that you may have to change the regular expression pattern to /^properties/ depending on the value of $pagename. If $pagename contains the whole URL (e.g. with domain name) then you will need to update the code with the domain name.
if( preg_match( '/^\/properties/', $pagename ) ) {
// Do your stuff here.
}
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');
}
?>
Spent the better part of a day trying to get my head around this and finally need to ask for some help.
I have a bunch of folders which i want to make into subdomains. I have followed the tutorial below and have set up a wildcard redirect in my DNS in step 1 and edited my virualhost in step2. This seems to have gone to plan.
However i am unsure of the logic behind step 3. How does the code below allow me to display content from a folder in a subdomain? i cant figure out what logic i am supposed to try and code - i think i am clearly missing something obvious here.
$serverhost = explode('.',$_SERVER["HTTP_HOST"]);
$sub = $serverhost[0];
if ($sub = "www") {
$sub = "";
}
(text from tutorial)
OK, here's what's taking place. You insert this code in your main php
file and what it does is check to see if the subdomain portion of the
domain (ie: thishere.yourdomain.com) is www. If so, it just nulls
$sub, otherwise, $sub will contain your subdomain keyword. Now, you
can check if ($sub > "") and take appropriate action with your code if
a subdomain exists, to display a page based on that value.
(tutorial link)
http://www.wiredstudios.com/php-programming/setting-up-wildcard-dns-for-subdomains-on-cpanel.html
Thanks in advance.
mmhh well, in fact, this code only permit you to get what subdomain is called.
So if you want to display the content of the folder corresponding to your subdomain, you have to scan your directory, then check if the folder called by subdomain exists, and then include script from this folder.
A simple way to do it is :
$scan = scandir('.'); // scan the current directory
if( in_array($sub, $scan) && is_dir($sub) ){
require( $sub.'/yourscript.php');
}
But this mean that your whole appication is designed in function of the $sub value, each include, each file prefixing etc ...
I am trying to execute code with PHP but only IF the URL is EXACTLY at the entry point of the website: http://mywebsite.com. So specifically ONLY on that URL, nothing after.
I am stumped after trying multiple PHP IF ELSE statements to try gaining it, very close I feel.
<?php $host = $_SERVER['HTTP_HOST']; if($host == "www.mywebsite.com" or $host == "mywebsite.com") { ?> MYHTML1SHOWS <?php } else { ?> MYHTML2SHOWS <?php } ?>
This has given me success in appearing on the domain when most visitors will come to mywebsite.com, but continues to work on all subsequent sub files/pages/directories. Which is 100% not wanted.
So I thought of a work around like ELSEIF's to show MYHTML2 to target all my pages, as they are handily all within country allocated directories: /au/ , /asia/ , /nz/ , /uk/ etc.
<?php } elseif (stripos($_SERVER['REQUEST_URI'],'/au/') !== false) { ?> HTML3 <?php } ?>
This didn’t work, but it was worth a try (works on its own IF statement in previous websites I’ve done, but I figure its clashing with the first IF statement which is more prioritized in the PHP). Appreciate any help guys, this has me stumped but would be ever useful. There were no similar questions on the net for only showing code this way.
(Background: I am implementing a 'Country Selector' that shows only on the entry point of mywebsite.com. I have already set up each country within their own sub-directories, thus no purpose of showing the country selector for them if a customer goes directly to one of those addresses).
You're probably doing some magic with Apache's mod_rewrite ... if not, that might be a good place to start looking. It sounds like the problem you're trying to solve is best done via Apache, either in your httpd.conf or (if enabled) via .htaccess.
http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Otherwise, the $_SERVER variables $_SERVER['PHP_SELF'] and $_SERVER['REQUEST_URI'] are probably of use to you.
http://www.php.net/manual/en/reserved.variables.server.php
$_SERVER['HTTP_HOST'] will only check the domain name, not the requested path. This is as you describe, but doesn't seem to be what you want.
So I made a script so that I can just use includes to get my header, pages, and then footer. And if a file doesnt exist a 404. That all works. Now my issue is how I'm supposed to get the end of the url being the page. For example,
I want to make it so that when someone goes to example.com/home/test, it will automatically just include test.php for example.
Moral of the story. How to some how get the page name. And then use it to "mask" the end of the page so that I don't need to have every URL being something.com/home/?p=home
Heres my code so far.
<?php
include($_SERVER['DOCUMENT_ROOT'].'/home/lib/php/_dc.php');
include($_SERVER['DOCUMENT_ROOT'].'/home/lib/php/_home_fns.php');
$script = $_SERVER['SCRIPT_NAME']; //This returns /home/index.php for example =/
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/home/default/header.php');
if($_GET["p"] == 'home' || !isset($_GET["p"])) {
include($_SERVER['DOCUMENT_ROOT'].'/home/pages/home.php');
} else if(file_exists($_SERVER['DOCUMENT_ROOT'].'/home/pages/'.$_GET["p"].'.php')) {
include($_SERVER['DOCUMENT_ROOT'].'/home/pages/'.$_GET["p"].'.php');
} else {
include($_SERVER['DOCUMENT_ROOT'].'/home/default/404.php');
}
include($_SERVER['DOCUMENT_ROOT'].'/home/default/footer.php');
?>
PHP by itself wouldn't be the best choice here unless you want your website littered with empty "redirect" PHP files. I would recommend looking into the Apache server's mod_rewrite module. Here are a couple of guides to get you started. Hope this helps!
The simplest way would be to have an index.php file inside the /home/whatever folder. Then use something like $_SERVER['PHP_SELF'] and extract the name if you want to automate it, or since you are already writing the file yourself, hardcode it into it.
That however looks plain wrong, you should probably look into mod-rewrite if you are up to creating a more complex/serious app.
I would also recommend cakePHP framework that has the whole path-to-controller thing worked out.