Search code examples
phpget

Get data from url in php


Is it possible to put this:

<?php echo $_GET['p']; ?>

Inside of this:

<?php include("vars.txt"); 
echo"".$title.""; ?>

Actually I want to get the filename? (example: vars.txt) from URL. Can anyone tell me how to do this?


Solution

  • If you have a $url

    $url = "http://example.com/file/vars.txt";

    and want to display on-screen text "Filename: vars.txt" then you can use the code below to do that

    $filename = basename($url);
    echo "Filename $filename";
    

    Edited Answer:

    What you are trying to do is potentially quite dangerous as anyone can select any file from your server to include in your page and get your website hacked, to make this a bit more secure you can do the following

    <?php
    $files = array(
       "vars" => "vars.txt",
       "vars2" => "vars2.txt",
       "some-other-file" => "vars3.txt"
    ); 
    
    if( $_GET['p'] && isset( $files[ $_GET['p'] ] ) {
        echo file_get_contents( $files[ $_GET['p'] ] );
    }
    ?>
    

    Then when you enter an URL like http://example.com/?p=vars then vars.txt content will be print on the screen.