Asked  7 Months ago    Answers:  5   Viewed   64 times

I need to get the path from the URL of the current request. For example, if the current URL is:

"http://www.example.com/example/test/hi.php?randomvariable=1"

I would want this:

"/example/test/hi.php?randomvariable=1"

 Answers

57

You want $_SERVER['REQUEST_URI']. From the docs:

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

Wednesday, March 31, 2021
 
Novalirium
answered 7 Months ago
73

Try this:

$str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$pos = strrpos($str, '/') + 1;
$result = substr($str, 0, $pos) . urlencode(substr($str, $pos));

You're looking for the last occurrence of the slash sign. The part before it is ok so just copy that. And urlencode the rest.

Wednesday, March 31, 2021
 
TheTechnicalPaladin
answered 7 Months ago
91

According to the PHP manual, you must specifically encode a URL if it contains special characters. This means the function itself should do no special encoding. Most likely your URL is being encoded before being passed to the function, so pass it through urldecode first and see what happens.

Edit: You're saying the encoding is being messed up. Again the PHP manual specifically states that you need to encode urls prior to passing them to file_get_contents. Try encoding the URL, then passing it to the function.

$url = urlencode($url);
file_get_contents($url);
Friday, May 28, 2021
 
rorymorris
answered 5 Months ago
99

file_get_contents() does not parse the content. You need to pass the value through json_decode().

<?php
    $params = json_decode(file_get_contents("php://input"), true);
    echo ($params["key_1"]);
?>
Saturday, May 29, 2021
 
JakeGR
answered 5 Months ago
45

With pure JavaScript:

console.log(window.location.href)

Using Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

Tuesday, July 27, 2021
 
weegee
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :