Formvalidator check even if value is empty - php

Thanks to this forum I came across below form validator some time back which work fine. However, I just have one problem.
When submitting a form with an empty textarea for instance it return the empty field as an error. However, as the value is not mandatory I need to correct this somehow.
<?php
/**
* Pork Formvalidator. validates fields by regexes and can sanatize them. Uses PHP filter_var built-in functions and extra regexes
* #package pork
*/
/**
* Pork.FormValidator
* Validates arrays or properties by setting up simple arrays
*
* #package pork
* #author SchizoDuckie
* #copyright SchizoDuckie 2009
* #version 1.0
* #access public
*/
class FormValidator
{
public static $regexes = Array(
'date' => "^[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}\$",
'datetime' => "20\d{2}(-|\/)((0[1-9])|(1[0-2]))(-|\/)((0[1-9])|([1-2][0-9])|(3[0-1]))(T|\s)(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])",
'amount' => "^[-]?[0-9]+\$",
'number' => "^[-]?[0-9,]+\$",
'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$",
'not_empty' => "[a-z0-9A-Z]+",
'words' => "^[A-Za-z]+[A-Za-z \\s]*\$",
'phone' => "^[0-9]{10,11}\$",
'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$",
'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$",
'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$",
'2digitopt' => "^\d+(\,\d{2})?\$",
'2digitforce' => "^\d+\,\d\d\$",
'anything' => "^[\d\D]{1,}\$",
'username' => "^[\w]{3,32}\$"
);
private $validations, $sanatations, $mandatories, $equal, $errors, $corrects, $fields;
public function __construct($validations=array(), $mandatories = array(), $sanatations = array(), $equal=array())
{
$this->validations = $validations;
$this->sanatations = $sanatations;
$this->mandatories = $mandatories;
$this->equal = $equal;
$this->errors = array();
$this->corrects = array();
}
/**
* Validates an array of items (if needed) and returns true or false
*
* JP modofied this function so that it checks fields even if they are not submitted.
* for example the original code did not check for a mandatory field if it was not submitted.
* Also the types of non mandatory fields were not checked.
*/
public function validate($items)
{
$this->fields = $items;
$havefailures = false;
//Check for mandatories
foreach($this->mandatories as $key=>$val)
{
if(!array_key_exists($val,$items))
{
$havefailures = true;
$this->addError($val);
}
}
//Check for equal fields
foreach($this->equal as $key=>$val)
{
//check that the equals field exists
if(!array_key_exists($key,$items))
{
$havefailures = true;
$this->addError($val);
}
//check that the field it's supposed to equal exists
if(!array_key_exists($val,$items))
{
$havefailures = true;
$this->addError($val);
}
//Check that the two fields are equal
if($items[$key] != $items[$val])
{
$havefailures = true;
$this->addError($key);
}
}
foreach($this->validations as $key=>$val)
{
//An empty value or one that is not in the list of validations or one that is not in our list of mandatories
if(!array_key_exists($key,$items))
{
$this->addError($key, $val);
continue;
}
$result = self::validateItem($items[$key], $val);
if($result === false) {
$havefailures = true;
$this->addError($key, $val);
}
else
{
$this->corrects[] = $key;
}
}
return(!$havefailures);
}
/* JP
* Returns a JSON encoded array containing the names of fields with errors and those without.
*/
public function getJSON() {
$errors = array();
$correct = array();
if(!empty($this->errors))
{
foreach($this->errors as $key=>$val) { $errors[$key] = $val; }
}
if(!empty($this->corrects))
{
foreach($this->corrects as $key=>$val) { $correct[$key] = $val; }
}
$output = array('errors' => $errors, 'correct' => $correct);
return json_encode($output);
}
/**
*
* Sanatizes an array of items according to the $this->sanatations
* sanatations will be standard of type string, but can also be specified.
* For ease of use, this syntax is accepted:
* $sanatations = array('fieldname', 'otherfieldname'=>'float');
*/
public function sanatize($items)
{
foreach($items as $key=>$val)
{
if(array_search($key, $this->sanatations) === false && !array_key_exists($key, $this->sanatations)) continue;
$items[$key] = self::sanatizeItem($val, $this->validations[$key]);
}
return($items);
}
/**
*
* Adds an error to the errors array.
*/
private function addError($field, $type='string')
{
$this->errors[$field] = $type;
}
/**
*
* Sanatize a single var according to $type.
* Allows for static calling to allow simple sanatization
*/
public static function sanatizeItem($var, $type)
{
$flags = NULL;
switch($type)
{
case 'url':
$filter = FILTER_SANITIZE_URL;
break;
case 'int':
$filter = FILTER_SANITIZE_NUMBER_INT;
break;
case 'float':
$filter = FILTER_SANITIZE_NUMBER_FLOAT;
$flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND;
break;
case 'email':
$var = substr($var, 0, 254);
$filter = FILTER_SANITIZE_EMAIL;
break;
case 'string':
default:
$filter = FILTER_SANITIZE_STRING;
$flags = FILTER_FLAG_NO_ENCODE_QUOTES;
break;
}
$output = filter_var($var, $filter, $flags);
return($output);
}
/**
*
* Validates a single var according to $type.
* Allows for static calling to allow simple validation.
*
*/
public static function validateItem($var, $type)
{
if(array_key_exists($type, self::$regexes))
{
$returnval = filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false;
return($returnval);
}
$filter = false;
switch($type)
{
case 'email':
$var = substr($var, 0, 254);
$filter = FILTER_VALIDATE_EMAIL;
break;
case 'int':
$filter = FILTER_VALIDATE_INT;
break;
case 'boolean':
$filter = FILTER_VALIDATE_BOOLEAN;
break;
case 'ip':
$filter = FILTER_VALIDATE_IP;
break;
case 'url':
$filter = FILTER_VALIDATE_URL;
break;
}
return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;
}
}
?>
So from what I understand I need to come up with a a way to validate an empty string as the above code will throw an error.
$validations = array(
'id' => 'number', //Value in _POST['id'] = '11'
'time' => 'datetime', //Value in _POST['time'] = '2016-03-17T11:05:01'
'description' => 'anything'); //Value in _POST['decription'] = ''
$required = array('id', 'time');
$validator = new FormValidator($validations, $required);
$validator->validate($_POST);
print_r $validator->getJSON();

You should either make the field required and add something like this
// validation
if (empty($variable)) {
echo 'such&such is required<br />';
$ok = false;
}
Or make the variable ="" or null;

Related

How to wrap functions in PHP's highlight_file with anchor tags?

