Codeigniter CI_Form_validation undefined function - php

So I am getting the following error.
Fatal error: Call to undefined method CI_Form_validation::error_array() in /home/kmgpdev/public_html/projects/lm/application/controllers/api.php on line 64
Line 63 through 66 reads
if($this->form_validation->run() == false) {
$this->output->set_output(json_encode(['result' => 0, 'error' => $this->form_validation->error_array()]));
return false;
}
If I remove the 64th line it works fine, just no errors are produced.
Also here is my MY_Form_validation.php file I created as a custom library.
class MY_Form_validation extends CI_Form_validation
{
public function __construct($config = array())
{
parent::__construct($config);
}
public function error_array()
{
if(count($this->_error_array > 0)) {
return $this->_error_array;
}
}
}
So it running well in localhost, xampp and when I upload to my ubuntu server then it happend this error, I cannot figure out why this error is coming up. I'm using php 5.5, Any suggestions?
Thanks in advance.

To get the first error message, I have put a utility function like this directly under //system/libraries/Form_validation.php. Otherwise you can use $this->form_validation->error_string() instead of directly picking error array. In most cases, you would want your user to see the error as a string :
function first_error_string($prefix = '', $suffix = '')
{
// No errrors, validation passes!
if (count($this->_error_array) === 0)
{
return '';
}
if ($prefix == '')
{
$prefix = $this->_error_prefix;
}
if ($suffix == '')
{
$suffix = $this->_error_suffix;
}
// Generate the error string
$str = '';
foreach ($this->_error_array as $val)
{
if ($val != '')
{
$str .= $prefix.$val.$suffix;
break;
}
}
return $str;
}

Related

I have Error in my php auto loader file at the time of excel upload

My code is working in local but when I upload my same code in live it gives me
Type: Error
Message: Class 'PHPExcel_Shared_String' not found
Filename: /home/u451055217/domains/barque.online/public_html/demo/application/libraries/PHPExcel/Autoloader.php
Line Number: 11
my auto load file:
<?php
PHPExcel_Autoloader::register();
if (ini_get('mbstring.func_overload') & 2) {
throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
}
PHPExcel_Shared_String::buildCharacterSets();
class PHPExcel_Autoloader
{
public static function register()
{
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true);
} else {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'));
}
}
public static function load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
return false;
}
$pClassFilePath = PHPEXCEL_ROOT .
str_replace('_', DIRECTORY_SEPARATOR, $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
return false;
}
require($pClassFilePath);
}
}
I do not know where I am wrong in my code.
I uploaded the same code of my local.

Getting PHPUNit code coverage of simple '} else {' line

I can't get PHPUnit's Code Coverage tool to mark this else statement as covered even though it must be or the following line could not be covered. Elsewhere in the same class another line that contains only } else { is correctly marked as covered.
if (is_string($externalId) && $externalId != '') {
$sitesIds[] = $externalId;
} else if ($regionName != null && $regionName != '') {
$sitesIds = $this->sitesService->getSites($regionName);
if (!is_array($sitesIds) || count($sitesIds) == 0) {
throw new \Exception(self::NO_MATCHING_REGION, '404');
}
} else {
throw new \Exception(self::BAD_REQUEST.'. Should specify station or region', '400');
}
Since else doesn't actually do anything (it can be considered just a label) it won't get covered.
Your problem is that you don't have a test where (is_string($externalId) && $externalId != '') is false, ($regionName != null && $regionName != '') is true and (!is_array($sitesIds) || count($sitesIds) == 0) is false. (You might want to be more specific by using not exactly equal to !== instead of not equal to !=: ($externalId !== '') & ($regionName !== null && $regionName !== ''))
If you can get $sitesIds = $this->sitesService->getSites($regionName); to return an array with at least one element, your red line will be covered and turn green.
The red line is telling you that the closing brace } before the else is technically reachable, but you have no tests that cover it.
With slightly modified source:
class A
{
const NO_MATCHING_REGION = 1;
const BAD_REQUEST = 2;
private $sitesService = ['a' => ['AA'], 'b'=>12];
public function a($externalId, $regionName)
{
$sitesIds = [];
if (is_string($externalId) && $externalId != '') {
$sitesIds[] = $externalId;
} else {
if ($regionName != null && $regionName != '') {
$sitesIds = $this->sitesService[$regionName];
if (!is_array($sitesIds) || count($sitesIds) == 0) {
throw new \Exception(self::NO_MATCHING_REGION, '404');
}
} else {
throw new \Exception(self::BAD_REQUEST.'. Should specify station or region', '400');
}
}
return $sitesIds;
}
}
The test
class ATest extends \PHPUnit_Framework_TestCase
{
/**
* #dataProvider data
*/
public function testOk($id, $reg, $res)
{
$a = new A;
$r = $a->a($id, $reg);
$this->assertEquals($res, $r);
}
public function data()
{
return [
['a', 1, ['a']],
[1,'a', ['AA']]
];
}
/**
* #dataProvider error
* #expectedException \Exception
*/
public function testNotOK($id, $reg)
{
$a = new A;
$a->a($id, $reg);
}
public function error()
{
return [
[1,'b'],
[1,null]
];
}
}
Covers the else line:
PHP 5.6.15-1+deb.sury.org~trusty+1
PHPUnit 4.8.21

