$upload_dir = wp_get_upload_dir(); $is_valid_file = false === $upload_dir['error'] && self::file_is_in_directory( $path, $upload_dir['basedir'] ); } } if ( ! $is_valid_file ) { throw new \Exception( esc_html__( 'File path is not a valid upload path.', 'woocommerce' ) ); } } /** * Check if a given file is inside a given directory. * * @param string $file_path The full path of the file to check. * @param string $directory The path of the directory to check. * @return bool True if the file is inside the directory. */ private static function file_is_in_directory( string $file_path, string $directory ): bool { // Extract protocol if it exists. $protocol = ''; if ( preg_match( '#^([a-z0-9]+://)#i', $file_path, $matches ) ) { $protocol = $matches[1]; $file_path = preg_replace( '#^[a-z0-9]+://#i', '', $file_path ); } $file_path = (string) new URL( $file_path ); // This resolves '/../' sequences. $file_path = preg_replace( '/^file:\\/\\//', $protocol, $file_path ); $file_path = preg_replace( '/^file:\\/\\//', '', $file_path ); return 0 === stripos( wp_normalize_path( $file_path ), trailingslashit( wp_normalize_path( $directory ) ) ); } }