PHP Get URL with Parameter - php

I want to get a URL and its parameters. Example:
www.someweb.com/somepage.php?id=10
How to get only somepage.php?id=10?
I'm already tried REQUEST_URI and PHP_SELF but it only gives me www.someweb.com/somepage.php or somepage.php. What I want to is just the page name and its parameter(s).

basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10).

for complette URL with protocol, servername and parameters:
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];

$_SERVER['PHP_SELF'] for the page name and $_GET['id'] for a specific parameter.
try print_r($_GET); to print out all the parameters.
for your request echo $_SERVER['PHP_SELF']."?id=".$_GET['id'];
return all the parameters echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];

function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
echo "The current page is ".curPageName()."?".$_SERVER['QUERY_STRING'];
This will get you page name , it will get the string after the last slash

Here's probably what you are looking for: php-get-url-query-string. You can combine it with other suggested $_SERVER parameters.

Here's a very thorough function I use to get the full URL:
function get_full_url( bool $include_query = true ) {
$protocol = ( ! empty( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) !== 'off' )
|| ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && strtolower( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) === 'https' )
|| ( ! empty( $_SERVER['HTTP_FRONT_END_HTTPS'] ) && strtolower( $_SERVER['HTTP_FRONT_END_HTTPS'] ) !== 'off' )
|| ( isset( $_SERVER['SERVER_PORT'] ) && intval( $_SERVER['SERVER_PORT'] ) === 443 ) ? 'https' : 'http';
$uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return $include_query ? $uri : str_replace( '?' . $_SERVER['QUERY_STRING'], '', $uri );
}

Related

Redirect to current URL, but replace string?

