Search code examples
phpurlglobal-variablessuperglobalsphp-builtin-server

Pass entire URL to $_GET variable in PHP built-in server


I'm running a PHP built-in server with

php -S 127.0.0.1:80 index.php

I want to pass the entire URI string to a field called "url" in the $_GET array. When I enter http://localhost/thisIsAURLString, I want var_dump($_GET); to return array(1) { ["url"]=> string(16) "thisIsAURLString" } Is there some way to do this with the PHP built in server?

The web application is usually run in a production environment with nginx, and with a configuration file as shown below. This configuration passes the URL to a field "url" in the $_GET variable, but I want to do something similar with the PHP built-in server.

server {

    listen 5001 default_server;
    listen [::]:5001 default_server ipv6only=on;
    root [myRoot];
    index index.php index.html index.htm;
    server_name [myServerName];


    location /uploads {
                try_files $uri $uri/ =404;
        }

        location /assets {
                try_files $uri $uri/ =404;
        }
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        rewrite ^/(.*)$ /index.php?url=$1 last;
    }

    location ~ .php$ {

        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_pass unix:/var/run/php/php7.0-fpm-01.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        include /etc/nginx/fastcgi_params;
    }
}

EDIT (some context) :

The context is that I'm a TA with many students. The web application in question is currently in a production environment with nginx and runs smoothly, but all of my ~100 students need to download and deploy the very same web application locally on their own computers. I can't alter the PHP code. The deployment should be as simple and smooth as possible, and if they can do this with some easily reproducible php command, that would be ideal.


Solution

  • You could bootstrap your application with this script. Save this snippet to a file, and set it as your entry point in whatever web server software you're using. It will produce the results you're asking for.

    <?php
       $root=__dir__;
    
       $uri=parse_url($_SERVER['REQUEST_URI'])['path'];
       $page=trim($uri,'/');  
    
       if (file_exists("$root/$page") && is_file("$root/$page")) {
           return false; // serve the requested resource as-is.
           exit;
       }
    
       $_GET['url']=$page;
       require_once 'index.php';
    ?>