PHPackages                             romangorbatko/gump - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. romangorbatko/gump

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

romangorbatko/gump
==================

A fast, extensible &amp; stand-alone PHP input validation class that allows you to validate any data

1.3(10y ago)0249MITPHP

Since Jun 10Pushed 10y ago1 watchersCompare

[ Source](https://github.com/RomanGorbatko/GUMP)[ Packagist](https://packagist.org/packages/romangorbatko/gump)[ Docs](https://wixelhq.com/)[ RSS](/packages/romangorbatko-gump/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (4)Used By (0)

Getting started
===============

[](#getting-started)

GUMP is a standalone PHP data validation and filtering class that makes validating any data easy and painless without the reliance on a framework.

Follow along on the project board:

#### There are 2 ways to install GUMP

[](#there-are-2-ways-to-install-gump)

###### Install Manually

[](#install-manually)

1. Download GUMP
2. Unzip it and copy the directory into your PHP project directory.

Include it in your project:

```
require "gump.class.php";

$is_valid = GUMP::is_valid($_POST, array(
	'username' => 'required|alpha_numeric',
	'password' => 'required|max_len,100|min_len,6'
));

if($is_valid === true) {
	// continue
} else {
	print_r($is_valid);
}
```

###### Install with composer

[](#install-with-composer)

Add the following to your composer.json file:

```
{
    "require": {
        "wixel/gump": "dev-master"
    }
}
```

Then open your terminal in your project directory and run:

`composer install`

#### Available Methods

[](#available-methods)

```
// Shorthand validation
is_valid(array $data, array $rules)

// Get or set the validation rules
validation_rules(array $rules);

// Get or set the filtering rules
filter_rules(array $rules);

// Runs the filter and validation routines
run(array $data);

// Strips and encodes unwanted characters
xss_clean(array $data);

// Sanitizes data and converts strings to UTF-8 (if available),
// optionally according to the provided field whitelist
sanitize(array $input, $whitelist = NULL);

// Validates input data according to the provided ruleset (see example)
validate(array $input, array $ruleset);

// Filters input data according to the provided filterset (see example)
filter(array $input, array $filterset);

// Returns human readable error text in an array or string
get_readable_errors($convert_to_string = false);

// Fetch an array of validation errors indexed by the field names
get_errors_array();

// Override field names with readable ones for errors
set_field_name($field, $readable_name);
```

Example (Long format)
=====================

[](#example-long-format)

The following example is part of a registration form, the flow should be pretty standard

```
# Note that filters and validators are separate rule sets and method calls. There is a good reason for this.

require "gump.class.php";

$gump = new GUMP();

$_POST = $gump->sanitize($_POST); // You don't have to sanitize, but it's safest to do so.

$gump->validation_rules(array(
	'username'    => 'required|alpha_numeric|max_len,100|min_len,6',
	'password'    => 'required|max_len,100|min_len,6',
	'email'       => 'required|valid_email',
	'gender'      => 'required|exact_len,1|contains,m f',
	'credit_card' => 'required|valid_cc'
));

$gump->filter_rules(array(
	'username' => 'trim|sanitize_string',
	'password' => 'trim',
	'email'    => 'trim|sanitize_email',
	'gender'   => 'trim',
	'bio'	   => 'noise_words'
));

$validated_data = $gump->run($_POST);

if($validated_data === false) {
	echo $gump->get_readable_errors(true);
} else {
	print_r($validated_data); // validation successful
}
```

Example (Short format)
======================

[](#example-short-format)

The short format is an alternative way to run the validation.

```
$data = array(
	'street' => '6 Avondans Road'
);

$validated = GUMP::is_valid($data, array(
	'street' => 'required|street_address'
));

if($validated === true) {
	echo "Valid Street Address!";
} else {
	print_r($validated);
}
```

Match data-keys against rules-keys
----------------------------------

[](#match-data-keys-against-rules-keys)

We can check if there is a rule specified for every data-key, by adding an extra parameter to the run method.

```
$gump->run($_POST, true);

```

If it doesn't match the output will be:

```
There is no validation rule for $field

```

Return Values
-------------

[](#return-values)

`run()` returns one of two types:

*ARRAY* containing the successfully validated and filtered data when the validation is successful

*BOOLEAN* False when the validation has failed

`validate()` returns one of two types:

*ARRAY* containing key names and validator names when data does not pass the validation.

You can use this array along with your language helpers to determine what error message to show.

*BOOLEAN* value of TRUE if the validation was successful.

`filter()` returns the exact array structure that was parsed as the `$input` parameter, the only difference would be the filtered data.

Available Validators
--------------------

[](#available-validators)

- required `Ensures the specified key value exists and is not empty`
- valid\_email `Checks for a valid email address`
- max\_len,n `Checks key value length, makes sure it's not longer than the specified length. n = length parameter.`
- min\_len,n `Checks key value length, makes sure it's not shorter than the specified length. n = length parameter.`
- exact\_len,n `Ensures that the key value length precisely matches the specified length. n = length parameter.`
- alpha `Ensure only alpha characters are present in the key value (a-z, A-Z)`
- alpha\_numeric `Ensure only alpha-numeric characters are present in the key value (a-z, A-Z, 0-9)`
- alpha\_dash `Ensure only alpha-numeric characters + dashes and underscores are present in the key value (a-z, A-Z, 0-9, _-)`
- alpha\_space `Ensure only alpha-numeric characters + spaces are present in the key value (a-z, A-Z, 0-9, \s)`
- numeric `Ensure only numeric key values`
- integer `Ensure only integer key values`
- boolean `Checks for PHP accepted boolean values, returns TRUE for "1", "true", "on" and "yes"`
- float `Checks for float values`
- valid\_url `Check for valid URL or subdomain`
- url\_exists `Check to see if the url exists and is accessible`
- valid\_ip `Check for valid generic IP address`
- valid\_ipv4 `Check for valid IPv4 address`
- valid\_ipv6 `Check for valid IPv6 address`
- valid\_cc `Check for a valid credit card number (Uses the MOD10 Checksum Algorithm)`
- valid\_name `Check for a valid format human name`
- contains,n `Verify that a value is contained within the pre-defined value set`
- containsList,n `Verify that a value is contained within the pre-defined value set. The list of valid values must be provided in semicolon-separated list format (like so: value1;value2;value3;..;valuen). If a validation error occurs, the list of valid values is not revelead (this means, the error will just say the input is invalid, but it won't reveal the valid set to the user.`
- doesNotcontainList,n `Verify that a value is not contained within the pre-defined value set. Semicolon (;) separated, list not outputted. See the rule above for more info.`
- street\_address `Checks that the provided string is a likely street address. 1 number, 1 or more space, 1 or more letters`
- iban `Check for a valid IBAN`
- min\_numeric `Determine if the provided numeric value is higher or equal to a specific value`
- max\_numeric `Determine if the provided numeric value is lower or equal to a specific value`
- date `Determine if the provided input is a valid date (ISO 8601)`
- starts `Ensures the value starts with a certain character / set of character`
- phone\_number `Validate phone numbers that match the following examples: 555-555-5555 , 5555425555, 555 555 5555, 1(519) 555-4444, 1 (519) 555-4422, 1-555-555-5555`
- regex `You can pass a custom regex using the following format: 'regex,/your-regex/'`
- valid\_json\_string `validate string to check if it's a valid json format`

Available Filters
-----------------

[](#available-filters)

Filters can be any PHP function that returns a string. You don't need to create your own if a PHP function exists that does what you want the filter to do.

- sanitize\_string `Remove script tags and encode HTML entities, similar to GUMP::xss_clean();`
- urlencode `Encode url entities`
- htmlencode `Encode HTML entities`
- sanitize\_email `Remove illegal characters from email addresses`
- sanitize\_numbers `Remove any non-numeric characters`
- trim `Remove spaces from the beginning and end of strings`
- base64\_encode `Base64 encode the input`
- base64\_decode `Base64 decode the input`
- sha1 `Encrypt the input with the secure sha1 algorithm`
- md5 `MD5 encode the input`
- noise\_words `Remove noise words from string`
- json\_encode `Create a json representation of the input`
- json\_decode `Decode a json string`
- rmpunctuation `Remove all known punctuation characters from a string`
- basic\_tags `Remove all layout orientated HTML tags from text. Leaving only basic tags`
- whole\_number `Ensure that the provided numeric value is represented as a whole number`

Creating your own validators and filters
========================================

[](#creating-your-own-validators-and-filters)

Adding custom validators and filters is made easy by using callback functions.

```
require("gump.class.php");

/*
   Create a custom validation rule named "is_object".
   The callback receives 3 arguments:
   The field to validate, the values being validated, and any parameters used in the validation rule.
   It should return a boolean value indicating whether the value is valid.
*/
GUMP::add_validator("is_object", function($field, $input, $param = NULL) {
    return is_object($input[$field]);
});

/*
   Create a custom filter named "upper".
   The callback function receives two arguments:
   The value to filter, and any parameters used in the filter rule. It should returned the filtered value.
*/
GUMP::add_filter("upper", function($value, $params = NULL) {
    return strtoupper($value);
});
```

Alternately, you can simply create your own class that extends the GUMP class.

```
require("gump.class.php");

class MyClass extends GUMP
{
	public function filter_myfilter($value, $param = NULL)
	{
		...
	}

	public function validate_myvalidator($field, $input, $param = NULL)
	{
		...
	}

} // EOC

$validator = new MyClass();

$validated = $validator->validate($_POST, $rules);
```

Please see `examples/custom_validator.php` for further information.

Remember to create a public methods with the correct parameter types and parameter counts.

- For filter methods, prepend the method name with "filter\_".
- For validator methods, prepend the method name with "validate\_".

Set Custom Field Names
======================

[](#set-custom-field-names)

You can easily override your form field names for improved readability in errors using the `GUMP::set_field_name($field, $readable_name)` method as follows:

```
$data = array(
	'str' => null
);

$rules = array(
	'str' => 'required'
);

GUMP::set_field_name("str", "Street");

$validated = GUMP::is_valid($data, $rules);

if($validated === true) {
	echo "Valid Street Address\n";
} else {
	print_r($validated);
}
```

validating file fields
======================

[](#validating-file-fields)

```
require "gump.class.php";

$is_valid = GUMP::is_valid(array_merge($_POST,$_FILES), array(
	'title' => 'required|alpha_numeric',
	'image' => 'required_file|extension,png;jpg'
));

if($is_valid === true) {
	// continue
} else {
	print_r($is_valid);
}
```

Running the examples:
---------------------

[](#running-the-examples)

1. Open up your terminal
2. cd \[GUMP DIRECTORY/examples\]
3. php \[file\].php

The output will depend on the input data.

Contributors
============

[](#contributors)

- Colleen Emryss
- Mark Slingsby
- Rob Crowe
- Roy de Kleijn
- Christian Klisch
- Inge Brattaas
- Adam Curtis
- Sean Hickey
- Dennis Thompson

TODO
====

[](#todo)

- A currency validator
- A country validator
- Location co-ordinates validator
- HTML validator
- Language validation ... determine if a piece of text is a specified language
- Validate a spam domain or IP.
- Validate a spam email address
- Validate spam text with askimet or something similar
- Improve documentation
- More examples
- W3C validation filter?
- A filter that integrates with an HTML tidy service?:
- Add a twitter &amp; facebook profile url validator:
- Add more logical examples - log in form, profile update form, blog post form, etc etc.
- Add validators to allow checking the PHP $\_FILES array.
- Allow a validator that can check for existing files on the host machine
- Add an 'is empty' validator check
- Check that arrays have a positive count (if type is array)
- A secure password validator

###  Health Score

31

—

LowBetter than 71% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 76% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~211 days

Total

3

Last Release

3881d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5755452273c21661f98a093d9e3fcc6030ad760d27c5924ac5737875efcabb34?d=identicon)[RomanGorbatko](/maintainers/RomanGorbatko)

---

Top Contributors

[![sn](https://avatars.githubusercontent.com/u/77145?v=4)](https://github.com/sn "sn (139 commits)")[![roydekleijn](https://avatars.githubusercontent.com/u/1298389?v=4)](https://github.com/roydekleijn "roydekleijn (6 commits)")[![rwitchell](https://avatars.githubusercontent.com/u/5378642?v=4)](https://github.com/rwitchell "rwitchell (6 commits)")[![groucho75](https://avatars.githubusercontent.com/u/1230256?v=4)](https://github.com/groucho75 "groucho75 (5 commits)")[![pl4g4](https://avatars.githubusercontent.com/u/945246?v=4)](https://github.com/pl4g4 "pl4g4 (4 commits)")[![mazubieta](https://avatars.githubusercontent.com/u/45144667?v=4)](https://github.com/mazubieta "mazubieta (4 commits)")[![ib4](https://avatars.githubusercontent.com/u/4975243?v=4)](https://github.com/ib4 "ib4 (4 commits)")[![tylerjaynelson](https://avatars.githubusercontent.com/u/1901204?v=4)](https://github.com/tylerjaynelson "tylerjaynelson (2 commits)")[![rcrowe](https://avatars.githubusercontent.com/u/282571?v=4)](https://github.com/rcrowe "rcrowe (2 commits)")[![StephenNeate](https://avatars.githubusercontent.com/u/740283?v=4)](https://github.com/StephenNeate "StephenNeate (1 commits)")[![tty02-fl](https://avatars.githubusercontent.com/u/7905895?v=4)](https://github.com/tty02-fl "tty02-fl (1 commits)")[![Nyholm](https://avatars.githubusercontent.com/u/1275206?v=4)](https://github.com/Nyholm "Nyholm (1 commits)")[![Cameronjmayfield](https://avatars.githubusercontent.com/u/1444395?v=4)](https://github.com/Cameronjmayfield "Cameronjmayfield (1 commits)")[![flawwan](https://avatars.githubusercontent.com/u/5606231?v=4)](https://github.com/flawwan "flawwan (1 commits)")[![headzoo](https://avatars.githubusercontent.com/u/707209?v=4)](https://github.com/headzoo "headzoo (1 commits)")[![juanvillegas](https://avatars.githubusercontent.com/u/773149?v=4)](https://github.com/juanvillegas "juanvillegas (1 commits)")[![MayurVirkar](https://avatars.githubusercontent.com/u/4211478?v=4)](https://github.com/MayurVirkar "MayurVirkar (1 commits)")[![nicklozon](https://avatars.githubusercontent.com/u/487421?v=4)](https://github.com/nicklozon "nicklozon (1 commits)")[![adamlc](https://avatars.githubusercontent.com/u/809944?v=4)](https://github.com/adamlc "adamlc (1 commits)")[![ryanhalliday](https://avatars.githubusercontent.com/u/961043?v=4)](https://github.com/ryanhalliday "ryanhalliday (1 commits)")

### Embed Badge

![Health badge](/badges/romangorbatko-gump/health.svg)

```
[![Health](https://phpackages.com/badges/romangorbatko-gump/health.svg)](https://phpackages.com/packages/romangorbatko-gump)
```

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k882.5M1.0k](/packages/webmozart-assert)[composer/semver

Version comparison library that offers utilities, version constraint parsing and validation.

3.3k479.5M567](/packages/composer-semver)[respect/validation

The most awesome validation engine ever created for PHP

5.9k36.6M349](/packages/respect-validation)[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k34.5M83](/packages/propaganistas-laravel-phone)[laminas/laminas-escaper

Securely and safely escape HTML, HTML attributes, JavaScript, CSS, and URLs

21986.9M118](/packages/laminas-laminas-escaper)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.2M67](/packages/swaggest-json-schema)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
