Home > Enterprise >  Downloading file to server from url
Downloading file to server from url

Time:10-18

I have a laravel application where I download files to my server from given URLs. I am using the following code to do this.

$file_name = $files_directory . str_replace( " ", "-", $_POST['file_name'] ) . $_POST['file_extension'];

if ( file_put_contents( $file_name, fopen( $file_url, 'r' ) ) !== false ) {

   $success = true;
   $msg     = "File Downloaded Successfully";

}

I am using user input to create a filename and extension. Is there a way to get the filename and extension from the URL response? Or is there a better way to approach this problem?

CodePudding user response:

I think, you will have problems with the solution . Because you havn't put try/catch cases and you hasn't validated file extensions. And these can bring security issuses in future. You have to change your script like this:

$file_name = $files_directory . str_replace( " ", "-", $_POST['file_name'] ) . $_POST['file_extension'];
try {
    if(in_array(mb_strtolower($_POST['file_extension']), ['jpg','png','...permitted_extenions.....'])){
        if ( file_put_contents( $file_name, fopen( $file_url, 'r' ) ) !== false ) {

            $success = true;
            $msg     = "File Downloaded Successfully";

        }
    }else throw new Exception('Errors with extention');

}catch(\Exception $e){
 echo $e->getMessage();
}


CodePudding user response:

You can use the code in this repo to handle image uploads: https://github.com/prasanth-j/laravel_ajax_image_crud

  • Related