I found it would be useful for me to be able to have a dumb, read-only version of my (private) code online, so I could check things from my phone without having to open an IDE or SSH into a remote host from a dynamic IP address. I've got all of it figured out except for the last part:
I'm using PHP's highlight_file to get that read-version of the code, but I'd like to make it so clicking on the functions allows me to jump to their declaration, just like CTRL+click does in PhpStorm. In order to do that I wrote up a "find function declaration" script, but now I need to
In order to do that I need to identify what the functions are, then wrap them in an anchor tag to call my function-finding script. So, is there any way I can configure highlight_file to denote my functions so I can wrap them? Or some regex or anything?
For what it's worth, I am using this line-number adding function for my printer.
You might have to re-think the process/requirements. The hightlight_file() function returns alot of HTML injected into the original code i.e.
function test() {}
test();
becomes:
<br />function </span><span style="color: #0000BB">test</span><span style="color: #007700">() {
<br /><span style="color: #0000BB">test</span><span style="color: #007700">();
Just sayin.....
After additional research I found Aidan Lister's comment on the PHP function itself, but the links were 404. After researching him a little I found his Git repo and the relevant functions. Here it is:
https://github.com/aidanlister/code/blob/master/PHP_Highlight.php
And copy/pasted in case a link 404's again:
<?php
/**
* PHP 5 added a set of new constants which need to be declared in this file for
* effective PHP 5 highlighting. It also removed constants, which need to be
* included for PHP 4 highlighting.
*
* The following file will define constants for PHP 4 / PHP 5 compatability
*
* The source of this file can be found at:
* https://raw.githubusercontent.com/aidanlister/code/master/PHP_Highlight.php
*
* It is part of the PEAR PHP_Compat package:
* http://pear.php.net/package/PHP_Compat
*/
require_once 'PHP/Compat/Constant/T.php';
/**
* Improved PHP syntax highlighting.
*
* Generates valid XHTML output with function referencing
* and line numbering.
*
* Extendable output methods provide maximum flexibility,
* toHtml(), toHtmlComment(), toList() and toArray().
*
* Highlighting can be inline (with styles), or the same as
* highlight_file() where colors are taken from php.ini.
*
* #author Aidan Lister <aidan#php.net>
* #version 1.4.3
* #link http://aidanlister.com/repos/v/PHP_Highlight.php
*/
class PHP_Highlight
{
/**
* Hold highlight colors
*
* Contains an associative array of token types and colours.
* By default, it contains the colours as specified by php.ini
*
* For example, to change the colour of strings, use something
* simular to $h->highlight['string'] = 'blue';
*
* #var array
* #access public
*/
var $highlight;
/**
* Things to be replaced for formatting or otherwise reasons
*
* The first element contains the match array, the second the replace
* array.
*
* #var array
* #access public
*/
var $replace = array(
"\t" => ' ',
' ' => ' ');
/**
* Format of the link to the PHP manual page
*
* #var string
* #access public
*/
var $manual = '%s';
/**
* Format of the span tag to be wrapped around each token
*
* #var string
* #access public
*/
var $span;
/**
* Hold the source
*
* #var string
* #access private
*/
var $_source = false;
/**
* Hold plaintext keys
*
* An array of lines which are plaintext
*
* #var array
* #access private
*/
var $_plaintextkeys = array();
/**
* Constructor
*
* Populates highlight array
*
* #param bool $inline If inline styles rather than colors are to be used
* #param bool $plaintext Do not format code outside PHP tags
*/
function PHP_Highlight($inline = false)
{
// Inline
if ($inline === false) {
// Default colours from php.ini
$this->highlight = array(
'string' => ini_get('highlight.string'),
'comment' => ini_get('highlight.comment'),
'keyword' => ini_get('highlight.keyword'),
'bg' => ini_get('highlight.bg'),
'default' => ini_get('highlight.default'),
'html' => ini_get('highlight.html')
);
$this->span = '<span style="color: %s;">%s</span>';
} else {
// Basic styles
$this->highlight = array(
'string' => 'string',
'comment' => 'comment',
'keyword' => 'keyword',
'bg' => 'bg',
'default' => 'default',
'html' => 'html'
);
$this->span = '<span class="%s">%s</span>';
}
}
/**
* Load a file
*
* #access public
* #param string $file The file to load
* #return bool Returns TRUE
*/
function loadFile($file)
{
$this->_source = file_get_contents($file);
return true;
}
/**
* Load a string
*
* #access public
* #param string $string The string to load
* #return bool Returns TRUE
*/
function loadString($string)
{
$this->_source = $string;
return true;
}
/**
* Parse the loaded string into an array
* Source is returned with the element key corresponding to the line number
*
* #access public
* #param bool $funcref Reference functions to the PHP manual
* #param bool $blocks Whether to ignore processing plaintext
* #return array An array of highlighted source code
*/
function toArray($funcref = true, $blocks = false)
{
// Ensure source has been loaded
if ($this->_source == false) {
return false;
}
// Init
$tokens = token_get_all($this->_source);
$manual = $this->manual;
$span = $this->span;
$stringflag = false;
$i = 0;
$out = array();
$out[$i] = '';
// Loop through each token
foreach ($tokens as $j => $token) {
// Single char
if (is_string($token)) {
// Entering or leaving a quoted string
if ($token === '"' && $tokens[$j - 1] !== '\\') {
$stringflag = !$stringflag;
$out[$i] .= sprintf($span, $this->highlight['string'], $token);
} else {
// Skip token2color check for speed
$out[$i] .= sprintf($span, $this->highlight['keyword'], htmlspecialchars($token));
// Heredocs behave strangely
list($tb) = isset($tokens[$j - 1]) ? $tokens[$j - 1] : false;
if ($tb === T_END_HEREDOC) {
$out[++$i] = '';
}
}
continue;
}
// Proper token
list ($token, $value) = $token;
// Make the value safe
$value = htmlspecialchars($value);
$value = str_replace(
array_keys($this->replace),
array_values($this->replace),
$value);
// Process
if ($value === "\n") {
// End this line and start the next
$out[++$i] = '';
} else {
// Function linking
if ($funcref === true && $token === T_STRING) {
// Look ahead 1, look ahead 2, and look behind 3
// For a function we expect T_FUNCTION T_STRING [T_WHITESPACE] (
if ((isset($tokens[$j + 1]) && $tokens[$j + 1] === '(' ||
isset($tokens[$j + 2]) && $tokens[$j + 2] === '(') &&
isset($tokens[$j - 3][0]) && $tokens[$j - 3][0] !== T_FUNCTION
&& function_exists($value)) {
// Insert the manual link
$value = sprintf($manual, $value, $value);
}
}
// Explode token block
$lines = explode("\n", $value);
foreach ($lines as $jj => $line) {
$line = trim($line);
if ($line !== '') {
// Uncomment for debugging
//$out[$i] .= token_name($token);
// Check for plaintext
if ($blocks === true && $token === T_INLINE_HTML) {
$this->_plaintextkeys[] = $i;
$out[$i] .= $line;
} else {
// Highlight encased strings
$colour = ($stringflag === true) ?
$this->highlight['string'] :
$this->_token2color($token);
$out[$i] .= sprintf($span, $colour, $line);
}
}
// Start a new line
if (isset($lines[$jj + 1])) {
$out[++$i] = '';
}
}
}
}
return $out;
}
/**
* Convert the source to an ordered list.
* Each line is wrapped in <li> tags.
*
* #access public
* #param bool $return Return rather than print the results
* #param bool $funcref Reference functions to the PHP manual
* #param bool $blocks Whether to use code blocks around plaintext
* #return string A HTML ordered list
*/
function toList($return = false, $funcref = true, $blocks = true)
{
// Ensure source has been loaded
if ($this->_source == false) {
return false;
}
// Format list
$source = $this->toArray($funcref, $blocks);
$out = "<ol>\n";
foreach ($source as $i => $line) {
$out .= " <li>";
// Some extra juggling for lines which are not code
if (empty($line)) {
$out .= ' ';
} elseif ($blocks === true && in_array($i, $this->_plaintextkeys)) {
$out .= $line;
} else {
$out .= "<code>$line</code>";
}
$out .= "</li>\n";
}
$out .= "</ol>\n";
if ($return === true) {
return $out;
} else {
echo $out;
}
}
/**
* Convert the source to formatted HTML.
* Each line ends with <br />.
*
* #access public
* #param bool $return Return rather than print the results
* #param bool $linenum Display line numbers
* #param string $format Specify format of line numbers displayed
* #param bool $funcref Reference functions to the PHP manual
* #return string A HTML block of code
*/
function toHtml($return = false, $linenum = false, $format = null, $funcref = true)
{
// Ensure source has been loaded
if ($this->_source == false) {
return false;
}
// Line numbering
if ($linenum === true && $format === null) {
$format = '<span>%02d</span> ';
}
// Format code
$source = $this->toArray($funcref);
$out = "<code>\n";
foreach ($source as $i => $line) {
$out .= ' ';
if ($linenum === true) {
$out .= sprintf($format, $i);
}
$out .= empty($line) ? ' ' : $line;
$out .= "<br />\n";
}
$out .= "</code>\n";
if ($return === true) {
return $out;
} else {
echo $out;
}
}
/**
* Convert the source to formatted HTML blocks.
* Each line ends with <br />.
*
* This method ensures only PHP is between <<code>> blocks.
*
* #access public
* #param bool $return Return rather than print the results
* #param bool $linenum Display line numbers
* #param string $format Specify format of line numbers displayed
* #param bool $reset Reset the line numbering each block
* #param bool $funcref Reference functions to the PHP manual
* #return string A HTML block of code
*/
function toHtmlBlocks($return = false, $linenum = false, $format = null, $reset = true, $funcref = true)
{
// Ensure source has been loaded
if ($this->_source == false) {
return false;
}
// Default line numbering
if ($linenum === true && $format === null) {
$format = '<span>%03d</span> ';
}
// Init
$source = $this->toArray($funcref, true);
$out = '';
$wasplain = true;
$k = 0;
// Loop through each line and decide which block to use
foreach ($source as $i => $line) {
// Empty line
if (empty($line)) {
if ($wasplain === true) {
$out .= ' ';
} else {
if (in_array($i+1, $this->_plaintextkeys)) {
$out .= "</code>\n";
// Reset line numbers
if ($reset === true) {
$k = 0;
}
} else {
$out .= ' ';
// Add line number
if ($linenum === true) {
$out .= sprintf($format, ++$k);
}
}
}
// Plain text
} elseif (in_array($i, $this->_plaintextkeys)) {
if ($wasplain === false) {
$out .= "</code>\n";
// Reset line numbers
if ($reset === true) {
$k = 0;
}
}
$wasplain = true;
$out .= str_replace(' ', ' ', $line);
// Code
} else {
if ($wasplain === true) {
$out .= "<code>\n";
}
$wasplain = false;
$out .= ' ';
// Add line number
if ($linenum === true) {
$out .= sprintf($format, ++$k);
}
$out .= $line;
}
$out .= "<br />\n";
}
// Add final code tag
if ($wasplain === false) {
$out .= "</code>\n";
}
// Output method
if ($return === true) {
return $out;
} else {
echo $out;
}
}
/**
* Assign a color based on the name of a token
*
* #access private
* #param int $token The token
* #return string The color of the token
*/
function _token2color($token)
{
switch ($token):
case T_CONSTANT_ENCAPSED_STRING:
return $this->highlight['string'];
break;
case T_INLINE_HTML:
return $this->highlight['html'];
break;
case T_COMMENT:
case T_DOC_COMMENT:
case T_ML_COMMENT:
return $this->highlight['comment'];
break;
case T_ABSTRACT:
case T_ARRAY:
case T_ARRAY_CAST:
case T_AS:
case T_BOOLEAN_AND:
case T_BOOLEAN_OR:
case T_BOOL_CAST:
case T_BREAK:
case T_CASE:
case T_CATCH:
case T_CLASS:
case T_CLONE:
case T_CONCAT_EQUAL:
case T_CONTINUE:
case T_DEFAULT:
case T_DOUBLE_ARROW:
case T_DOUBLE_CAST:
case T_ECHO:
case T_ELSE:
case T_ELSEIF:
case T_EMPTY:
case T_ENDDECLARE:
case T_ENDFOR:
case T_ENDFOREACH:
case T_ENDIF:
case T_ENDSWITCH:
case T_ENDWHILE:
case T_END_HEREDOC:
case T_EXIT:
case T_EXTENDS:
case T_FINAL:
case T_FOREACH:
case T_FUNCTION:
case T_GLOBAL:
case T_IF:
case T_INC:
case T_INCLUDE:
case T_INCLUDE_ONCE:
case T_INSTANCEOF:
case T_INT_CAST:
case T_ISSET:
case T_IS_EQUAL:
case T_IS_IDENTICAL:
case T_IS_NOT_IDENTICAL:
case T_IS_SMALLER_OR_EQUAL:
case T_NEW:
case T_OBJECT_CAST:
case T_OBJECT_OPERATOR:
case T_PAAMAYIM_NEKUDOTAYIM:
case T_PRIVATE:
case T_PROTECTED:
case T_PUBLIC:
case T_REQUIRE:
case T_REQUIRE_ONCE:
case T_RETURN:
case T_SL:
case T_SL_EQUAL:
case T_SR:
case T_SR_EQUAL:
case T_START_HEREDOC:
case T_STATIC:
case T_STRING_CAST:
case T_SWITCH:
case T_THROW:
case T_TRY:
case T_UNSET_CAST:
case T_VAR:
case T_WHILE:
return $this->highlight['keyword'];
break;
case T_CLOSE_TAG:
case T_OPEN_TAG:
case T_OPEN_TAG_WITH_ECHO:
default:
return $this->highlight['default'];
endswitch;
}
}

Codeigniter File Validation Not Working

Why is that form validation still return an error even though the input file is not empty
Here's my controller together with my callback function
public function add_post()
{
$validation = array (
array(
'field' => 'post_title',
'label' => 'Post title',
'rules' => 'trim|required|alpha_numeric_spaces'
),
array(
'field' => 'post_desc',
'label' => 'Post Description',
'rules' => 'trim|required|alpha_numeric_spaces'
),
array(
'field' => 'post_content',
'label' => 'Post content',
'rules' => 'trim|required'
),
array(
'field' => 'headerimage',
'label' => 'File',
'rules' => 'required|callback_file_check'
)
);
$this->form_validation->set_rules($validation);
if($this->form_validation->run()===FALSE)
{
$info['errors'] = validation_errors();
$info['success'] = false;
}
else
{
$this->save_image();
$datetime = $this->get_time();
$data = array(
"post_title" => $this->input->post('post_title'),
"post_content" => $this->input->post('post_content'),
"post_image" => $this->uploadFileName,
"post_created" => $datetime
);
$this->Blog_model->add_post($data);
$info['success'] = true;
$info['message'] = "Successfully added blog post";
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
Here's the form mark-up
<?php echo form_open_multipart('#',array("class"=>"form-horizontal","id"=>"blogform")); ?>
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Enter your post title" name="post_title" class="form-control">
</div>
<div class="col-md-6 form-group">
<label for="file" class="control-label col-md-4">Select header image:</label>
<div class="col-md-8">
<input type="file" id="header" name="headerimage" accept="image/*" />
</div>
</div>
</div>
<input type="text" placeholder="Enter your post description" name="post_desc" class="form-control">
<label class="control-label text-muted">Post Body:</label>
<div>
<textarea id="post_content"></textarea>
</div>
<button class="btn btn-default pull-right" type="button" id="save-post"><i class="fa fa-save"></i> Save Post</button>
<div class="clearfix"></div>
<?php echo form_close(); ?>
I call the add_post controller function through AJAX.
$(document).on('click','#save-post',function(){
$post_content = $('#post_content').summernote('code');
$.ajax({
url:site_url('Blog/add_post'),
data: $('#blogform').serialize() + "&post_content=" + $post_content,
type: "POST",
dataType: 'json',
encode: true,
success: function(data){
if(!data.success){
if(data.errors){
$('#blog-message').html(data.errors).addClass('alert alert-danger');
}
}else{
alert(data.message);
}
}
});
});
I don't understand why validation is not working properly or I think the controller doesn't get the input file.
File upload data is not stored in the $_POST array, so cannot be validated using CodeIgniter's form_validation library. File uploads are available to PHP using the $_FILES array.
if (empty($_FILES['headerimage']['name']))
{
$this->form_validation->set_rules('headerimage', 'file', 'required');
// OR
$this->form_validation->set_rules('headerimage', 'file', 'trim|required');
}
OR you can use below system/application/libraries/MY_form_validation.php
Example :
$this->form_validation->set_rules(
// Field Name
$file_field_name ,
// Label
"YOUR FILE LAEBL",
// Rules
"file_required|file_min_size[10KB]|file_max_size[500KB]|file_allowed_type[jpg,jpeg]|file_image_mindim[50,50]|file_image_maxdim[400,300]"
);
MY_form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* Rules supported:
* file_required
* file_allowed_type[type]
* file_disallowed_type[type]
* file_size_min[size]
* file_size_max[size]
* file_image_mindim[x,y]
* file_image_maxdim[x,y]
*/
class MY_Form_validation extends CI_Form_validation {
function __construct()
{
parent::CI_Form_validation();
}
function set_rules($field, $label = '', $rules = '')
{
if(count($_POST)===0 AND count($_FILES) > 0)//it will prevent the form_validation from working
{
//add a dummy $_POST
$_POST['DUMMY_ITEM'] = '';
parent::set_rules($field,$label,$rules);
unset($_POST['DUMMY_ITEM']);
}
else
{
//we are safe just run as is
parent::set_rules($field,$label,$rules);
}
}
function run($group='')
{
$rc = FALSE;
log_message('DEBUG','called MY_form_validation:run()');
if(count($_POST)===0 AND count($_FILES)>0)//does it have a file only form?
{
//add a dummy $_POST
$_POST['DUMMY_ITEM'] = '';
$rc = parent::run($group);
unset($_POST['DUMMY_ITEM']);
}
else
{
//we are safe just run as is
$rc = parent::run($group);
}
return $rc;
}
function file_upload_error_message($error_code)
{
switch ($error_code)
{
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
log_message('DEBUG','called MY_form_validation::_execute ' . $row['field']);
//changed based on
//http://codeigniter.com/forums/viewthread/123816/P10/#619868
if(isset($_FILES[$row['field']]))
{// it is a file so process as a file
log_message('DEBUG','processing as a file');
$postdata = $_FILES[$row['field']];
//before doing anything check for errors
if($postdata['error'] !== UPLOAD_ERR_OK)
{
$this->_error_array[$row['field']] = $this->file_upload_error_message($postdata['error']);
return FALSE;
}
$_in_array = FALSE;
// If the field is blank, but NOT required, no further tests are necessary
$callback = FALSE;
if ( ! in_array('file_required', $rules) AND $postdata['size']==0)
{
// Before we bail out, does the rule contain a callback?
if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
{
$callback = TRUE;
$rules = (array('1' => $match[1]));
}
else
{
return;
}
}
foreach($rules as $rule)
{
/// COPIED FROM the original class
// Is the rule a callback?
$callback = FALSE;
if (substr($rule, 0, 9) == 'callback_')
{
$rule = substr($rule, 9);
$callback = TRUE;
}
// Strip the parameter (if exists) from the rule
// Rules can contain a parameter: max_length[5]
$param = FALSE;
if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
// Call the function that corresponds to the rule
if ($callback === TRUE)
{
if ( ! method_exists($this->CI, $rule))
{
continue;
}
// Run the function and grab the result
$result = $this->CI->$rule($postdata, $param);
// Re-assign the result to the master data array
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
// If the field isn't required and we just processed a callback we'll move on...
if ( ! in_array('file_required', $rules, TRUE) AND $result !== FALSE)
{
return;
}
}
else
{
if ( ! method_exists($this, $rule))
{
// If our own wrapper function doesn't exist we see if a native PHP function does.
// Users can use any native PHP function call that has one param.
if (function_exists($rule))
{
$result = $rule($postdata);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
continue;
}
$result = $this->$rule($postdata, $param);
if ($_in_array == TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
}
}
//this line needs testing !!!!!!!!!!!!! not sure if it will work
//it basically puts back the tested values back into $_FILES
//$_FILES[$row['field']] = $this->_field_data[$row['field']]['postdata'];
// Did the rule test negatively? If so, grab the error.
if ($result === FALSE)
{
if ( ! isset($this->_error_messages[$rule]))
{
if (FALSE === ($line = $this->CI->lang->line($rule)))
{
$line = 'Unable to access an error message corresponding to your field name.';
}
}
else
{
$line = $this->_error_messages[$rule];
}
// Is the parameter we are inserting into the error message the name
// of another field? If so we need to grab its "field label"
if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['label']))
{
$param = $this->_field_data[$param]['label'];
}
// Build the error message
$message = sprintf($line, $this->_translate_fieldname($row['label']), $param);
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
return;
}
}
}
else
{
log_message('DEBUG','Called parent _execute');
parent::_execute($row, $rules, $postdata,$cycles);
}
}
/**
* Future function. To return error message of choice.
* It will use $msg if it cannot find one in the lang files
*
* #param string $msg the error message
*/
function set_error($msg)
{
$CI =& get_instance();
$CI->lang->load('upload');
return ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
}
/**
* tests to see if a required file is uploaded
*
* #param mixed $file
*/
function file_required($file)
{
if($file['size']===0)
{
$this->set_message('file_required','Uploading a file for %s is required.');
return FALSE;
}
return TRUE;
}
/**
* tests to see if a file is within expected file size limit
*
* #param mixed $file
* #param mixed $max_size
*/
function file_size_max($file,$max_size)
{
$max_size_bit = $this->let_to_bit($max_size);
if($file['size']>$max_size_bit)
{
$this->set_message('file_size_max',"%s is too big. (max allowed is $max_size)");
return FALSE;
}
return true;
}
/**
* tests to see if a file is bigger than minimum size
*
* #param mixed $file
* #param mixed $min_size
*/
function file_size_min($file,$min_size)
{
$max_size_bit = $this->let_to_bit($max_size);
if($file['size']<$min_size_bit)
{
$this->set_message('file_size_min',"%s is too small. (Min allowed is $max_size)");
return FALSE;
}
return true;
}
/**
* tests the file extension for valid file types
*
* #param mixed $file
* #param mixed $type
*/
function file_allowed_type($file,$type)
{
//is type of format a,b,c,d? -> convert to array
$exts = explode(',',$type);
//is $type array? run self recursively
if(count($exts)>1)
{
foreach($exts as $v)
{
$rc = $this->file_allowed_type($file,$v);
if($rc===TRUE)
{
return TRUE;
}
}
}
//is type a group type? image, application, word_document, code, zip .... -> load proper array
$ext_groups = array();
$ext_groups['image'] = array('jpg','jpeg','gif','png');
$ext_groups['application'] = array('exe','dll','so','cgi');
$ext_groups['php_code'] = array('php','php4','php5','inc','phtml');
$ext_groups['word_document'] = array('rtf','doc','docx');
$ext_groups['compressed'] = array('zip','gzip','tar','gz');
if(array_key_exists($exts[0],$ext_groups))
{
$exts = $ext_groups[$exts[0]];
}
//get file ext
$file_ext = strtolower(strrchr($file['name'],'.'));
$file_ext = substr($file_ext,1);
if(!in_array($file_ext,$exts))
{
$this->set_message('file_allowed_type',"%s should be $type.");
return false;
}
else
{
return TRUE;
}
}
function file_disallowed_type($file,$type)
{
$rc = $this->file_allowed_type($file,$type);
if(!$rc)
{
$this->set_message('file_disallowed_type',"%s cannot be $type.");
}
return $rc;
}
//http://codeigniter.com/forums/viewthread/123816/P20/
/**
* given an string in format of ###AA converts to number of bits it is assignin
*
* #param string $sValue
* #return integer number of bits
*/
function let_to_bit($sValue)
{
// Split value from name
if(!preg_match('/([0-9]+)([ptgmkb]{1,2}|)/ui',$sValue,$aMatches))
{ // Invalid input
return FALSE;
}
if(empty($aMatches[2]))
{ // No name -> Enter default value
$aMatches[2] = 'KB';
}
if(strlen($aMatches[2]) == 1)
{ // Shorted name -> full name
$aMatches[2] .= 'B';
}
$iBit = (substr($aMatches[2], -1) == 'B') ? 1024 : 1000;
// Calculate bits:
switch(strtoupper(substr($aMatches[2],0,1)))
{
case 'P':
$aMatches[1] *= $iBit;
case 'T':
$aMatches[1] *= $iBit;
case 'G':
$aMatches[1] *= $iBit;
case 'M':
$aMatches[1] *= $iBit;
case 'K':
$aMatches[1] *= $iBit;
break;
}
// Return the value in bits
return $aMatches[1];
}
/**
* returns false if image is bigger than the dimensions given
*
* #param mixed $file
* #param array $dim
*/
function file_image_maxdim($file,$dim)
{
log_message('debug','MY_form_validation:file_image_maxdim ' . $dim);
$dim = explode(',',$dim);
if(count($dim)!==2)
{
//bad size given
$this->set_message('file_image_maxdim','%s has invalid rule expected similar to 150,300 .');
return FALSE;
}
log_message('debug','MY_form_validation:file_image_maxdim ' . $dim[0] . ' ' . $dim[1]);
//get image size
$d = $this->get_image_dimension($file['tmp_name']);
log_message('debug',$d[0] . ' ' . $d[1]);
if(!$d)
{
$this->set_message('file_image_maxdim','%s dimensions was not detected.');
return FALSE;
}
if($d[0] < $dim[0] && $d[1] < $dim[1])
{
return TRUE;
}
$this->set_message('file_image_maxdim','%s image size is too big.');
return FALSE;
}
/**
* returns false is the image is smaller than given dimension
*
* #param mixed $file
* #param array $dim
*/
function file_image_mindim($file,$dim)
{
$dim = explode(',',$dim);
if(count($dim)!==2)
{
//bad size given
$this->set_message('file_image_mindim','%s has invalid rule expected similar to 150,300 .');
return FALSE;
}
//get image size
$d = $this->get_image_dimension($file['tmp_name']);
if(!$d)
{
$this->set_message('file_image_mindim','%s dimensions was not detected.');
return FALSE;
}
log_message('debug',$d[0] . ' ' . $d[1]);
if($d[0] > $dim[0] && $d[1] > $dim[1])
{
return TRUE;
}
$this->set_message('file_image_mindim','%s image size is too big.');
return FALSE;
}
/**
* attempts to determine the image dimension
*
* #param mixed $file_name path to the image file
* #return array
*/
function get_image_dimension($file_name)
{
log_message('debug',$file_name);
if (function_exists('getimagesize'))
{
$D = #getimagesize($file_name);
return $D;
}
return FALSE;
}
}
/* End of file MY_form_validation.php */
/* Location: ./system/application/libraries/MY_form_validation.php */
For required file validation you can set validation as follow:
if (empty($_FILES['headerimage']['name']))
{
$this->form_validation->set_rules('headerimage', 'File', 'required');
}
Remove:
array(
'field' => 'headerimage',
'label' => 'File',
'rules' => 'required|callback_file_check'
)

How to do robust PHP database modeling

I am trying to figure out best practices for writing robust object oriented database models in PHP. I would like to use a data access layer and then have an abstract model class that my actual models would be able to extend. I was hoping to be able to encapsulate all basic CRUD functionality in these layers so I don't have to write lots of redundant code. I am having trouble finding tutorial on how to do this. Does anyone know of a tutorial or have example code on how to do this?
If you want to abstract this further to just make procedural calls to DbMgr.php above,
you can use the below code. This will help you develop project fast and anyone who doesn't have database knowledge can also use below methods to develop php mysql application.
CALL THIS FILE : DbMgrInterface.php
//Includes complete implementation of DB operations
require_once __DIR__.'/DbMgr.php';
$perform_Database_Operation = null; // Global variable to reuse the connection
$error_code = null; // Global variable holding the error_code for a transaction
function getDBConfig($config = ''){
$source = 'Func';
$type = 'mysql';
if(isset($config['source'])){
$source = $config['source'];
}
if( (strcasecmp("Func",$source) == 0) && (function_exists('get_DbConfig')) ) {
$config = get_DbConfig();
}
if(isset($config['type'])){
$type = $config['type'];
}
$config['dbType'] = strtolower($type);
$config['servername'] = $config['host'];
$config['Port'] = $config['port'];
$config['userName'] = $config['username'];
$config['passWord'] = $config['password'];
$config['DatabaseName'] = $config['database'];
return $config;
}
/**
Logic: If config array is passed to this method then definitely the new handle is required.
Else, If DBMgrHandle already exists then return the existing handle.
Else, get the default DB config, and instantiate a new DBMgr Handle.
*/
function DBMgr_Handle($config = '') {
global $perform_Database_Operation;
$className = 'DBMgr';
if(is_array($config)){
$config = getDBConfig($config);
if(strcasecmp($config['dbType'], 'mssql') == 0){
$className = 'SSRV';
}
$perform_Database_Operation = new $className($config);
return $perform_Database_Operation;
}
if(isset($perform_Database_Operation))
return $perform_Database_Operation;
$config = getDBConfig($config);
if(strcasecmp($config['dbType'], 'mssql') == 0){
$className = 'SSRV';
}
if(function_exists('getclassObject'))
$perform_Database_Operation = getclassObject($className, $config);
else
$perform_Database_Operation = new $className($config);
return $perform_Database_Operation;
}
/*=====================================================READ==============================================================*/
/*
* #access public
* #param associative_Array $readInput. Format is described below:
* array(
* 'Fields'=> 'Field1, Field2, Field3', //Mandatory
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //optional
* 'order' => 'FieldName DESC' //optional
* )
clause refers exact/valid values as mysql query accepts.
clause is a condition to filter output. e.g. 'FieldName = DesiredValue' would return entries where FieldName has DesiredValue value only.
Order refers exact/valid values as mysql query accepts and is used to sort data selection. example value can be 'FieldName ASC' or 'FieldName DESC'.
* #param string $outputFormat. Values can be one of 'RESULT, NUM_ROWS, NUM_ARR, ASSOC', where ASSOC is default value.
* It defines whether the read should return 'mysql result resource/ Numbers of rows in result set / Numbered array / Associative array
* #param string $DataType. Value can only be 'JSON' else ''. Use this to get data set returned as json.
* #param string $keyField_Output. This can be a field name so that indexes of assoc array can be defined with value of the field passed.
*
* #return false, else 0(zero- for no corresponding entry), else output in described format.
* If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Read($readInput, $outputFormat = "ASSOC", $DataType = "", $keyField_Output = '') {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Read($readInput, $outputFormat, $DataType, $keyField_Output);
}
/*=====================================================INSERT==============================================================*/
/*
* #access public
* #param associative_Array $insertInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'Fields'=> array( //Mandatory
'FieldName1' =>Value1,
'FieldName2' =>Value2,
'FieldName_n'=>Value_n
)
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return Inserted Id on success, else false on failure. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Insert($insertInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Insert($insertInput);
}
/*=====================================================UPDATE==============================================================*/
/*
* #access public
* #param associative_Array $updateInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'Fields'=> array( //Mandatory
'FieldName1' =>Value1,
'FieldName2' =>Value2,
'FieldName_n'=>Value_n
),
* 'clause'=> 'FieldName = FieldValue', //optional
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return true on success, else false. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Update($updateInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Update($updateInput);
}
/*=====================================================DELETE==============================================================*/
/*
* #access public
* #param associative_Array $deleteInput. Format is described below:
* array(
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //OPTIONAL. But if not specified all the data from database would be deleted
* )
* So in above associative array the element refered by key 'Fields' is itself an associative array which would specify DbField and corresponding Value to be stored
* #return true on success, else false on failure. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Delete($deleteInput) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Delete($deleteInput);
}
/*=====================================================RUN ABSOLUTE QUERY==============================================================*/
/*
* #access public
* #param Query as a string. Query can be of any type
* #param string $outputFormat. Values can be one of 'RESULT, NUM_ROWS, NUM_ARR, ASSOC', where ASSOC is default value.
* It defines whether the read should return 'mysql result resource/ Numbers of rows in result set / Numbered array / Associative array
* #param string $DataType. Value can only be 'JSON' else ''. Use this to get data set returned as json.
* #param string $keyField_Output. This can be a field name so that indexes of assoc array can be defined with value of the field passed.
*
* #return false, else 0(zero- for no corresponding entry), else output in described format. If mysql error is to be accessed, it is available with a aglobal variable $DB_OperationError
*/
function DB_Query($query, $outputFormat = "ASSOC", $DataType = "", $keyField_Output = '') {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Query($query, $outputFormat, $DataType, $keyField_Output);
}
/**
* The function makes a complete database dump of dump for selective tables, depending upon the TABLE_LIST. If TABLE_LIST is empty,
* a complete database dump is made, else dump for selective tables is carried out.
* #param unknown $ExportDBArray
* $ExportDBArray = array(
'DUMP_FILE_NAME' => 'dump.sql', // optional
'TABLE_LIST' => array( // optional
'Table1' => 'userinfo',
'Table2' => 'usageinfo'
)
);
* #return boolean
*/
function DB_ExportTable($ExportDBArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Export($ExportDBArray);
}
/**
* The function imports SQL Dump from the given file path.
* #param unknown $ImportDBArray
* $ImportDBArray = array(
'COMPLETE_PATH' => __DIR__ . "\\database_dump.sql"
);
*/
function DB_ImportTable($ImportDBArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->Import($ImportDBArray);
}
/**
*
* #param unknown $multipleFieldsArray
* $multipleFieldsArray = array(
'TABLE_NAME' => 'userinfo',
'ID_LIST' => true ,
'FIELD_DETAILS' => array(
array('Username' => 'bjam123','Password' =>md5('password123'), 'UserType' => 1),
array('Username' => 'ppu12', 'Password' => md5('password1234'), 'UserType' => 2),
array('Username' => 'ppu13', 'Password' => md5('password12345'), 'UserType' => 3),
array('Username' => 'ppu14', 'Password' => md5('password123456'), 'UserType' => 4)
)
);
* #return array containing the insert_id
*/
function DB_InsertMultipleRows($multipleFieldsArray) {
$perform_Database_Operation = DBMgr_Handle();
return $perform_Database_Operation->InsertMR($multipleFieldsArray);
}
/**
* Call this function to perform MSSQL Server specific transactions
* #param unknown $fieldValueArray
* Format is described below:
* array(
* 'Fields'=> 'Field1, Field2, Field3', //Mandatory
* 'Table'=> 'TableName', //Mandatory
* 'clause'=> 'FieldName = FieldValue', //optional
* 'order' => 'FieldName DESC' //optional
* )
clause refers exact/valid values as mysql query accepts.
clause is a condition to filter output. e.g. 'FieldName = DesiredValue' would return entries where FieldName has DesiredValue value only.
Order refers exact/valid values as mysql query accepts and is used to sort data selection. example value can be 'FieldName ASC' or 'FieldName DESC'.
* #param unknown $operationType
* Possible Values - READ, INSERT, UPDATE, DELETE
* #param unknown $outputFormat
* Possible Values - ASSOC, NUM_ARR, NUM_ROWS
*/
function DB_SSRV_Transact($fieldValueArray, $operationType, $outputFormat) {
$perform_Database_Operation = SSRV_Handle();
$perform_Database_Operation->transact($fieldValueArray, $operation, $outputFormat);
}
/*=====================================================Close mysql connection or destroy mysqli object==============================================================*/
/*
* #access public
*/
function DB_Close()
{
$perform_Database_Operation = DBMgr_Handle();
$perform_Database_Operation->closeConnection();
global $perform_Database_Operation;
$perform_Database_Operation = null;
return;
}
?>
Something on these lines:
This is abstraction that uses mysqli extensions of php
CALL THIS FILE : DbMgr.php
<?php
class DBMgr{
private $mysql_Host, $Port, $userName, $passWord, $DatabaseName, $connection, $dbType;
//Constructor function to connect and select database.
/*
* The argument is a assoc array with possible following structure
* array(
* 'source' => 'value is a string. Possible values are Func/Coded', Default value is Func. For Func, the application must have already defined a functiobn name get_DbConfig, which will return assoc array with following structure,
* array(
* 'host' => '',
* 'port' => '',
* 'username' => '',
* 'password' => '',
* 'database' => '',
* 'type' => 'optional. The default value is mysql'
* );
* 'type' => 'mandatory/Required only for Coded Source' Default value is mysql. Other possible values are nssql,postgresql.
* 'host' => 'mandatory/Required only for Coded Source'
* 'port' => 'mandatory/Required only for Coded Source'
* 'username' => 'mandatory/Required only for Coded Source'
* 'password' => 'mandatory/Required only for Coded Source'
* 'database' => 'mandatory/Required only for Coded Source. This is the database name.'
* );
*
*/
function __construct($config)
{
$this->dbType = $config['dbType'];
$this->mysql_Host = $config['host'];
$this->Port = $config['port'];
$this->userName = $config['username'];
$this->passWord = $config['password'];
$this->DatabaseName = $config['database'];
$this->connect_SpecificDatabase();
}
function __destruct() {
$this->connection = null;
}
private function connect_SpecificDatabase(){
if(!isset($this->connection)) {
switch ($this->dbType) {
case 'mysql':
$db = new mysqli('p:'.$this->mysql_Host, $this->userName, $this->passWord, $this->DatabaseName, $this->Port); // Make a connection my MySQL
$this->connection = $db;
break;
case 'postgresql':
// Make a connection to PostgreSQL
$connectionString = "host = '".$this->mysql_Host."' port = '".$this->Port."' dbname = '".$this->DatabaseName."' user='".$this->userName."' password = '".$this->passWord."'";
$db = pg_connect($connection_string);
$this->connection = $db;
break;
}
}
else {
$db = $this->connection;
}
if (!$db)
return "Error: Connection failed '".$this->set_dbError()."'";
}
private function set_dbError($Query, &$DB_OperationError = '')
{
include_once __DIR__.'./../ErrorHandling.php';
$DB_OperationError = "";
global $error_code;
switch ($this->dbType) {
case 'mysql':
$DB_OperationError = mysqli_error($this->connection);
$error_code = mysqli_errno($this->connection);
break;
case 'mssql':
$DB_OperationError = mssql_get_last_message();
break;
case 'postgresql':
$DB_OperationError = pg_last_error($this->connection);
break;
}
ErrorLogging('query: --'.$Query.' -- '.'Error: --'.$DB_OperationError);
}
private function FieldValuePair_ToString($FieldValueArray,$onlyValueString=false)
{
$FieldsAsString = "";
foreach ($FieldValueArray as $FieldName => $value) {
if($FieldsAsString != "")
$FieldsAsString .= ', ';
/* if(strpos($value, '+') > 0 || strpos($value, '-') > 0)
$FieldsAsString .= $FieldName." = ".$value;
*/
if(strpos($value,'\'') !== false || strpos($value,'\"') !== false) {
$value = addslashes($value);
}
if($onlyValueString){
if($value != 'now()')
$FieldsAsString .= "'".$value."'";
else
$FieldsAsString .= $value;
}
else{
if($value != 'now()')
$FieldsAsString .= $FieldName." = '".$value."'";
else
$FieldsAsString .= $FieldName." = ".$value;
}
}
return $FieldsAsString;
}
public function Prepare_Output($output, $output_Format, $keyField_Output = '')
{
$output_Format = strtolower($output_Format); // Convert output_Format to lowercase
if(!is_object($output))
return $output;
elseif($output->num_rows == 0)
return 0;
switch($output_Format)
{
case 'result':
return $output;
break;
case 'num_rows':
return $output->num_rows;
break;
case 'num_arr':
while ($row = $output->fetch_array(MYSQLI_NUM)) {
$output_arr[] = $row;
}
return $output_arr;
break;
case 'assoc':
default:
while ($row = $output->fetch_assoc()) {
if($keyField_Output != '' && isset($row[$keyField_Output])){
$output_arr[strval($row[$keyField_Output])] = $row;
}
else
$output_arr[] = $row;
}
return $output_arr;
break;
}
}
private function Prepare_Query($input_array, $prepare_For)
{
$Query = "";
switch($prepare_For)
{
case 'READ':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "SELECT ";
$Query .= $input_array['Fields'];
$Query .= " FROM ";
$Query .= $input_array['Table'];
if(isset($input_array['clause']) && $input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
if(isset($input_array['order']) && $input_array['order'] != "" && $input_array['order'] !== NULL)
{
$Query .= " ORDER BY ";
$Query .= $input_array['order'];
}
break;
case 'INSERT':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "INSERT INTO ";
$Query .= $input_array['Table'];
$Query .= " SET ";
$Query .= $this->FieldValuePair_ToString($input_array['Fields']);
break;
case 'UPDATE':
if($input_array['Fields'] == "" || $input_array['Fields'] == NULL || $input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "UPDATE ";
$Query .= $input_array['Table'];
$Query .= " SET ";
$Query .= $this->FieldValuePair_ToString($input_array['Fields']);
if(isset($input_array['clause']) && $input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
break;
case 'DELETE':
if($input_array['Table'] == "" || $input_array['Table'] == NULL)
return false;
$Query .= "DELETE FROM ";
$Query .= $input_array['Table']."";
if($input_array['clause'] != "" && $input_array['clause'] !== NULL)
{
$Query .= " WHERE ";
$Query .= $input_array['clause'];
}
break;
case 'INSERT_MR':
$vstring = ""; // Field String
if(is_array($input_array)) {
$tableName = $input_array['TABLE_NAME'];
$input_array = $input_array['FIELD_ARRAY'];
for($i = 0 ;$i < count($input_array); $i++) {
$vstring .= "(" . $this->FieldValuePair_ToString($input_array[$i],true) . ")";
if(! ($i == (count($input_array) - 1))) $vstring .= ",";
}
// Column String
$column_string = implode("," , array_keys($input_array[0])); // Get the column names
$Query = "INSERT INTO ".$tableName." (" . $column_string . ") VALUES ".$vstring.";"; // Form Query String
}
break;
case 'IMPORT_DB':
if(is_array($input_array)) {
$completePathOfSQLFile = "\"" . $input_array['COMPLETE_PATH'];
$Query = "mysql --user" . $this->userName . " --password " . $this->DatabaseName . " < " . $completePathOfSQLFile;
}
break;
case 'EXPORT_DB':
if(is_array($input_array)) {
$TableArray = $input_array['TABLE_LIST'];
$dumpFileName = $input_array['DUMP_FILE_NAME'];
$dQuery = "mysqldump -h ".$this->mysql_Host." --port=".$this->Port." --user=".$this->userName." --password=".$this->passWord;
$dumpFilePath = __DIR__;
$dumpFileName = $dumpFileName == "" ? time().'mysqlDump.sql': $dumpFileName;
if(($TableArray == null) || count($TableArray) == 0 ) {
// Export all tables
$Query = $dQuery . " --databases ".$this->DatabaseName." > ".$dumpFilePath."\\".$dumpFileName;
} else {
$tableNames = "";
// Export selective tables
foreach($TableArray as $k => $k_value) {
$tableNames .= " " . $$TableArray[$k];
}
$Query = $dQuery . " " . $this->DatabaseNames." " . $tableNames . " > \"" . $dumpFilePath."\\".$dumpFileName."\"";
}
}
break;
}
return $Query;
}
public function Read($input_array, $outputFormat, $DataType = "", $keyField_Output = '')
{
$Query = $this->Prepare_Query($input_array, 'READ');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = $this->Prepare_Output($result, $outputFormat, $keyField_Output);
if( ($DataType != "") && (strcasecmp(strtolower($DataType) , 'as_json') == 0) )
$output = json_encode($output);
}
}
return $output;
}
public function Insert($input_array)
{
$Query = $this->Prepare_Query($input_array, 'INSERT');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = mysqli_insert_id($this->connection);
if(!$output)
return true;
}
}
return $output;
}
public function Update($input_array)
{
$Query = $this->Prepare_Query($input_array, 'UPDATE');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = true;
}
}
return $output;
}
public function Delete($input_array)
{
$Query = $this->Prepare_Query($input_array, 'DELETE');
$output = "";
if(!$Query)
$output= 'INVALID';
else
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = true;
}
}
return $output;
}
public function Query($Query, $outputFormat = 'ASSOC', $DataType = "", $keyField_Output = '')
{
$result = $this->connection->query($Query);
if (!$result)
{
$this->set_dbError($Query);
$output = false;
}
else
{
$output = $this->Prepare_Output($result, $outputFormat, $keyField_Output);
if($DataType != "")
$output = json_encode($output);
}
return $output;
}
public function Export($ExportDBArray) {
$Query = $this->Prepare_Query($input_array, 'EXPORT_DB');
$op = '';
$REtVal = '';
$query = 'dir';
$resultQuery = exec($query,$op,$REtVal);
if($resultQuery) return true;
else return false;
}
public function Import($ImportDBArray) {
$Query = $this->Prepare_Query($ImportDBArray, 'IMPORT_DB');
$resultQuery = exec($Query);
}
public function InsertMR($multipleFieldsArray) {
$tableName = $multipleFieldsArray['TABLE_NAME'];
$listOfID = $multipleFieldsArray['ID_LIST'];
$FieldsArray = $multipleFieldsArray['FIELD_DETAILS'];
$input_array = array('FIELD_ARRAY' => $FieldsArray, 'TABLE_NAME' => $tableName);
$Query = $this->Prepare_Query($input_array, 'INSERT_MR');
$result = $this->connection->query($Query); // Run Query
$output = array();
if (!$result) {
$this->set_dbError($Query);
} else {
$insert_id = mysqli_insert_id($this->connection);
if($listOfID) {
for($i=0; $i<count($FieldsArray); $i++) {
$output[$i] = $insert_id;
$insert_id++;
}
} else {
$output[0] = $insert_id;
}
}
return $output;
}
public function closeConnection() {
if(isset($this->connection)) {
mysqli_close($this->connection);
}
}
};
?>