So I have a working redirect that currently sends customers to my homepage if they select a different city from a drop-down select. This changes some custom user meta data and uses that to determine when a redirect should occur. Simple enough.
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com');
}
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: example.com/chicago/');
}
What I would like to achieve is, if the customer is on the shop page, the I can redirect them to the CURRENT page they are on (not the homepage), but simply replace the city name with strpos or something similar... basically call the current URL and only replace the name of the city, regardless of where in the URL that string is.
Something like:
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com');
}
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: GET CURRENT URL & REPLACE CURRENT CITY (using a list of cities) OR ADD 'CHICAGO' AFTER DOMAIN IF ONE DOESN'T EXIST ');
}
Any advice?
Something like this should work (remove type declarations if using < PHP 7+):
function get_current_url( array $cities, string $target_city ): string {
// Get protocol.
$url = ( $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://' );
// Get URL parts.
$port = $_SERVER['SERVER_PORT'];
$name = $_SERVER['SERVER_NAME'];
$uri = $_SERVER['REQUEST_URI'];
// Check all cities in the array and replace if found.
foreach ( $cities as $city ) {
$uri = str_replace( $city, $target_city, $uri );
}
// Build URL with matching port.
$url .= ( $port !== '80' ? $name . ':' . $port . $uri : $name . $uri );
// Return escaped URL.
return esc_url( $url );
}
And then in your code:
if ( is_user_logged_in() && $metalocation_display !== 'chicago' && strpos($url,'chicago') == true) {
header('Location: example.com');
}
// Fill array with possible cities.
$cities = array( 'london', 'new-york', );
if ( is_user_logged_in() && $metalocation_display == 'chicago' && strpos($url,'chicago') == false) {
header('Location: ' . get_current_url( $cities, 'chicago' ) );
}
Obviously be sure to prefix the function though.

Cannot find where a redirect is specified

I've recently become the maintainer of a Wordpress site (I'm completely new to wordpress) and I'm having some difficulty determining where a redirect is specified.
I've checked the .htaccess file, and there's nothing specified in there. As far as I can tell, the rewrite rules aren't the cause.
I've tried deleting the page being redirected from and re-creating it, and the redirect still occurs.
My question is: where can you specify a redirect? I've run out of ideas of where to look.
one of my client want to custom url like
https://www.qsleap.com/gmat/resources as you know in wordpress evry request is catch by index.php . request filter catches the request and
call the page .
Read this code it may give you any idea.
function permalinks_customizer_request_before($query ){
$uri=$_SERVER['REQUEST_URI'];
$match= preg_match('/(gmat|gre|sat|lsat|cat)(\/resources\/tags\/)
(.*)\/(articles|videos|concept-notes|qna)/', $uri,$matches);
//$match=
preg_match('/(gmat|gre|sat|lsat|cat)/\resources/\tags/stanford-
gsb/\articles|videos|concept-notes)/?$', $uri,$matches);
if($match){
$url = parse_url( get_bloginfo( 'url' ) );
$url = isset( $url['path']) ? $url['path'] : '';
$request = ltrim( substr( $_SERVER['REQUEST_URI'], strlen( $url ) ), '/' );
$request = ( ( $pos = strpos( $request, '?' ) ) ? substr( $request, 0, $pos ) : $request );
if ( ! $request )
return $query;
$original_url="?page_name=tags&exam=".$matches[1]."&post_tag=".$matches[3]."&post_type=".$matches[4];
if ( $original_url !== null ) {
$original_url = str_replace('//', '/', $original_url);
if ( ( $pos = strpos( $_SERVER['REQUEST_URI'], '?' ) ) !== false ) {
$queryVars = substr( $_SERVER['REQUEST_URI'], $pos + 1 );
$original_url .= ( strpos( $original_url, '?' ) === false ? '?' : '&') . $queryVars;
}
$oldRequestUri = $_SERVER['REQUEST_URI'];
$oldQueryString = $_SERVER['QUERY_STRING'];
$_SERVER['REQUEST_URI'] = '/' . ltrim( $original_url, '/' );
$_SERVER['QUERY_STRING'] = ( ( $pos = strpos( $original_url, '?' ) ) !== false ? substr( $original_url, $pos + 1 ) : '' );
parse_str( $_SERVER['QUERY_STRING'], $queryArray );
$oldValues = array();
global $wp;
$wp->parse_request();
$query = $wp->query_vars;
if ( is_array( $queryArray ) ) {
foreach ( $queryArray as $key => $value ) {
$oldValues[$key] = $_REQUEST[$key];
$_REQUEST[$key] = $_GET[$key] = $value;
$query[$key]=$value;
}
}
$_SERVER['REQUEST_URI'] ='';
$_SERVER['QUERY_STRING']='';
}
}
return $query;
}
add_filter( 'request','permalinks_customizer_request_before',0);
function wp_url_rewrite_templates() {
if (get_query_var( 'page_name' ) && get_query_var( 'page_name'
)=='tags') {
add_filter( 'template_include', function() {
$template= dirname( __FILE__ ) . '/page-tags.php';
return $template;
});
}
}
add_action( 'template_redirect', 'wp_url_rewrite_templates' ,4 );
I think the easiest way for you to remove the redirects will be with this plugin.
https://redirection.me/
After you install it and activate it. From the Wordpress Admin
Tools > Redirection
You'll see a list of redirects, and add/remove any.

GET URL from pages that access my Image

Imagine any webpage ex: example1.com/something... using this html:
<img src="http://www.example2.com/controller/showImage" >
My controller in web2.com is something like:
function showImage() {
getIP(); //return USER IP (working)
getURL(); //return example1.com/something... (not working it returns always 'http://www.example2.com/controller/showImage')
addMetricsSQL($ip, $url); //add ip and url in database (working)
header('Content-Type: image/jpeg'); //headers
readfile($this->$path_img); //a path
}
My current function is:
public function getURL() {
$ssl = ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' );
$sp = strtolower( $_SERVER['SERVER_PROTOCOL'] );
$protocol = substr( $sp, 0, strpos( $sp, '/' ) ) . ( ( $ssl ) ? 's' : '' );
$port = $_SERVER['SERVER_PORT'];
$port = ( ( ! $ssl && $port=='80' ) || ( $ssl && $port=='443' ) ) ? '' : ':'.$port;
$host = ( false && isset( $_SERVER['HTTP_X_FORWARDED_HOST'] ) ) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : ( isset( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : null );
$host = isset( $host ) ? $host : $_SERVER['SERVER_NAME'] . $port;
return $protocol . '://' . $host . $_SERVER['REQUEST_URI'];
}
But like I said, it only returns example2.com/controller/showImage
My questions:
Is posible to get the right URL(in this case
example1.com/something...) using PHP?
How the getURL() function should be?
Thanks in advance
It was painfull but the answer to my question is:
public function getURL() {
return getenv('HTTP_REFERER', true) ?: getenv('HTTP_REFERER');
}
HTTP_REFERER Makes all the magic.

php for full url yoast

I am new to php.
I am using Wordpress and yoast.
However, the yoast plugin is not writing the canonical correctly. I wish to write the canonical so that it uses the syntax
<link rel="canonical" href="https://www.travelideology.com/about/">
However, it is writing
<link rel="canonical" href="https:/about/">
Would be happy if someone can let me know what is wrong with my code.
The code is as follows:
function my_wpseo_canonical( $canonical ) {
global $post;
$attachment = get_post( $post->ID );
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$cleansed = $protocol . "://" . $_SERVER['HTTP_HOST'];
$cleansed2 = get_permalink($attachment);
$canonical = $cleansed . $cleansed2;
return $canonical;
}
add_filter( 'wpseo_canonical', 'my_wpseo_canonical' );
try
function my_wpseo_canonical( $canonical ) {
global $post;
$attachment = get_post( $post->ID );
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$cleansed = $protocol . "://" .site_url(). $_SERVER['HTTP_HOST'];
$cleansed2 = get_permalink($attachment);
$canonical = $cleansed . $cleansed2;
return $canonical;
}

Protect under-developpement Website / Custom URL per user and store IP

I want to protect a page under developpement. The problem is that people are sharing that link. I'd like to manually give a custom link to the users, store the IP they use and then prevent the link being reused on a different IP. I'm using wordpress, and It's the entire site i'd like to protect. Also, is there a way to track who shared the URL?
Exemple :
I'd give a friend this http://exemple.com/abc, that link works as long as the user is on the IP that was first used. If that user shares that link to someone else or another IP tries to access the site using the URL I'd like to log it somehow.
I'll give you some basic advises, since this is relatively complicated and I don't have the time to write all of the code :) .
First you need to add a plain admin page - on this page initially you want to have a <form> with a text field and a submit field. The text field will be where you enter the page URL that you want to share.
You will also have an option stored in the database(we will create that later). It should be an array, to which you will later add the URL's.
Once you submit the URL you will create a nonce for this URL - it must be unique for it(you can use uniqid() for instance). You will then store the URL in an array like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$urls = get_option( 'my_custom_links', array() );
$id = uniqid();
$urls[ $id ] = array(
'url' => $_POST['my_url'],
'ip' => '',
);
// Update the links.
update_option( 'my_custom_links', $urls );
}
$urls = get_option( 'my_custom_links', array() );
// Display the form here...
// Display the URL's data
foreach ($urls as $id => $data) {
echo '<p>URL: <strong>' . $data['url'] . '</strong><br />Share URL: <strong>' . add_query_arg( 'n', $id, home_url( '/' ) ) . '</strong>' . ( $data['ip'] ? '<br />Accessed from IP: <strong>' . $data['ip'] . '</strong>' : '' ) . '</p>';
}
Then you just need to add a function that will check if a user is allowed to view a specific URL, like so(add the code to your functions.php):
function my_site_protection() {
global $pagenow;
// If we're not on admin or login page and the user is not logged-in
if ( ! is_admin() && 'wp-login.php' != $pagenow ) {
$login_redirect = true;
if ( isset( $_GET['n'] ) && $_GET['n'] ) {
$n = $_GET['n'];
$urls = get_option( 'my_custom_links', array() );
$data = isset( $urls[ $n ] ) ? $urls[ $n ] : false;
if ( $data ) {
if ( ! $data['ip'] || $data['ip'] == $_SERVER['REMOTE_ADDR'] ) {
// If no IP is set, set it and update the option
if ( ! $data['ip'] ) {
$urls[ $id ]['ip'] = $_SERVER['REMOTE_ADDR'];
update_option( 'my_custom_links', $urls );
}
if ( add_query_arg( 'n', $id, $data['url'] ) == curPageURL() ) {
// Don't redirect if we're on the correct page
$login_redirect = false;
} else {
// Redirect the user to the proper URL
wp_redirect( add_query_arg( 'n', $id, $data['url'] ) );
exit;
}
}
}
}
// Redirect user to log-in screen
$login_redirect && auth_redirect();
}
}
add_action('init', 'my_site_protection', 1);
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}
You'll have to figure-out the rest on your own, but I gave you most of the stuff, so if you look around a bit, you'll be able to accomplish that.
PP: I haven't tested the code, but in theory it should work - tell me if some part of it doesn't work.

Categories