I've written some code that includes 'home.php' if the URL contains 'index.php':
<?php if($_GET['page'] != "index.php") {
include('_includes/home.php'); } ?>
This works fine for a specific page (in this instance the home page), but I want to extend this logic for any page on my site. For instance if the URL contained 'foo2.php' I'd want the the PHP to search for and include '_includes/foo2.php'.
I'm new to php so any help would be appreciated.
if the URL was:
http://example.com/?page=foo2
if (empty($_GET['page'])){
include ("_includes/index.php");
exit;
}
$Page_Search = glob("_includes/*.php");
if (in_array($_GET['page'],$Page_Search)){
include ("_includes/$page.'.php');
exit;
}
This might be of use.
How about:
if(isset($_GET['page'])) include "_includes/{$_GET['page']}.php";
Related
My problem might seem very basic, but i don't know how to search about this in google. I want my website's content to be reachable only trough global get variables. Like so..
<?php
include("../backend/connection.php");
if(isset($_GET['page'])){
if ($_GET['page'] === "register"){
include ("pages/register.php");
}
elseif($_GET['page'] === "login"){
include ("pages/login.php");
}
elseif($_GET['page'] === "home"){
include ("pages/home.php");
}
}
?>
So, the user can access the register page trough "www.mywebsite.com?page=register". But he can also access that page using "www.mywebsite.com/pages/register.php". This is a problem. The connection file is included only in my index file. The register.php file contains code that requires a database connection, and since that database connection is included only in the index file, the user will get error. Trough that error he will get information about my website directories, and he might try to continue digging until he finds a hole.
I think the following code might fix the problem.
<?php
include("../backend/connection.php");
if(isset($_GET['page'])){
if ($_GET['page'] === "register"){
include ("pages/register.php");
}
elseif($_GET['page'] === "login"){
include ("pages/login.php");
}
elseif($_GET['page'] === "home"){
include ("pages/home.php");
}
}elseif(!isset($_GET['page'])){
header("www.mywebsite.com?page=home");
}
?>
I consider that code a quick fix, but i know that there is a better way for me to do this, i need some advice.
Move the folder pages outside the document root and load them with:
include ("../pages/register.php");
just like you do with ../backend/connection.php.
That way, no one can access them directly from the outside through the web server, but will still be accessible in your PHP code. You also don't need to check if some constant is defined on all your pages.
This is also how most modern frameworks do it. They only have an index.php-file in the web root and all the other code outside (including views)
You can define constant, for example
define('APP_LOADED', true);
in included scripts check that constant is defined and exit if not
if (!defined('APP_LOADED')){
exit();
}
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');
}
?>
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.
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 want to make my homepage, without frames, should i just split up my design on index.php so it is header.php/footer.php, and then just include them on every page?
Yes, you can split your index.php into header.php/footer.php and then just include them on every page.
Note that your pages can be not static HTML but php scripts, to show multiple pages with one script.
I'd suggest also to have not a commonplace structure like
include 'header.php';
//do some stuff
include 'footer.php';
but another structure, much more useful:
//do some stuff, retrieve all data.
include 'header.php';
include 'page.php'; //include page template
include 'footer.php';
I suggest you use a framework. Most frameworks (if not all) have simple template systems, so you don't have to repeat code.
The problem with the suggested solution of including stuff in every page of your site is that you have to update all the pages of your site if you want to include another thing, say a sidebar.
A better idea is not to have a script--page connection at all. So you don't write a php file per page you want to show. Instead, use one front controller file, most use index.php in the root of the website. And then use Apache mod_rewrite or other server techniques to have flexibility in the URL's of your site. Then let index.php map different URL requests to serve different pages, you can then put all the pages of your site into a database or somewhere else.
This way there's only one point in your site that includes the templates for the header and footer, so that's easily changeable, and you can use the root of the site to serve AJAX requests, in which you won't want to output HTML but JSON for instance.
Afaik this is a good way of going about it.
Another idea would be to have just one single point of entry which is called with a GET parameter, e.g ?site=about. Your index.php could look like this:
<?php
// whitelist of allowed includes
$allowedIncludes = array('home', 'about', 'error404'); // etc.
// what to include if ?site is not set at all / set to an illegal include
$defaultInclude = 'home';
$errorInclude = 'error404';
// if site is not set, include default
$site = (empty($_GET['site'])) ? $defaultInclude : $_GET['site'];
// if site is illegal, include error page
$include = (in_array($site, $allowedIncludes)) ? $site : $errorInclude;
// actual includes
include 'header.php';
include $include.'.php';
include 'footer.php';
Thus you only have to include header.php and footer.php once and have full control about what is allowed and what is not (the included files could be in a directory that only php has access to). While your index.php handles the request, home.php, about.php do not have to know about header.php and footer.php (you could easily replace them at a later point in time).
If you do not like http://www.example.com/?site=about, you can look into mod_rewrite and friends.
You may want to set a session for that. A session variable exists as long as a visitor is on your website:
<?php
session_start(); // Remember that session_start(); must be the first line of your PHP and HTML-code
if($add_a_message){
$_SESSION['message'] = 'Message';
}
if($destroy_message){
$_SESSION['message'] = '';
}
// echo this message
if(isset($_SESSION['message']) && strlen($_SESSION['message']) > 0){
echo '<strong>' . $_SESSION['message'] . '</strong>';
}
?>