PHPackages                             kengoldfarb/underscore\_libs - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. kengoldfarb/underscore\_libs

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

kengoldfarb/underscore\_libs
============================

\_php libraries

2.0.3(8y ago)21.8k1MITPHPPHP &gt;=5.3.0

Since Dec 7Pushed 8y ago1 watchersCompare

[ Source](https://github.com/kengoldfarb/underscore_libs)[ Packagist](https://packagist.org/packages/kengoldfarb/underscore_libs)[ Docs](http://underscorephp.com)[ RSS](/packages/kengoldfarb-underscore-libs/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (1)Versions (11)Used By (1)

UnderscorePHP \_Libs
====================

[](#underscorephp-_libs)

### A set of useful, framework-agnostic PHP libraries to make life easier

[](#a-set-of-useful-framework-agnostic-php-libraries-to-make-life-easier)

Goal: A set of libraries that are useful, flexible, and can be used within any framework.

Installation
------------

[](#installation)

### Composer

[](#composer)

Using the [composer](http://getcomposer.org/) package manager, In your composer.json file add:

```
{
    "require": {
        "kengoldfarb/underscore_libs": "~2.0.0"
    }
}
```

Then install it (from the same directory as composer.json): php composer.phar install

### Manual Installation

[](#manual-installation)

You can either download the [latest release](https://github.com/kengoldfarb/underscore_libs/releases) or you can just grab the source of an individual library and plug it in to your project.

Usage
-----

[](#usage)

Here you'll find information and examples about each of the libraries. These examples may not cover all permutations of how a library may be used. For more advanced details please view the source code...hopefully you'll find that the comments are very verbose and easy to understand.

- [Logging](#log): *A logging class that also logs objects!*
- [Encryption](#crypt): *Simple AES or RSA (pub/private key) encryption*
- [UUID](#uuid): *Generate and work with uuids*
- [Database (MySQL)](#db): *MySQL database wrapper class with some nicities*
- [File](#file): *Makes working with files easier*
- [Random](#rand): *Generate random numbers, strings.*
- [ServiceResponse](#service-response): *For API responses to generate consistent json or xml responses*
- [Session](#session): *A session wrapper to provide additional error checking*
- [SSL](#ssl): *Methods to check if SSL is active or require SSL*
- [Web Response](#web-response): *Some nice utility stuff like setting P3P headers, sending http status codes, etc.*
- [Info](#info): *Extract information about a web request*

Tests
-----

[](#tests)

Tests can be found in the 'tests' directory and can be run with phpunit. If you've cloned this repository, you can run the tests...

```
$ cd /path/to/underscore_libs
$ composer install # The location of composer may differ on your computer
$ vendor/bin/phpunit tests/_CryptTest.php # Run the test

```

\### Logging The logging library provides are log levels and the ability to log complex objects.

Logs are written via php's native `error_log` function. The location of the log message may appear in a file, webserver log, syslog, etc. depending on your settings.

Change the **error\_log** setting in your php.ini file to adjust the location.

#### Options

[](#options)

You can set the following options on the logger:

- `_Log::$logLevel` *Default: DEBUG*

The log level may be set to one of:

- `_\_LogContants::FATAL`
- `_\_LogContants::CRIT`
- `_\_LogContants::WARN`
- `_\_LogContants::INFO`
- `_\_LogContants::DEBUG`

Once set, any logs at or above that level will be logged. For example, if I set the level to INFO, any 'debug' logs will not be written but a 'warn' log would be written.

- `_Log::$logObjects` *Default: TRUE*

Boolean. Whether or not to log complex objects.

- `_Log::$logEcho` *Default: FALSE*

Boolean. Whether to use php's `echo` for log messages. Can be handy for CLI scripts.

- `_Log::$useExceptions` *Default: FALSE*

Boolean. Whether to throw an exception if an error log can't be written. In most cases you probably want to leave this FALSE

#### Examples

[](#examples)

```
use _\_Log;
_Log::$logLevel = _\_LogContants::INFO;

_Log::debug('This is a debug message that will not be written because of log level');
_Log::info('This is an info message');
_Log::warn('This is a warning message');
_Log::crit('This is a critical message');
_Log::fatal('Oh snap.  This is a fatal error message');
```

\### Encryption The Crypt class provides AES and RSA encryption and decryption methods.

#### AES encryption with PKCS7 padding

[](#aes-encryption-with-pkcs7-padding)

##### Options

[](#options-1)

`_Crypt::_encryptAESPKCS7($textToEncrypt, $key, $cipher, $mode)`

**$textToEncrypt** *Required*

**$key** *Required*

**$cipher** *Optional*

Default: MCRYPT\_RIJNDAEL\_256 Allowed values are: MCRYPT\_RIJNDAEL\_128, MCRYPT\_RIJNDAEL\_192, MCRYPT\_RIJNDAEL\_256

[More information](http://www.php.net/manual/en/mcrypt.ciphers.php)

**$mode** *Optional*

Default: MCRYPT\_MODE\_CBC Allowed values are: MCRYPT\_MODE\_CBC, MCRYPT\_MODE\_ECB, MCRYPT\_MODE\_CFB, MCRYPT\_MODE\_OFB, MCRYPT\_MODE\_NOFB, MCRYPT\_MODE\_STREAM

[More information](http://us3.php.net/manual/en/mcrypt.constants.php)

##### Basic Example

[](#basic-example)

```
use _\_Crypt;

// Set the secret key
$secretKey = "MySecretKey123";

// The text to encrypt
$textToEncrypt = "How much wood could a woodchuck chuck if a woodchuck could chuck wood?";

// The encrypted text
$encryptedText = _Crypt::_encryptAESPKCS7($textToEncrypt, $secretKey);

// The decrypted text (will match $textToEncrypt)
$decryptedText = _Crypt::_decryptAESPKCS7($encryptedText, $secretKey);
```

#### RSA encryption (public/private keys)

[](#rsa-encryption-publicprivate-keys)

This type of encryption is perfect for situations where you need to encrypt something within an application that doesn't need to be decrypted within the application. In that case you could keep the decryption (private) key off your application server for added security.

#### Generate RSA Public/Private keypair

[](#generate-rsa-publicprivate-keypair)

Generate a keypair. You can optionally pass in $keybits which may be one of: 1024, 2048, 4096

```
$keys = _Crypt::_generateRSAKeys();
$publicKey = $keys['public'];
$privateKey = $keys['private'];
```

#### RSA Encrypt/Decrypt

[](#rsa-encryptdecrypt)

```
$textToEncrypt = "How much wood could a woodchuck chuck if a woodchuck could chuck wood?";
$encryptedText = _Crypt::_encryptRSA($textToEncrypt, $publicKey);
$decryptedText = _Crypt::_decryptRSA($encryptedText, $privateKey);
```

\### UUID This library provides functions for working with a UUID or "Universally Unique Identifier". #### Generate a UUID

[](#generate-a-uuid)

##### Options

[](#options-2)

$withHyphens *Default: TRUE*This single option can be passed to the function that controls over whether or not the UUID will contain hyphens.

##### Example

[](#example)

```
use _\_UUID;

$uuid = _UUID::getUUID();
```

#### Convert UUID string to binary representation

[](#convert-uuid-string-to-binary-representation)

##### Example

[](#example-1)

```
use _\_UUID;

$uuid = '55a0afe6-0e00-4c08-9fb9-7905f0a106b6';
$binaryUUID = _UUID::charUUIDToBinary($uuid);
```

#### Convert UUID in binary to string representation

[](#convert-uuid-in-binary-to-string-representation)

##### Options

[](#options-3)

$withHyphens *Default: TRUE*This single option can be passed to the function that controls over whether or not the UUID will contain hyphens.

##### Example

[](#example-2)

```
use _\_UUID;

$uuid = '55a0afe6-0e00-4c08-9fb9-7905f0a106b6';
$binaryUUID = _UUID::charUUIDToBinary($uuid);

$strUUID = _UUID::binaryUUIDToCharUUID($binaryUUID);

// At this point, $uuid == $strUUID
```

\### Database Wrapper for the mysqli library. Provides both regular and static class interfaces. In most cases you'll want to use the static interface which will share the DB connection within your application. This helps prevent the opening of uncessary connections.

#### Public variables

[](#public-variables)

$mysqli For non-static interfaces, you can access the 'mysqli' object directly.

**Note:** the below examples assume you're using the static version of the DB class. The non-static versions of the functions have the same name without the beginning underscore. I.e. \_Log::\_query($sql) corresponds to $db-&gt;query($sql)

#### Examples

[](#examples-1)

##### Create a connection

[](#create-a-connection)

```
use _\_Db;
$host = 'localhost';
$user = 'root';
$pass = 'mysupersecretpassword';
$dbName = 'the_db';
$port = 3306;

_Db::_createConnection($host, $username, $password, $dbName, $port);
```

##### Create a query, escape it, get the number of rows and process the rows

[](#create-a-query-escape-it-get-the-number-of-rows-and-process-the-rows)

```
$sql = "select * from users";
$sql = _Db::_escape($sql);
$queryResult = _Db::_query($sql);

if($queryResult === FALSE) {
	// Handle error
}else{
	$numRows = _Db::_count();
	while($row = _Db::getRow()) {
		// Do something with $row
	}
}
```

##### Insert a new row into the db and get the resulting id

[](#insert-a-new-row-into-the-db-and-get-the-resulting-id)

```
$sql = "insert into users (name, username) values ('Ken', 'ken')";
$queryResult = _Db::_query($sql);
if($queryResult === FALSE) {
	// Handle error
}else{
	$userId = _Db::_lastId();
}
```

\### File Simplifies the task of writing and reading from files #### Regular Methods

[](#regular-methods)

- writeToFile($textToWrite, $filename = NULL)
- getFilePermissions($filename = NULL)
- readAllFromFile($filename = NULL)
- readByLineFromFile($filename = NULL)
- deleteFile($filename)
- getTemporaryFileDirectory()

#### Static Methods

[](#static-methods)

- \_writeToFile($textToWrite, $filename, $permissions = \_FileConstants::READ\_WRITE\_END\_OF\_FILE\_CREATE)
- \_readAllFromFile($filename, $permission = \_FileConstants::READ\_ONLY)

#### Options

[](#options-4)

Some of the methods will allow you to pass a constant specifying which permissions the file should be opened with. The available (self explanitory) options are: \_FileConstants::READ\_ONLY \_FileConstants::READ\_WRITE \_FileConstants::WRITING\_ONLY\_CREATE \_FileConstants::READ\_WRITE\_TRUNCATE\_CREATE \_FileConstants::WRITE\_ONLY\_END\_OF\_FILE\_CREATE \_FileConstants::READ\_WRITE\_END\_OF\_FILE\_CREATE \_FileConstants::WRITE\_ONLY\_BEGIN\_OF\_FILE \_FileConstants::READ\_WRITE\_BEGIN\_OF\_FILE \_FileConstants::WRITE\_ONLY\_NO\_TRUNCATE\_BEGIN\_OF\_FILE \_FileConstants::READ\_WRITE\_NO\_TRUNCATE\_BEGIN\_OF\_FILE

#### Examples

[](#examples-2)

##### Read from file

[](#read-from-file)

```
use _\_File;
$fileData = _File::_readAllFromFile('/tmp/myfile.txt');
if($fileData === FALSE) {
	// Handle error reading from file
}

echo $fileData;
```

##### Write to file

[](#write-to-file)

```
use _\_File;
$writeSuccessful = _File::_writeToFile('Here is some text for myfile.txt', '/tmp/myfile.txt');
if($writeSuccessful) {
	echo $fileData;
}else{
	// Hand error writing file
}
```

\### Info General info and helper class.

#### Get the user's IP address

[](#get-the-users-ip-address)

Gets the user's ip. This should work behind load balancers. It will first check for the `HTTP_X_FORWARDED_FOR` header for the ip address. If that isn't set it will use `REMOTE_ADDR`.

```
use _\_Info;
$userIp = _Info::_getUserIpAddr();
```

#### Get the current datetime in a mysql friendly format

[](#get-the-current-datetime-in-a-mysql-friendly-format)

```
use _\_Info;
$mysqlDatetime = _Info::_mysqlNow();
```

\### Random #### Get Random Number

[](#get-random-number)

**\_getRand($min, $max)**

```
use _\_Rand;
$min = 0;
$max = 100;
_Rand::_getRand($min, $max);
```

#### Get Random String

[](#get-random-string)

**\_randString($length, $lettersNumbersOnly = false)**

```
use _\_Rand;
$length = 10; // The number of characters in the string
$lettersNumbersOnly = true; // String will contain only letters and numbers
_Rand::_randString($length, $lettersNumbersOnly);
```

#### Get Random Character

[](#get-random-character)

**\_randCharacter($start = 32, $end = 126)**

##### Parameters

[](#parameters)

**$start** The ascii character code to start from **$end** The ascii character code to end at

See [http://www.asciitable.com](http://www.asciitable.com/) for a list of character codes

```
use _\_Rand;
$randChar = _Rand::_randCharacter();

```

\### Service Response This library generates json or xml responses in a consistent format.

#### Parameters

[](#parameters-1)

**$objects** Any object to be serialized. String, number, object, array, etc. **$echoResponse** *optional* Whether or not to echo the response **$format** *optional* 'json' or 'xml'

#### Success

[](#success)

**\_success($objects, $echoResponse = TRUE, $format = 'json')**

```
use _\_ServiceResponse;
_ServiceResponse::_success(array('hello' => 'world'));

// Result: {"status": "success", "hello": "world"}
```

#### Failure

[](#failure)

**\_failure($objects, $echoResponse = TRUE, $format = 'json')**

```
use _\_ServiceResponse;
_ServiceResponse::_failure(array('reason' => 'server error'));

// Result: {"status": "failure", "reason": "server error"}
```

\### SSL TODO

\### Session TODO

\### Web Response TODO

Versioning
----------

[](#versioning)

This project will follow the guidelines set forth in [Semantic Versioning](http://semver.org/);

Contact
-------

[](#contact)

Author: [Ken Goldfarb](mailto:hello@kengoldfarb.com)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~280 days

Recently: every ~339 days

Total

7

Last Release

3227d ago

Major Versions

1.0.2 → 2.0.02014-01-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/c2693ebaacdf72f34dc86a5b07d532f7c80076a3533a00c28ee179eda2b96d42?d=identicon)[kengoldfarb](/maintainers/kengoldfarb)

---

Top Contributors

[![kengoldfarb](https://avatars.githubusercontent.com/u/1094411?v=4)](https://github.com/kengoldfarb "kengoldfarb (33 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kengoldfarb-underscore-libs/health.svg)

```
[![Health](https://phpackages.com/badges/kengoldfarb-underscore-libs/health.svg)](https://phpackages.com/packages/kengoldfarb-underscore-libs)
```

###  Alternatives

[doctrine/deprecations

A small layer on top of trigger\_error(E\_USER\_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.

1.8k473.4M32](/packages/doctrine-deprecations)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k17.1M59](/packages/spatie-regex)

PHPackages © 2026

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