Need small trim() adjustment in complex FormValidator function

I've made the following function, but as it's gotten a bit complex I have no idea how to tackle the problem I have with it now.
Right now the function trims every input before it validates them.
I want it to check if the input type is password first so that it doesn't trim the input before the validation.
public function check($source, $inputs = array()) {
foreach($inputs as $input => $requirements) {
foreach($requirements as $requirement => $reqValue) {
$input = escape($input);
$inputValue = (isset($source[$input])) ? trim($source[$input]) : null;
if($requirement === 'required' && (!isset($inputValue) || empty($inputValue))) {
$this->addError($input, 'required');
//var_dump($this->_errors);
} elseif(!empty($inputValue)) {
switch($requirement) {
case 'min':
if(strlen($inputValue) < $reqValue) {
$this->addError($input, $requirement);
}
break;
case 'max':
if(strlen($inputValue) > $reqValue) {
$this->addError($input, $requirement);
}
break;
case 'match':
if($inputValue != $source[$reqValue]) {
$this->addError($input, $requirement);
}
break;
case 'unique':
$users = $this->_db->query("SELECT * FROM {$reqValue} WHERE {$input} = '{$inputValue}'");
if($users->count()) {
$this->addError($input, $requirement);
}
break;
}
}
}
}
return $this;
}
I use it like:
$validate = new FormValidator();
$validation = $validate->check($_POST, array(
'password' => array(
'type' => 'password', //<-- doesn't work yet in the function
'required' => true,
'min' => 6
),
));
Before your second foreach, check if type exists in $input.
Store it in a temporary variable.
foreach($inputs as $input => $requirements) {
$password = false;
if (array_key_exists('type', $requirements) && $requirements['type'] == 'password') {
$password = false;
}
foreach($requirements as $requirement => $reqValue) {
[...]
... and then check it before you trim:
$inputValue = (isset($source[$input])) ? $source[$input] : null;
if(!$password) {
$inputValue = trim($inputValue);
}

API for dropbox login, access,upload ,delete using cakephp

I have created application in dropbox developer account.
I am using this component class for dropbox .when i trying to login i am getting this error "Please create your dropbox_token and dropbox_token_secret fields in your user model."
<?php
/**
* CAKEPHP DROPBOX COMPONENT v0.4
* Connects Cakephp to Dropbox using cURL.
*
* Copyright (C) 2010 Kyle Robinson Young
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* #author Kyle Robinson Young <kyle at kyletyoung.com>
* #copyright 2010 Kyle Robinson Young
* #license http://www.opensource.org/licenses/mit-license.php The MIT License
* #version 0.4
* #link http://www.kyletyoung.com/code/cakephp_dropbox_component
*
* SETTINGS:
* email/password: To your dropbox account
* cache: Set to name of cache config or false for no cache
*
* When in doubt, clear the cache.
*
* TODO:
* Make sync function smarter (use modified).
*
*/
class DropboxComponent extends Object
{
var $email, $password;
var $loggedin = false;
var $post, $cookie = array();
var $cache = 'default';
var $_wcache = array();
/**
* INITIALIZE
* #param class $controller
* #param array $settings
*/
function initialize(&$controller, $settings=array())
{
if (!extension_loaded('curl'))
{
trigger_error('Dropbox Component: I require the cURL extension to work.');
} // no curl
if (empty($settings['email']) || empty($settings['password']))
{
trigger_error('Dropbox Component: I need your dropbox email and password to login.');
} // email|pass empty
else
{
$this->email = $settings['email'];
$this->password = $settings['password'];
if (isset($settings['cache'])) $this->cache = $settings['cache'];
$this->login();
} // else
} // initialize
/**
* UPLOAD
* Upload a local file to a remote folder.
*
* #param $file
* #param $dir
* #return bool
*/
function upload($from=null, $to='/')
{
if (!file_exists($from)) return false;
$data = $this->request('https://www.dropbox.com/home');
$token = $this->findOnDropbox('token_upload', $data);
if ($token === false) return false;
$this->post = array(
'plain' => 'yes',
'file' => '#'.$from,
'dest' => $to,
't' => $token
);
$data = $this->request('https://dl-web.dropbox.com/upload');
if (strpos($data, 'HTTP/1.1 302 FOUND') === false) return false;
return true;
} // upload
/**
* DOWNLOAD
* Download a remote file to a local folder.
* Both from and to must be a path to a file name.
*
* #param str $from
* #param str $to
* #param str $w
* #return bool
*/
function download($from=null, $to=null, $w=null)
{
$data = $this->file($from, $w);
if (empty($data['data'])) return false;
if (!is_writable(dirname($to))) return false;
if (!$fp = fopen($to, 'w')) return false;
if (fwrite($fp, $data['data']) === false) return false;
fclose($fp);
return true;
} // download
/**
* SYNC
* Compares files from the local and remote folders
* then syncs them.
* Both local and remote must be folders.
*
* TODO:
* Currently only checks if files exists. Doesn't
* check if they are up to date which it should.
*
* #param str $local
* #param str $remote
* #return bool
*/
function sync($local=null, $remote=null)
{
if (!is_dir($local)) return false;
// GET REMOTE FILES
$remote_files = $this->files($remote);
// GET LOCAL FILES
$local_files = array();
$d = dir($local);
while (false !== ($entry = $d->read()))
{
if (substr($entry, 0, 1) == '.') continue;
if (is_dir($local.DS.$entry)) continue;
$local_files[] = $entry;
} // while
$d->close();
// DOWNLOAD FILES
$tmp = array();
foreach ($remote_files as $file)
{
if (empty($file['w'])) continue;
$tmp[] = $file['name'];
if (in_array($file['name'], $local_files)) continue;
$this->download($file['path'].$file['name'], $local.$file['name'], $file['w']);
} // foreach
// UPLOAD FILES
foreach ($local_files as $file)
{
if (in_array($file, $tmp)) continue;
$this->upload($local.$file, $remote);
} // foreach
return true;
} // sync
/**
* FILES
* Returns an array of remote files/folders
* within the given dir param.
*
* #param str $dir
* #return array
*/
function files($dir='/')
{
$dir = $this->escape($dir);
if ($this->cache === false) Cache::delete('dropbox_files_'.$dir, $this->cache);
if (($files = Cache::read('dropbox_files_'.$dir, $this->cache)) === false)
{
$files = array();
$data = $this->request('https://www.dropbox.com/browse_plain/'.$dir.'?no_js=true');
// GET FILES
$matches = $this->findOnDropbox('files', $data);
if ($matches === false) return false;
// GET TYPES
$types = $this->findOnDropbox('file_types', $data);
// GET SIZES
$sizes = $this->findOnDropbox('file_sizes', $data);
// GET MODS
$mods = $this->findOnDropbox('file_modified_dates', $data);
$i = 0;
foreach ($matches as $key => $file)
{
// IF PARENT
if (strpos($file, "Parent folder") !== false) continue;
// GET FILENAME
$found = $this->findOnDropbox('filename', $file);
if ($found === false) continue;
$found = parse_url($found);
$filename = pathinfo($found['path']);
$filename = $filename['basename'];
if (empty($filename)) continue;
// SET DEFAULTS
$path = $dir.$filename;
$type = 'unknown';
$size = 0;
$modified = 0;
// GET TYPE
if (!empty($types[$key])) $type = trim($types[$key]);
// GET SIZE
if (!empty($sizes[$key])) $size = trim($sizes[$key]);
// GET MODIFIED
if (!empty($mods[$key])) $modified = trim($mods[$key]);
// ADD TO FILES
$files[$i] = array(
'path' => urldecode($dir),
'name' => $filename,
'type' => $type,
'size' => $size,
'modified' => $modified
);
// IF FILE OR FOLDER - FILES HAVE W
$w = $this->findOnDropbox('w', $file);
if ($w !== false)
{
$files[$i]['w'] = $w;
// SAVE W FOR LATER
$this->_wcache[$dir.'/'.$filename] = $w;
} // !empty
$i++;
} // foreach
} // Cache::read
if ($this->cache !== false)
{
Cache::write('dropbox_files_'.$dir, $files, $this->cache);
} // if cache
return $files;
} // files
/**
* FILE
* Returns a remote file as an array.
*
* #param str $file
* #param str $w
* #return array
*/
function file($file=null, $w=null)
{
$file = $this->escape($file);
if ($this->cache === false) Cache::delete('dropbox_file_'.$file, $this->cache);
if (($out = Cache::read('dropbox_file_'.$file, $this->cache)) === false)
{
if (empty($w))
{
if (!empty($this->_wcache[$file])) $w = $this->_wcache[$file];
else return false;
} // empty w
$data = $this->request('https://dl-web.dropbox.com/get/'.$file.'?w='.$w);
$type = $this->findOnDropbox('content_type', $data);
$data = substr(stristr($data, "\r\n\r\n"), 4);
if (!empty($type[0])) $type = $type[0];
$out = array(
'path' => $file,
'w' => $w,
'data' => $data,
'content_type' => $type
);
if ($this->cache !== false)
{
Cache::write('dropbox_file_'.$file, $out, $this->cache);
} // if cache
} // Cache::read
return $out;
} // file
/**
* LOGIN
* to dropbox
*
* #return bool
*/
function login()
{
if (!$this->loggedin)
{
if (empty($this->email) || empty($this->password)) return false;
$data = $this->request('https://www.dropbox.com/login');
// GET TOKEN
$token = $this->findOnDropbox('token_login', $data);
if ($token === false) return false;
// LOGIN TO DROPBOX
$this->post = array(
'login_email' => $this->email,
'login_password' => $this->password,
't' => $token
);
$data = $this->request('https://www.dropbox.com/login');
// IF WERE HOME
if (stripos($data, 'location: /home') === false) return false;
$this->loggedin = true;
} // if loggedin
return true;
} // login
/**
* REQUEST
* Returns data from given url and
* saves cookies. Use $this->post and
* $this->cookie to submit params.
*
* #param str $url
* #return str
*/
function request($url=null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// IF POST
if (!empty($this->post))
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->post);
$this->post = array();
} // !empty
// IF COOKIES
if (!empty($this->cookie))
{
$cookies = array();
foreach ($this->cookie as $key => $val)
{
$cookies[] = "$key=$val";
} // foreach
$cookies = implode(';', $cookies);
curl_setopt($ch, CURLOPT_COOKIE, $cookies);
} // !empty
// GET DATA
$data = curl_exec($ch);
// SAVE COOKIES
$cookies = $this->findOnDropbox('cookies', $data);
if ($cookies !== false)
{
$this->cookie = array_merge($this->cookie, $cookies);
} // if cookies
curl_close($ch);
return $data;
} // request
/**
* ESCAPE
* Returns a dropbox friendly str
* for a url
*
* #param str $str
* #return str
*/
function escape($str=null)
{
return str_replace(
array('+','_','%2E','-','%2F','%3A'),
array('%20','%5F','.','%2D','/',':'),
urlencode($str)
);
} // escape
/**
* FIND ON DROPBOX
* A single function for parsing data from
* Dropbox. For easy update when/if Dropbox
* updates their html.
*
* #param str $key
* #param str $data
* #return mixed
*/
function findOnDropbox($key=null, $data=null)
{
switch (strtolower($key))
{
// FIND FILES & NAMES
case 'files':
preg_match_all('/<div.*details-filename.*>(.*?)<\/div>/i', $data, $matches);
if (!empty($matches[0])) return $matches[0];
break;
// FIND FILE TYPES
case 'file_types':
preg_match_all('/<div.*details-icon.*>(<img.*class="sprite s_(.*)".*>)<\/div>/i', $data, $matches);
if (!empty($matches[2])) return $matches[2];
break;
// FIND FILE SIZES
case 'file_sizes':
preg_match_all('/<div.*details-size.*>(.*)<\/div>/i', $data, $matches);
if (!empty($matches[1])) return $matches[1];
break;
// FIND FILE MODIFIED DATES
case 'file_modified_dates':
preg_match_all('/<div.*details-modified.*>(.*)<\/div>/i', $data, $matches);
if (!empty($matches[1])) return $matches[1];
break;
// FIND FILE NAME
case 'filename':
preg_match('/href=[("|\')]([^("|\')]+)/i', $data, $match);
if (!empty($match[1])) return $match[1];
break;
// FIND W
case 'w':
preg_match('/\?w=(.[^"]*)/i', $data, $match);
if (!empty($match[1])) return $match[1];
break;
// FIND CONTENT TYPE
case 'content_type':
preg_match('/Content-Type: .+\/.+/i', $data, $type);
if (!empty($type)) return $type;
break;
// FIND COOKIES
case 'cookies':
preg_match_all('/Set-Cookie: ([^=]+)=(.*?);/i', $data, $matches);
$return = array();
foreach ($matches[1] as $key => $val)
{
$return[(string)$val] = $matches[2][$key];
} // foreach
if (!empty($return)) return $return;
break;
// FIND LOGIN FORM TOKEN
case 'token_login':
preg_match('/<form [^>]*\/login[^>]*>.*?<\/form>/si', $data, $match);
if (!empty($match[0]))
{
preg_match('/<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>/si', $match[0], $match);
if (!empty($match[1])) return $match[1];
} // !empty
break;
// FIND UPLOAD FORM TOKEN
case 'token_upload':
preg_match('/<form [^>]*https\:\/\/dl-web\.dropbox\.com\/upload[^>]*>.*?<\/form>/si', $data, $match);
if (!empty($match[0]))
{
preg_match('/<input [^>]*name="t" [^>]*value="(.*?)"[^>]*>/si', $match[0], $match);
if (!empty($match[1])) return $match[1];
} // !empty
break;
} // switch
return false;
} // findOnDropbox
} // DropboxComponent
?>
Controller code
class DropboxWebserverController extends AppController
{
var $name = 'DropboxWebserver';
var $uses = array();
var $autoRender = false;
var $components = array('Dropbox' => array(
'email' => 'email#gmail.com',
'password' => 'password',
//'cache' => false
));
var $root_folder = '/';
var $default_home = array('index.html', 'index.htm', 'index.php');
/**
* INDEX
*/
function index()
{
$args = func_get_args();
$args = implode('/', $args);
$path = pathinfo($args);
if ($path['dirname'] == ".")
{
$folder = $path['basename'];
$file = '';
} // dirname == .
else
{
$folder = $path['dirname'];
$file = $path['basename'];
} // else
$files = $this->Dropbox->files($this->root_folder.$folder);
//debug($files);
// FIND FILE
foreach ($files as $f)
{
if (strpos($f['type'], 'folder') !== false) continue;
if (empty($f['name'])) continue;
if ($f['name'] == $file)
{
$file = $this->Dropbox->file($this->root_folder.$folder.'/'.$file, $f['w']);
$output = $file['data'];
$content_type = $file['content_type'];
break;
} // name == file
// FIND DEFAULT HOME
if (in_array($f['name'], $this->default_home))
{
$default = $f;
} // in_array
} // foreach
if (!empty($output))
{
header('Content-Type: '.$content_type);
echo $output;
} // !empty
elseif (!empty($default))
{
$file = $this->Dropbox->file($this->root_folder.$folder.'/'.$default['name'], $default['w']);
header('Content-Type: '.$file['content_type']);
echo $file['data'];
} // !empty default
else
{
echo 'Error 404: File Not Found';
} // else
} // index
}
How to login and access drop box account using cakephp

Categories