I'm able to retrieve the full URL like: http://www-click08-co-uk/wonga.php
and I need to retrieve the script name "wonga" from it.
The url will be changing depending on what page the user is on and I will always need the word or phrase after the / and not including the .php, in the example above I would like to create a variable with the value of this being wonga
This is the code I currently have, where "argos" is, is where the database is searched and responds with the information I need, this is where the vaiable would be used
<?php
//-----------------------------------------------------
// Include files and set Classes
//-----------------------------------------------------
require_once $_SERVER["DOCUMENT_ROOT"] . "/includes/common.php";
$db = new dbConnection();
$directorydata = new directorydata();
$phoneDirectory = new phoneDirectory();
$conn = $db->pdoConnect();
// Load the directorydata row via the row ID - 543 is "best buy"
//$directorydata->get($db, 543);
// Load the directorydata row via the url alias field
$directorydata->get($db, "Argos");
// Phone number isn't formatted coming out the DB
$formattedPhoneNumber = $phoneDirectory->formatPhoneNumber($directorydata->Number1);
?>
Just because you didn't provide any code, I provide you a way to solve this on your own:
$url = "http://www-click08-co-uk/wonga.php";
// SEARCH and replace
// FIRST_FUNCTION => google => php trailing name component of path
// SECOND_FUNCTION => google => php explode a string by string
// THIRD_FUNCTION => google => php pop first element of array
$urlParts = SECOND_FUNCTION( ".", FIRST_FUNCTION( $url ) );
echo THIRD_FUNCTION( $urlParts );
OUTPUT:
wonga
An example use of parse_url could be:
$url = 'http://www-click08-co-uk/wonga.php?page=74';
$route = parse_url($url, PHP_URL_PATH);
$routeTokens = explode('/', $route);
$scriptName = array_pop($routeTokens);
echo $scriptName;
which in this case outputs wonga.php.
Just note that this is a very rare task that you would have to take care of yourself. So instead of parse_url you might look at the bigger picture here and start looking for some good MVC framework.
Related
I'm trying to check against an array of URL's with PHP, but one of the URL's will have some random strings in front of it (generated sub domain).
This is what I have so far:
<?php
$urls = array(
'127.0.0.1',
'develop.domain.com'
);
?>
<?php if (in_array($_SERVER['SERVER_NAME'], $urls)) : ?>
//do the thing
<?php endif; ?>
The only thing is that the develop.domain.com will have something in front of it. For example namething.develop.domain.com.
Is there a way to check for a wildcard in the array of URL's so that it can check for the 127.0.0.1 and and matches for develop.domain.com?
Simplest way is to go all regex like this
// Array of allowed url patterns
$urls = array(
'/^127.0.0.1$/',
'/^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*(develop.domain.com)$/i'
);
// For each of the url patterns in $urls,
// try to match the $_SERVER['SERVER_NAME']
// against
foreach ($urls as $url) {
if (preg_match($url, $_SERVER['SERVER_NAME'])) {
// Match found. Do something
// Break from loop since $_SERVER['SERVER_NAME']
// a pattern
break;
}
}
Assuming that URL will use one word in sub-domain like you mentioned in your question.
If URL consists of more than one word then the following code needs to be modified as per expected word in sub-domain.
<?php
// Supported URLs array
$urls = array(
'127.0.0.1',
'develop.domain.com'
);
// Server name
//$_server_name = $_SERVER['SERVER_NAME'];
$_server_name = 'namething.develop.domain.com';
// Check if current server name contains more than 2 "." which means it has sub-subdomain
if(substr_count($_server_name, '.') > 2) {
// Fetch sub-string from current server name starting after first "." position till end and update it to current server name variable
$_server_name = substr($_server_name, strpos($_server_name, '.')+1, strlen($_server_name));
}
// Check if updated/filterd server name exists in our allowed URLs array
if (in_array($_server_name, $urls)){
// do something
echo $_server_name;
}
?>
Output:
PASS domain.develop.domain.com
PASS namething.develop.domain.com
FAIL subsubdomain.domain.develop.domain.com
FAIL namething1.namething2.develop.domain.com
I'm currently hardcoding an include into my pages and its a lot of work everytime I want to create a new page. Currently, my url is like this:
http://example.com/folder/one-z-pagename.php?var1=one&var2=two
and in one-z-pagename.php I have an include that looks like this:
include("lander-a-pagename.php");
So what I want to do is instead of hardcoding the file into the page like above, I want to grab one-z-pagename.php without the ?var1=one&var2=two from the url, erase the first 6 characters which is one-z- and replace it with lander-a-.
How do I do something like this?
use parse_url and basename to get filename then str_replace
$url= parse_url('http://example.com/folder/one-z-pagename.php?var1=one&var2=two');
$file = basename($url['path']);
$newfile = str_replace('one-z-','lander-a-',$file);
echo $newfile;
output : lander-a-pagename.php
It can be achive by many method, have a look on below two methods:
Method 1:
$current_script_name = basename(__FILE__);
$include_script_name = 'lander-a-'.substr($current_script_name, 6);
Method 2:
$current_script_name = $_SERVER['SCRIPT_NAME'];
$current_script_name = end(explode('/', $current_script_name));
$include_script_name = 'lander-a-'.substr($current_script_name, 6);
//OR
$include_script_name = str_replace('one-z', 'lander-a', $current_script_name);
variable $include_script_name contains required filename which you want to include.
Hope this will help.
i want to fetch youtube videos from the above script but the above code is getting keyword from GET parameter example.com/s=keyword and i want it to get from a example.com/HERE
i mean you can see there is a $_GET['s']
So this function works like this
example.com/s=keyword
and i want it to work like this
example/page/keyword
sorry for my bad english
$keyword = $_GET['s'];
file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&q=$keyword&type=video&key=abcdefg&maxResults=5");
Have a look at $_SERVER[REQUEST_URI]
This will return you the current url. Then process it using simple string or array functions to get the params, like
$current_url = $_SERVER['REQUEST_URI'];
$url_arr = explode("/", $current_url);
Then access the parameters using the array indexes
like $page = $url_arr[0];
Can anyone suggest a method in php or a function for parsingSEO friendly urls that doesn't involve htaccess or mod_rewrite? Examples would be awesome.
http://url.org/file.php/test/test2#3
This returns: Array ( scheme] => http [host] => url.org [path] => /file.php/test/test2 [fragment] => 3 ) /file.php/test/test2
How would I separate out the /file.php/test/test2 section? I guess test and test2 would be arguments.
EDIT:
#Martijn - I did figure out what your suggested before getting the notification about your answer. Thanks btw. Is this considered an ok method?
$url = 'http://url.org/file.php/arg1/arg2#3';
$test = parse_url($url);
echo "host: $test[host] <br>";
echo "path: $test[path] <br>";
echo "frag: $test[fragment] <br>";
$path = explode("/", trim($test[path]));
echo "1: $path[1] <br>";
echo "2: $path[2] <br>";
echo "3: $path[3] <br>";
echo "4: $path[4] <br>";
You can use explode to get the parts from your array:
$path = trim($array['path'], "/"); // trim the path of slashes
$path = explode("/", $path);
unset($path[0]); // the first one is the file, the others are sections of the url
If you really want to make it zerobased again, add this as last line:
$patch = array_values($path);
In response to your edit:
You want to make this as flexible as you can, so no fixed coding based on a max of 5 items. Although you probably will never exceed that, just don't pin yourself to it, just overhead you dont need.
If you have a pages system like this:
id parent name url
1 -1 Foo foo
2 1 Bar, child of Foo bar-child-of-foo
Make a recursive function. Pass the array to a function which takes the first section to find a root item
SELECT * FROM pages WHERE parent=-1 AND url=$path[0]
That query will return an id, use that in the parent column with the next value of the array. Unset each found value of the $path array. In the end, you will have an array with the remaining parts.
To sketch an example:
function GetFullPath(&$path, $parent=-1){
$path = "/"; // start with a slash
// Make the query for childs of this item
$result = mysqli_query($conn, "SELECT * FROM pages WHERE parent=".$parent." AND url=".current($path)." LIMIT 1");
// If any rows exists, append more of the url via recursiveness:
if($result->num_rows!==0){
// Remove the first part so if we go one deeper we start with the next value
$path = array_slice($patch,1); // remove first value
$fetch = $result->fetch_assoc();
// Use the fetched value to go deeper, find a child with the current item as parent
$path.= GetFullPath($path, $fetch['parent']);
}
// Return the result. if nothing is found at all, the result will be "/", probs home
return $path;
}
echo GetFullPath($path); // I pass it by reference, any alterations in the function happen to the variable outside the scope aswell
This is a draft, I did not test this, but you get the idea im trying to sketch. You can use the same method to get the ID of the page you are at. Just keep passing the variable back up again c
One of these days im getting the hang of recursiveness ^^.
Edit again: Oops, that turned out to be quite some code.
I'm stuck with some simple code.
I have created a database query that successfully makes '$albumPath' correctly point to the url 'albums/album0147'
How do I format the link to include another directory ie. 'albums/album0147/imageThumbs'
echo $albumPath;
displays albums/album0147 correctly on the page, but what do I put after $albumpath to correctly display albums/album0147/imageThumbs ?
I'm new to this, but learning rapidly through trial and error.
Since $albumPath is just a string, you can use the . operator to concatenate strings:
$albumPathImgs = $albumPath."/imageThumbs";
If "imageThumbs" is stored in another variable, say $thumbsDir:
$thumbsDir = "imageThumbs";
$albumPathImgs = $albumPath."/".$thumbsDir;
echo $albumsPathImgs;
You can define the slash independently so you can name your albums and files based on It's name only:
$slash = '/';
So you can define your main album:
$albums = 'albums';
Then you can define your sub albums:
$album0147 = 'album0147';
$imageThumbs = 'imageThumbs';
Now you can concatenate the albums together and make the url valid by adding the forwardslash in between (or a backward one, depending on your OS):
$url = $albums. $slash. $album0147. $slash. $imageThumbs;
You can even go so far as to define the image names:
$img1 = 'img101.png';
$image = $url. $img1;