Skip to content

Instantly share code, notes, and snippets.

@kkumar326
Created February 19, 2020 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkumar326/7d0ee009ca4182c59fef0a64f3225d61 to your computer and use it in GitHub Desktop.
Save kkumar326/7d0ee009ca4182c59fef0a64f3225d61 to your computer and use it in GitHub Desktop.
PHP file logging
/*
To ease debugging. Logs data into a file - debug.log in root.
Usage: dlog("w", $var1, "string", 45, true)
Modes: Write and Append
*/
function dlog(string $mode='a', ...$vars) {
if (in_array($mode, ["a", "w"])) {
$fileHandle = @fopen("debug.log", $mode);
if ($fileHandle === FALSE){
throw new Exception('Unable to open the file!');
die();
}
foreach ($vars as $var) {
fwrite($fileHandle, stringify($var)."\r\n");
}
fclose($fileHandle);
}
}
// Converts data into string
function stringify($var): string {
switch (gettype($var)) {
case 'string':
return $var;
break;
case 'object':
return serialize($var);
break;
case 'array':
return implode(',', $var);
break;
case 'boolean':
case 'integer':
case 'double':
return strval($var);
break;
default:
return '**Unknown Variable Type**';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment