$post Unslashed $_POST. * @param int $depth Current depth. * @return array */ public static function post( array $post, int $depth = 0 ): array { $clean = array(); foreach ( $post as $key => $value ) { $key = self::key( (string) $key ); if ( '' === $key ) { continue; } if ( is_array( $value ) ) { if ( $depth < self::DEPTH ) { $clean[ $key ] = self::post( $value, $depth + 1 ); } continue; } if ( is_scalar( $value ) ) { $clean[ $key ] = sanitize_textarea_field( (string) $value ); } } return $clean; } /** * Sanitised uploads, by field name: file name, type, size, error code and the temporary * file, which must be a real upload of this request. Anything else is dropped. * * @param array $files $_FILES. * @return array */ public static function files( array $files ): array { $clean = array(); foreach ( $files as $key => $file ) { $key = self::key( (string) $key ); if ( '' === $key || ! is_array( $file ) || ! is_scalar( $file['tmp_name'] ?? null ) ) { continue; } $tmp = (string) $file['tmp_name']; if ( '' !== $tmp && ! is_uploaded_file( $tmp ) ) { continue; } $clean[ $key ] = array( 'name' => sanitize_file_name( is_scalar( $file['name'] ?? null ) ? (string) $file['name'] : '' ), 'type' => sanitize_mime_type( is_scalar( $file['type'] ?? null ) ? (string) $file['type'] : '' ), 'tmp_name' => $tmp, 'error' => absint( $file['error'] ?? UPLOAD_ERR_NO_FILE ), 'size' => absint( $file['size'] ?? 0 ), ); } return $clean; } /** * A field name: letters, digits, underscore and dash. * * @param string $key Raw key. */ private static function key( string $key ): string { return substr( (string) preg_replace( '/[^A-Za-z0-9_-]/', '', $key ), 0, 100 ); } }