PHP code example of yohgaki / validate-php-scr

1. Go to this page and download the library: Download yohgaki/validate-php-scr library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yohgaki / validate-php-scr example snippets



fine basic type specifications array $B. You can define any validation rule as you like.
qdn']);
// Validate record ID
$id = '1234';
$id = validate($ctx, $id, $basicTypes['uint32']);
// Check results
var_dump($domain, $id);


re_once __DIR__.'/../lib/basic_types.php'; // Defines basic type array $B

$func_opts = VALIDATE_OPT_DISABLE_EXCEPTION;
// Validate domain name w/o exception
$domain = 'es-i.jp';
$domain = validate($ctx, $domain, $basicTypes['fqdn'], $func_opts);
// Validate record ID
$id = '1234';
$id = validate($ctx, $id, $basicTypes['uint32'], $func_opts);

if (validate_get_status($ctx) == false) {
    // Check last validation error
}
// Get all user error
$errors = validate_get_user_errors($ctx);

//Check results
var_dump($domain, $id, $errors);


// Simple "username" and "email" form validation example.
// "Validate" is suitable for "From Validations" also.
nputs specifications at central repository.
// If your web app does not have strict client side validations, you will need
// "Input validation spec" AND "Business logic(Form) validation spec".

// If client JavaScript has validation
$username = [
    VALIDATE_STRING,        // "username" is string
    VALIDATE_STRING_ALNUM,  // "username" has only alphanumeric chars.
    ['min'=> 6, 'max'=> 40, // "username" can be 6 to 40 chars.
    'error_message'=>'Username is 6 to 40 chars. Alphanumeric char only.']
];

// "Validate" can be extend by callbacks.
$email = [
    VALIDATE_CALLBACK, // "email" is complex, so write PHP script for it.
    VALIDATE_CALLBACK_ALNUM, // Allow alpha numeric chars.
    ['min'=> 6, 'max'=> 256, 'ascii'=>'@._-', // Allow 6 to 256 chars and additional '@._-'
    'error_message'=>'Please enter valid email address. We only accepts address with DNS MX record.',
    'callback'=> function($ctx, &$result, $input) {     // Let's define rules by PHP function.
        $parts = explode('@', $input);
        if (count($parts) > 2) {         // Chars/min/max is already validated.
            $err =  "Only one '@' is allowed."; // This could be i18n function for multilingual sites.
            validate_error($ctx, $err);
            return false;
        }
        if (!dns_get_mx($parts[1], $mx)) {
            $err = "Sorry, we only allow hosts with MX record.";
            validate_error($ctx, $err);
            return false;
        }
        return true;
    }]
];

$spec = [ // Combine predefined parameter spec into one spec.
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min'=>2, 'max'=>10], // Inputs must have 2 to 10 elements.
    [
        // Simply reuse predefined spec for parameters.
        "username" => $username,
        "email"    => $email,
        // You can validate $_GET/$_POST/$_COOKIE/$_SERVER/$_FILES at once by nesting.
    ]
];

$inputs = [
    'username' => 'yohgaki',
    'email' => '[email protected]'
];

$func_opts = VALIDATE_OPT_DISABLE_EXCEPTION; // Disable exception, to check errors, etc.
$results = validate($ctx, $inputs, $spec, $func_opts); // Now, let's validate and done.

// Check results
var_dump(validate_get_status($ctx));        // $results is NULL when error. validate_get_status() can be used also.
var_dump($results, $inputs);                // $inputs contains unvalidated values.
var_dump(validate_get_user_errors($ctx));   // Get user errors.
var_dump(validate_get_system_errors($ctx)); // Get system errors.


re_once __DIR__.'/../lib/basic_types.php'; // Defines $B (basic type) array

$request_headers_orig = ['a'=>'abc', 'b'=>'456']; //apache_request_headers(); // Get request headers

// Check cookie and user agent. Allow undefined and extra headers.
$basicTypes['cookie'][VALIDATE_FLAGS]                 |= VALIDATE_FLAG_UNDEFINED; // Allow undefined(optional)
$basicTypes['user-agent'][VALIDATE_FLAGS]             |= VALIDATE_FLAG_UNDEFINED_TO_DEFAULT; // Allow undefined and set default
$basicTypes['user-agent'][VALIDATE_OPTIONS]['default'] = '';
$basicTypes['user-agent'][VALIDATE_OPTIONS]['min']     = 0; // Allow 0 length(empty)
$spec1 = [ // Explicit validations
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min'=>2, 'max'=>20], // Inputs must have 2 to 20 elements.
    [
        'Cookie' => $basicTypes['cookie'],
        'User-Agent' => $basicTypes['user-agent'],
    ]
];

// validate() removes validated values from $request_headers_orig
$request_headers = validate($ctx, $request_headers_orig, $spec1);

// Check the rest of headers.
// Allow array 'header512' strings and ALNUM + '_' + '-' keys
$basicTypes['header512'][VALIDATE_FLAGS]   |= VALIDATE_FLAG_ARRAY | VALIDATE_FLAG_ARRAY_KEY_ALNUM;
$basicTypes['header512'][VALIDATE_OPTIONS]['min'] = 0; // Allow 0 length(empty) headers
$basicTypes['header512'][VALIDATE_OPTIONS]['amin'] = 0; // Allow 0 extra headers
$basicTypes['header512'][VALIDATE_OPTIONS]['amax'] = 20; // Allow 20 extra headers
$spec2 = $basicTypes['header512'];

