Jump to content

[SOLVED] filter out url


pagedrop

Recommended Posts

Hello, I have this below code, where a user enters a url and the file specified in the url is retrieved and saved on the server.

 

Now i want to display just the filename and its extension at the end. please let me know how to do it.

for example, i enter a url like http://www.google.com/google/test.html, after retrieving the file, i want to show just test.html

 

thanks

 

<?php

echo "script started\n";

echo "<br>";

echo $_GET['url'];

echo "<br>";

$inputfile = fopen($_GET['url'], "r");

$outputfile = fopen("file.pdf", "w");

echo "opened files\n";

echo "<br>";

$data = '';

while (!feof($inputfile)) {

  $data .= fread($inputfile, 8192);

}

echo "read data\n";

echo "<br>";

fwrite($outputfile, $data);

echo "transfered data\n";

echo "<br>";

fclose ($inputfile);

fclose ($outputfile);

echo "files closed\n";

echo "<br>";

echo "done";

echo "<br>";

 

?>

Link to comment
https://forums.phpfreaks.com/topic/153067-solved-filter-out-url/
Share on other sites

 

here are two good functions to extract the filename and extension part from any given path or url.

 

<?php
    function ShowFileExtension($filepath)
    {
        preg_match('/[^?]*/', $filepath, $matches);
        $string = $matches[0];
     
        $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);

        # check if there is any extension
        if(count($pattern) == 1)
        {
            echo 'No File Extension Present';
            exit;
        }
       
        if(count($pattern) > 1)
        {
            $filenamepart = $pattern[count($pattern)-1][0];
            preg_match('/[^?]*/', $filenamepart, $matches);
            echo $matches[0];
        }
    }
   
    function ShowFileName($filepath)
    {
        preg_match('/[^?]*/', $filepath, $matches);
        $string = $matches[0];
        #split the string by the literal dot in the filename
        $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
        #get the last dot position
        $lastdot = $pattern[count($pattern)-1][1];
        #now extract the filename using the basename function
        $filename = basename(substr($string, 0, $lastdot-1));
        #return the filename part
        return $filename;
    }
?>

 

usage

 

<?php
   //$string = 'C:\My Documents\My Name\filename.ext';
    //$string = 'http://php.net/manual/add-note.php?
&redirect=http://php.net/function.basename.php';
   
    echo ShowFileName($string);
    echo ShowFileExtension($string);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.