Getting the second part of a URL through PHP - php

I'm trying to setup a page that pulls just a part of the URL but I can't even get it to echo on my page.
Since I code in PHP, I prefer dynamic pages, so my urls usually have "index.php?page=whatever"
I need the "whatever" part only.
Can someone help me. This is what I have so far, but like I said, I can't even get it to echo.
$suburl = substr($_SERVER["HTTP_HOST"],strrpos($_SERVER["REQUEST_URI"],"/")+1);
and to echo it, I have this, of course:
echo "$suburl";

If you need to get the value of the page parameter, simply use the $_GET global variable to access the value.
$page = $_GET['page']; // output => whatever

your url is index.php?page=whatever and you want to get the whatever from it
if the part is after ? ( abc.com/xyz.php?......) , you can use $_GET['name']
for your url index.php?page=whatever
use :
$parameter= $_GET['page']; //( value of $parameter will be whatever )
for your url index.php?page=whatever&no=28
use :
$parameter1= $_GET['page']; //( value of $parameter1 will be whatever )
$parameter2= $_GET['no']; //( value of $parameter2 will be 28 )
please before using the parameters received by $_GET , please sanitize it, or you may find trouble of malicious script /code injection
for url : index.php?page=whatever&no=28
like :
if(preg_match("/^[0-9]*$/", $_GET['no'])) {
$parameter2= $_GET['no'];
}
it will check, if GET parameter no is a digit (contains 0 to 9 numbers only), then only save it in $parameter2 variable.
this is just an example, do your checking and validation as per your requirement.

You can use basic PHP function parse_url for example:
<?php
$url = 'http://site.my/index.php?page=whatever';
$query = parse_url($url, PHP_URL_QUERY);
var_dump(explode('=', $query));
Working code example here: PHPize.online

Related

$GET query to directory?

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];

Preserving $_POST variables when paginating

I have a simple list of orders which a user can filter by status (open,dispatched,closed). The filter dropdown triggers a post to the server and sends the filter value through. Orders are listed out 10 to a page with pagination links for any results greater than 10. Problem is when I click the pagination links to view the next page of results the filter value in the post is lost.
public function filter_orders() {
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$filter = $this->input->post('order_status_filter');
$config = array();
$config["base_url"] = base_url() . "control/orders/filter_orders";
$config["per_page"] = 10;
$config['next_link'] = 'Next';
$config["uri_segment"] = 4;
$config['total_rows'] = $this->model_order->get_all_orders_count($this->input->post('order_status_filter'));
}
How can I make the pagination and filter work together. I've thought about injecting a query string in to the pagination links but it doesn't seem like a great solution.
The answer is very simple, use $_GET. You can also use URI segments.
i.e, index.php/cars/list/5/name-asc/price-desc'
The main reason you'll want to use $_GET is so you can link other users so they see the same result set you see. I'm sure users of your web app will want this functionality if you can imagine them linking stuff to each other.
That said, it would be ok to ALSO store the filters in the session so that if the user navigates away from the result set and then goes back, everything isn't reset.
Your best bet is to start a session and store the POST data in the session. In places in your code where you check to see if the user has sent POST data, you can check for session data (if POST is empty).
In other words, check for POST data (as you already do). If you got POST data, store it in the session. If a page has no POST data, check to see if you have session data. If you do, proceed as if it was POSTed. If you have both, overwrite the session with POST. You'll want to use new data your user sent you to overwrite older data they previously sent.
You either put everything in $_GET or if the data is sensible, put it in $_SESSION. Then it travels between pages.
In your case there seem to be no reason to put your filter data anywhere else than in $_GET.
A query string does seem the best solution. You could store it in the session or in cookies as well, but it makes sense to also store it in the query string.
Store it in cookies or the session if you want to remember the user's choice. Which seems like a friendly solution. It allows the user to keep their settings for a next visit, or for another page.
Store it in the query string, because going to 'page 2' doesn't tell you anything if you don't know about filters, page size or sorting. So if a user wants to bookmark page 2 or send it by e-mail, let them be able to send a complete link that contains this meta information.
Long story short: Store it in both.
maybe its not a right answer but, give it a try
<?php
// example url
$url = "index.php?page=6&filter1=value1&filter2=value2";
// to get the current url
//$url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
// change the page to 3 without changing any other values
echo url_change_index( $url, "page", 3 );
// will output "index.php?page=3&filter1=value1&filter2=value2"
// remove page index from url
echo url_change_index( $url, "page" );
// will output "index.php?filter1=value1&filter2=value2"
// the function
function url_change_index( $url, $name = null, $value = null ) {
$query = parse_url( $url, PHP_URL_QUERY );
$filter = str_replace( $query, "", $url );
parse_str( $query, $parsed );
$parsed = ( !isset( $parsed ) || !is_array( $parsed ) ) ? array() : $parsed;
if ( empty( $value ) ) {
unset( $parsed[$name] );
}
else {
$parsed[$name] = $value;
}
return $filter.http_build_query( $parsed );
}
?>

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Remove specific parameter from URL while preserving other parameters