// $request_headers has only validated values. No control chars nor multibyte chars.
$request_headers += validate($ctx, $request_headers_orig, $spec2);
// Check results
var_dump($request_headers, $request_headers_orig);


re_once __DIR__.'/../lib/basic_types.php'; // Defines $basicTypes

// ---- Per-source specs -------------------------------------------------------

// $_GET: only a CSRF token is expected (64-char lowercase hex, SHA-256).
$getSpec = [
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min' => 1, 'max' => 1], // exactly 1 element
    [
        'csrf' => $basicTypes['hex64'],
    ]
];

// $_POST: a registration form.
$postSpec = [
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min' => 5, 'max' => 5],
    [
        'username' => [
            VALIDATE_STRING, VALIDATE_STRING_ALNUM,
            ['min' => 3, 'max' => 32, 'ascii' => '-_',
             'error_message' => 'Username must be 3-32 chars (alnum, "-", "_").']
        ],
        'email'    => $basicTypes['email'],
        'age'      => [
            VALIDATE_INT, VALIDATE_FLAG_NONE,
            ['min' => 13, 'max' => 120,
             'error_message' => 'Age must be between 13 and 120.']
        ],
        'country'  => [
            VALIDATE_REGEXP, VALIDATE_FLAG_NONE,
            ['min' => 2, 'max' => 2,
             'ascii' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
             'regexp' => '/\A(?:JP|US|GB|DE|FR)\z/', // ISO 3166-1 alpha-2 whitelist
             'error_message' => 'Country must be one of: JP, US, GB, DE, FR.']
        ],
        'accepted_tos' => $basicTypes['accepted'], // "yes"/"on"/"1"/"true"
    ]
];

// $_COOKIE: session id (PHP session.sid_length default is 32; tolerate 32-128).
$cookieSpec = [
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min' => 1, 'max' => 4], // session + optional UX cookies
    [
        'PHPSESSID' => $basicTypes['sessid'],
        'lang'      => array_replace($basicTypes['alpha_dash32'],
                                     [VALIDATE_FLAGS => VALIDATE_STRING_ALNUM | VALIDATE_FLAG_UNDEFINED]),
        'theme'     => array_replace($basicTypes['alpha_dash32'],
                                     [VALIDATE_FLAGS => VALIDATE_STRING_ALNUM | VALIDATE_FLAG_UNDEFINED]),
    ]
];

// $_FILES: single avatar upload. Each $_FILES[<name>] is itself an array of 5
// keys: name, type, tmp_name, error, size. Validate every key.
$uploadSpec = [
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min' => 5, 'max' => 5],
    [
        'name'     => [VALIDATE_STRING, VALIDATE_STRING_ALNUM,
                       ['min' => 1, 'max' => 255, 'ascii' => '._-']],
        'type'     => [VALIDATE_REGEXP, VALIDATE_FLAG_NONE,
                       ['min' => 6, 'max' => 32,
                        'ascii' => 'abcdefghijklmnopqrstuvwxyz/',
                        'regexp' => '/\Aimage\/(?:jpeg|png|gif|webp)\z/']],
        'tmp_name' => [VALIDATE_STRING, VALIDATE_STRING_ALNUM,
                       ['min' => 1, 'max' => 4096, 'ascii' => '/_.-']],
        'error'    => [VALIDATE_INT, VALIDATE_FLAG_NONE,
                       ['min' => 0, 'max' => 8]], // UPLOAD_ERR_OK..UPLOAD_ERR_EXTENSION
        'size'     => [VALIDATE_INT, VALIDATE_FLAG_NONE,
                       ['min' => 1, 'max' => 5 * 1024 * 1024]], // up to 5 MiB
    ]
];

$filesSpec = [
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min' => 1, 'max' => 1],
    [
        'avatar' => $uploadSpec,
    ]
];

// ---- Top-level spec: validate every HTTP input source at once ---------------

$spec = [
    VALIDATE_ARRAY,
    VALIDATE_FLAG_NONE,
    ['min' => 4, 'max' => 4],
    [
        'get'    => $getSpec,
        'post'   => $postSpec,
        'cookie' => $cookieSpec,
        'files'  => $filesSpec,
    ]
];

// Bundle the four superglobals under matching keys.
$inputs = [
    'get'    => $_GET,
    'post'   => $_POST,
    'cookie' => $_COOKIE,
    'files'  => $_FILES,
];

$func_opts = VALIDATE_OPT_DISABLE_EXCEPTION; // interactive form: collect errors
$result = validate($ctx, $inputs, $spec, $func_opts);

if (!validate_get_status($ctx)) {
    // One or more inputs are invalid. Show user-facing errors back to the form.
    $errors = validate_get_user_errors($ctx);
    // $inputs now contains only the values that did NOT validate.
    // Re-render the form with $errors.
    // FAIL FAST for APPLICATION INPUT validation errors that no honest client
    // would ever produce (broken types, oversized strings, etc.).
    var_dump($errors);
    exit;
}

// $result is a fully-typed, fully-validated nested array. Hand it to the
// business-logic layer (model) without further input-shape checks.
var_dump($result);