pagedrop Posted April 7, 2009 Share Posted April 7, 2009 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>"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/153067-solved-filter-out-url/ Share on other sites More sharing options...
MadTechie Posted April 7, 2009 Share Posted April 7, 2009 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/153067-solved-filter-out-url/#findComment-803959 Share on other sites More sharing options...
pagedrop Posted April 8, 2009 Author Share Posted April 8, 2009 thank you for your help Quote Link to comment https://forums.phpfreaks.com/topic/153067-solved-filter-out-url/#findComment-804220 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.