Can't set error message in Code Igniter 3 when using callback function

I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.

How to implement method pointers in PHP

Is there a way to implement method pointers in PHP?
I keep getting the following error:
Fatal error: Call to undefined function create_jpeg() in /Users/sky/Documents/images.php on line 175
This is line 175:
if ($this->ImageType_f[$pImageType]($pPath) != 0)
class CImage extends CImageProperties
{
private $Image;
private $ImagePath;
private $ImageType;
private function create_jpeg($pFilename)
{
if (($this->Image = imagecreatefromjepeg($pFilename)) == false)
{
echo "TEST CREATION JPEG\n";
echo "Error: ".$pFilename.". Creation from (JPEG) failed\n";
return (-1);
}
return (0);
}
private function create_gif($pFilename)
{
if (($this->Image = imagecreatefromgif($pFilename)) == false)
{
echo "Error: ".$pFilename.". Creation from (GIF) failed\n";
return (-1);
}
return (0);
}
private function create_png($pFilename)
{
if (($this->Image = imagecreatefrompng($pFilename)) == false)
{
echo "Error: ".$pFilename.". Creation from (PNG) failed\n";
return (-1);
}
return (0);
}
function __construct($pPath = NULL)
{
echo "Went through here\n";
$this->Image = NULL;
$this->ImagePath = $pPath;
$this->ImageType_f['JPEG'] = 'create_jpeg';
$this->ImageType_f['GIF'] = 'create_gif';
$this->ImageType_f['PNG'] = 'create_png';
}
function __destruct()
{
if ($this->Image != NULL)
{
if (imagedestroy($this->Image) != true)
echo "Failed to destroy image...";
}
}
public function InitImage($pPath = NULL, $pImageType = NULL)
{
echo "pPath: ".$pPath."\n";
echo "pImgType: ".$pImageType."\n";
if (isset($pImageType) != false)
{
if ($this->ImageType_f[$pImageType]($pPath) != 0)
return (-1);
return (0);
}
echo "Could not create image\n";
return (0);
}
}
Just call the method you need with $this->$method_name() where $method_name is a variable containing the method you need.
Also it is possible using call_user_func or call_user_func_array
What is callable is described here: http://php.net/manual/ru/language.types.callable.php
So assuming $this->ImageType_f['jpeg']' must be callable: array($this, 'create_jpeg').
Alltogether: call_user_func($this->ImageType_f[$pImageType], $pPath) is the way to do it.
Or if $this->ImageType_f['jpeg'] = 'create_jpeg':
$this->{$this->ImageType_f['jpeg']]($pPath);
Some documentation on functions I mentioned here:
http://us2.php.net/call_user_func
http://us2.php.net/call_user_func_array
Your problem is is line:
if ($this->ImageType_f[$pImageType]($pPath) != 0)
-since $this->ImageType_f[$pImageType] will result in some string value, your call will be equal to call of global function, which does not exists. You should do:
if ($this->{$this->ImageType_f[$pImageType]}($pPath) != 0)
-but that looks tricky, so may be another good idea is to use call_user_func_array():
if (call_user_func_array([$this, $this->ImageType_f[$pImageType]], [$pPath]) != 0)
I think you need to use this function call_user_func
In your case call will looks like
call_user_func(array((get_class($this), ImageType_f[$pImageType]), array($pPath));

Error When Calling Function

I searched forever trying to find an answer, but was ultimately stumped. I've been writing code to allow multiple bots to connect to a chat box. I wrote all the main code and checked it over to make sure it was all okay. Then when I got to calling the function needed to make it work, it gave me an error saying:
Notice: Undefined variable: ip in C:\wamp\www\BotRaid.php on line 40
And also an error saying:
Fatal Error: Cannot access empty property in C:\wamp\www\BotRaid.php
on line 40
( Also a screenshot here: http://prntscr.com/ckz55 )
<?php
date_default_timezone_set("UCT");
declare(ticks=1);
set_time_limit(0);
class BotRaid
{
public $ip="174.36.242.26";
public $port=10038;
public $soc = null;
public $packet = array();
##############################
# You can edit below this #
##############################
public $roomid="155470742";
public $userid = "606657406";
public $k = "2485599605";
public $name="";
public $avatar=;
public $homepage="";
##############################
# Stop editing #
##############################
public function retry()
{
$this->connect($this->$ip,$this->$port); //Line 40, where I'm getting the error now.
$this->join($this->$roomid);
while($this->read()!="DIED");
}
public function connect($ip, $port)
{
if($this->$soc!=null) socket_close($this->$soc);
$soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$this->$soc)$this->port();
if(!socket_connect($this->$soc,$this->$ip,$this->$port))$this->port();
}
public function port()
{
$this->$port++;
if($this->$port>10038) $this->$port=10038;
$this->retry();
}
public function join($roomid)
{
$this->send('<y m="1" />');
$this->read();
$this->send('<j2 q="1" y="'.$this->$packet['y']['i'].'" k="'.$this->$k.'" k3="0" z="12" p="0" c"'.$roomid.'" f="0" u="'.$this->$userid.'" d0="0" n="'.$this->$name.'" a="'.$this->$avatar.'" h="'.$this->$homepage.'" v="0" />');
$this->port();
$this->$roomid;
}
public function send($msg)
{
echo "\n Successfully connected.";
socket_write($this->$soc, $this->$msg."\0", strlen($this->$msg)+1);
}
public function read($parse=true)
{
$res = rtrim(socket_read($this->$soc, 4096));
echo "\nSuccessfully connected.";
if(strpos(strtolower($res), "Failed"))$this->port();
if(!$res) return "DIED";
$this->lastPacket = $res;
if($res{strlen($res)-1}!='>') {$res.=$this->read(false);}
if($parse)$this->parse($res);
return $res;
}
public function parse($packer)
{
$packet=str_replace('+','#più#',str_replace(' ="',' #=#"',$packet));
if(substr_count($packet,'>')>1) $packet = explode('/>',$packet);
foreach((Array)$packet as $p) {
$p = trim($p);
if(strlen($p)<5) return;
$type = trim(strtolower(substr($p,1,strpos($p.' ',' '))));
$p = trim(str_replace("<$type",'',str_replace('/>','',$p)));
parse_str(str_replace('"','',str_replace('" ','&',str_replace('="','=',str_replace('&','__38',$p)))),$this->packet[$type]);
foreach($this->packet[$type] as $k=>$v) {
$this->packet[$type][$k] = str_replace('#più#','+',str_replace('#=#','=',str_replace('__38','&',$v)));
}
}
}
}
$bot = new BotRaid; //This is where I had the error originally
$bot->retry();
?>
Line 40 is below the "Stop Editing" line. Anyone have any suggestions? Or perhaps need me to clear some things up?
You are accessing the properties of the class incorrectly.
The line:
$this->connect($this->$ip,$this->$port);
Should be:
$this->connect($this->ip, $this->port);
Since there was no local variable called $ip, your expression was evaluating to $this-> when trying to access the property since PHP lets you access properties and functions using variables.
For example, this would work:
$ip = 'ip';
$theIp = $this->$ip; // evaluates to $this->ip
// or a function call
$method = 'someFunction';
$value = $this->$method(); // evaluates to $this->someFunction();
You will have to change all the occurrences of $this->$foo with $this->foo since you used that notation throughout the class.
As noted in the comment by #Aatch, see the docs on variable variables for further explanation. But that is what you were running into accidentally.

Categories