I want remove a parameter from a URL:
$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';
I am trying to get this result:
https://stackoverflow.com/?name=alaa&
https://stackoverflow.com/?&star=5
I am trying to do it using preg_replace, but I've no idea how it can be done.
$link = preg_replace('~(\?|&)counter=[^&]*~','$1',$link);
Relying on regular expressions can screw things up sometimes..
You should use, the parse_url() function which breaks up the entire URL and presents it to you as an associative array.
Once you have that array, you can edit it as you wish and remove parameters.
Once, completed, use the http_build_url() function to rebuild the URL with the changes made.
Check the docs here..
Parse_Url Http_build_query()
EDIT
Whoops, forgot to mention. After you get the parameter string, youll obviously need to separate the parameters as individual ones. For this you can supply the string as input to the parse_str() function.
You can even use explode() with & as the delimeter to get this done.
I would recommend using a combination of parse_url() and http_build_query().
Handle it correctly! !
remove_query('http://example.com/?a=valueWith**&**inside&b=value');
Code:
function remove_query($url, $which_argument=false){
return preg_replace( '/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);
}
A code example how I would grab a requested URL and remove a parameter called "name", then reload the page:
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //complete url
$parts = parse_url($url);
parse_str($parts['query'], $query); //grab the query part
unset($query['name']); //remove a parameter from query
$dest_query = http_build_query($query); //rebuild new query
$dest_url=(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http").'://'.$parts['path'].'?'.$dest_query; //add query to host
header("Location: ".$dest_url); //reload page
parse_url() and parse_str() are buggy. Regular expressions can work but have the tendency to break. If you want to correctly deconstruct, make changes, and then reconstruct a URL, you should look at:
http://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
ExtractURL() generates parse_url()-like output but does much more (and does it right). CondenseURL() takes an array from ExtractURL() and constructs a new URL from the information. Both functions are in the 'support/http.php' file.
Years later...
$_GET can be manipulated like any other array in PHP. Simply unset the key and create the http query using the http_build_query function.
// Populate _GET with sample data...
$_GET = array(
'value_a' => "A",
'key_to_remove' => "Don't delete me bro!",
'value_b' => "B"
);
// Should output everything...
// "value_a=A&key_to_remove=Don%27t+delete+me+bro%21&value_b=B"
echo "\n".http_build_query( $_GET );
// Remove the key from _GET...
unset( $_GET[ 'key_to_remove' ] );
// Should output everything else...
// "value_a=A&value_b=B"
echo "\n".http_build_query( $_GET );
This is working for me:
function removeParameterFromUrl($url, $key)
{
$parsed = parse_url($url);
$path = $parsed['path'];
unset($_GET[$key]);
if(!empty(http_build_query($_GET))){
return $path .'?'. http_build_query($_GET);
} else return $path;
}

Get Argument And Print It

I want to do a print on a argument that is on the URL, like this(in this case it's Google):
http://bitoffapp.org/?http://google.com/
I want to get that and print it like this:
print("Go <a href='$url'>back</a> to the page you was before the login);
How can I do this?
$div = explode("?", $_SERVER['REQUEST_URI'], 2);
$arg = end($div);
//like Sarfraz says, you can also use directly $_SERVER['QUERY_STRING']
echo sprintf(
'Go back to the page...',
htmlspecialchars(urldecode($arg), ENT_QUOTES));
In practice, you'll want to validate the URL to see
If it's indeed a valid URL (see FILTER_VALIDATE_URL)
If you can find your site prefix there (checking for substr($url, 0, strlen($prefix)) === $prefix) is enough; $url is the urldecoded query string)
The reason for these checks is that otherwise attackers may trick your users into visiting URLs that, although prefixed with your domain, actually forward them to malicious websites or vulnerable registered protocols in the victim's browser.
If it has to be from the url, you should have it urlencoded and as a GET variable.
$prevUrl = urlencode("http://google.com/");
http://bitoffapp.org/?url=$prevUrl;
Then just read that into your php function from the GET global
$url = urldecode($_GET['url']);
print("Go <a href='$url'>back</a> to the page you was before the login");
However, I'd actually look at grabbing their previous url from the _SERVER global. _SERVER Global.
Do:
var_export($_REQUEST);
Get:
array ( 'http://www_google_com' => '', )
For a proper reference, use ?url=http://google.com/
Then you can find it in these::
$_REQUEST['url']; // All POST, GET, ... variables
$_GET['url'];
If your URL is http://bitoffapp.org/script.php?url={my_url} you could do this :
echo 'Go back to the page you were on before login';
parse_url($url,PHP_URL_QUERY);

Categories