Is there a way to get the last error in php4 - error-handling

PHP 5 has error_get_last. Is there any way to completely or at least partially replicate the same functionality in PHP4.3?

Ripped from the PHP manual (courtesy of php at joert dot net):
<?php
if( !function_exists('error_get_last') ) {
set_error_handler(
create_function(
'$errno,$errstr,$errfile,$errline,$errcontext',
'
global $__error_get_last_retval__;
$__error_get_last_retval__ = array(
\'type\' => $errno,
\'message\' => $errstr,
\'file\' => $errfile,
\'line\' => $errline
);
return false;
'
)
);
function error_get_last() {
global $__error_get_last_retval__;
if( !isset($__error_get_last_retval__) ) {
return null;
}
return $__error_get_last_retval__;
}
}
?>

Yes it is, but you will have to do some programming, you need to attach error handler
$er_handler = set_error_handler("myErrorHandler");
but before this you need to write your "myErrorHandler"
function myErrorHandler($errNumber, $errString, $errFile, $errLine)
{
/*now add it to session so you can access it from anywhere, or if you have class with the static variable you can save it there */
$_SESSION["Error.LastError"] = $errNumber . '<br>' . $errString . '<br>' . $errFile . '<br>' . $errLine;
}
Now when error is occured you can get it by
if(isset($_SESSION["Error.LastError"]))
$str = $_SESSION["Error.LastError"];
now to replicate your method you need to create function
function get_last_error()
{
$str = "";
if(isset($_SESSION["Error.LastError"]))
$str = $_SESSION["Error.LastError"];
return $str;
}

Related

How to validate files with Yii2 getInstancesByName uploaded from API?

I'm working on a mobile app, the Yii2 is used as backend API, the problem that I can not validate the uploaded files, any idea how I can do it?
public static function uploadPicture ($vid) {
$model = new Pictures ();
$model->load(\Yii::$app->getRequest()->getBodyParams(), '');
$model->vid_image = \yii\web\UploadedFile::getInstancesByName('vid_image');
$imageDir = Yii::$app->params[ 'uploadDir' ];
//if ( $model->validate() AND !empty($model->vid_image) ) { //does not work
if ( !empty($model->vid_image) ) {
foreach ( $model->vid_image as $images => $image) {
$model->name = "t_" . time() . "_i_" . uniqid() . '.' . $image->extension;
$model->vid = $vid;
echo $image->hasError;//return empty
//Yii::$app->end();
//if ( $model->save() and $model->validate() ) { // does not work
if(1==1 and $model->validate()){ // $model->validate() always empty!!!
$image->saveAs($imageDir . '/' . $model->name);
Yii::$app->getResponse()->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
Yii::info("[pic.21] image: " . $model->name . " uploaded to: " . $imageDir, __METHOD__);
} elseif ( $model->hasErrors() ) {
$response = \Yii::$app->getResponse();
$response->setStatusCode(500);
throw new ServerErrorHttpException('Failed to create the object for unknown reason. [APIx001]');
}
}
}
return $model;
}
The files are uploaded without validation.
Thanks,

PHP Slim Framework : Slim Application Error when using PDO

I want to use PDO with my Slim php application. When I use a simple select query and send json data to Twig page. But I keep getting this error : Slim Application Error
This is my code :
<?php
require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App;
$container = $app->getContainer();
$container['view'] = function ($container) {
$templates = __DIR__ . '/templates/';
$cache = __DIR__ . '/tmp/views/';
$view = new Slim\Views\Twig($templates, array('cache' => false));
return $view;
};
$container['db'] = function ($container) {
$pdo = new PDO("mysql:host=localhost;DBName=dbsat", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
$app->get('/', function ($request, $response) {
$sth = $this->db->prepare("SELECT * from client where id=:id");
$sth->bindParam("id", 1);
$sth->execute();
$todos = json_encode($sth->fetchAll());
$data = ['user' => $todos];
return $this->view->render($response, 'home.twig', $data);
});
$app->get('/login', function ($request, $response) {
return $this->view->render($response, 'login.twig');
});
$app->run();
?>
The problem appears at this line :
$sth = $this->db->prepare("SELECT * from client where id=:id");
Problem solved. It was caused by binding param
Message: Cannot pass parameter 2 by reference
By knowing the error I have fixed it. Thank you all.

Add Pre default text in phalcon flash messages

In phalcon default flash messaging service only provide with default error div.
<div class="alert alert-warning">Our message</div>
But i want to add something inside div box like this.
<div class="alert alert-warning"> <button class="close">x</button> Our Message </div>
However, phalcon we are only allow to set only class of each message as per my knowledge.
$di->set('flash', function () {
return new FlashSession([
'error' => 'alert alert-danger alert-dismissible',
'success' => 'alert alert-success alert-dismissible',
'notice' => 'alert alert-info alert-dismissible',
'warning' => 'alert alert-warning alert-dismissible'
]);
});
Is there any configuration or any other way to add that close button on every message. I want something like
message = '<button class="close-btn">x</button>'+message
However i don't want to add this close button on every flash message because in future may be i need to change the class of close button so that in that case i need to change in all from the project.
You can do this by extending the Phalcon\FlashSession class and overriding the outputMessage() method, or by creating your own flash component to output the HTML you desire. Example of a custom flash component is below, we use a similar class when we develop with Falcon, this component assumes the existence of a session component in the DI.
This is untested but the code in principle would give you the ability to add a close button to the output HTML, or you can set specific HTML content for each message type in the relevant methods (error, success, warning, info).
Example usage:
// settings messages in your controllers / components
// 2nd param defines a position
$this->flashMessage->error('Something is bad!', 'form_top');
$this->flashMessage->success('Something is right!');
$this->flashMessage->info('Something is interesting!');
$this->flashMessage->warning('Something is worrying!');
// rendering messages in your views
// 1st param will render messages for a specific position if a position was set
$this->flashMessage->render();
$this->flashMessage->render('form_top');
Example class:
class FlashMessage extends Phalcon\Mvc\User\Component
{
/**
* #var array
**/
public $classmap = array();
/**
* Sets defaults for the class map (optional)
*
* #param array $classmap
**/
public function __construct($classmap = array()) {
// -- set the defaults
$this->classmap = array(
'error' => 'flash_message-error',
'success' => 'flash_message-success',
'info' => 'flash_message-info',
'warning' => 'flash_message-warning'
);
// -- set new class map options (also optional)
if (!empty($classmap)) {
foreach ($classmap as $key => $value) {
$this->classmap[$key] = $value;
}
}
}
/**
* error(), success(), info(), warning()
* Sets the flash messages
*
* #param string message
* #param string position
* #return string
**/
public function error($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['error'] . '">
' . $message . '
</div>
');
}
public function success($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['success'] . '">
' . $message . '
</div>
');
}
public function info($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['info'] . '">
' . $message . '
</div>
');
}
public function warning($message, $position = '')
{
$this->session->flashMessage = array(
'position' => $position,
'message' => '<div class="' . $this->classmap['warning'] . '">
' . $message . '
</div>
');
}
/**
* Check if theres messages in the session to render
*
* #param string $position
* #return bool
**/
public function hasMessage($position = null)
{
if (isset($this->session->flashMessage) && !empty($position)) {
return $this->session->flashMessage['position'] == $position ? true : false ;
} else {
return $this->session->flashMessage ? true : false ;
}
}
/**
* Renders the flash message
*
* #param string $position
* #return string
**/
public function render($position = null)
{
// -- store the message locally
$message = $this->session->flashMessage;
// -- check if there is in fact a flashed message
if (empty($message))
return;
// -- then remove from the session
$this->session->remove('FlashMessage');
// -- if no position the just return the message
if (is_null($position)) {
return $message['message'];
// -- else return the requested position
} elseif ($position == $message['position']) {
return $message['message'];
}
}
}
I am using something like this, you can extend it like you want. But this is just the gist of how it works:
class Messenger extends Component
{
protected static $_messageCloseHtml = '×';
/**
* #param array|string $messages
*/
public static function flashError($messages)
{
$messages = !is_array($messages) ? [$messages] : $messages;
foreach ($messages as $message) {
\Phalcon\Di::getDefault()->get('flashSession')->error(self::_getBody($message));
}
}
/**
* #param string $message
* #return string
*/
protected static function _getBody($message)
{
return self::$_messageCloseHtml . $message;
}
}
For every message, you can add some HTML code to the message.
My flashError is for the error messages. You can add the same method code for the warning, info and success.
So basically you extend the (existing) FlashSession and when assigning the messages you call a global method which adds additional text or html to your message.

Magento API, Return Orders with NULL values

Using the magento api version 1 and soap.
Need to return all orders with 'coupon_code'=> NULL
The call I'm attempting:
$order_listAR = $proxy->call($sessionId, 'sales_order.list', array(array('coupon_code'=>array('null'=>'null'))));
The ouput I want returned is this:
array(237) {
["state"]=>
string(8) "complete"
["status"]=>
string(8) "complete"
["coupon_code"]=> NULL
So far this seems to work properly, but I'm not sure if ('null'=>'null') is the proper way to find NULL values in the array. Can someone explain why this works, and, or if this is the correct syntax? I don't have any margin for error on this.
Yes, the syntax you use is correct to filter against null.
array(
'coupon_code' => array(
'null' => 'this_value_doesnt_matter'
)
)
Magento maps* the API method sales_order.list to Mage_Sales_Model_Order_Api::items().
public function items($filters = null)
{
:
$collection = Mage::getModel("sales/order")->getCollection()
:
if (is_array($filters)) {
try {
foreach ($filters as $field => $value) {
if (isset($this->_attributesMap['order'][$field])) {
$field = $this->_attributesMap['order'][$field];
}
$collection->addFieldToFilter($field, $value);
}
} catch (Mage_Core_Exception $e) {
$this->_fault('filters_invalid', $e->getMessage());
}
}
:
}
The items() method uses a Mage_Sales_Model_Resource_Order_Collection to fetch the orders for the API call. That collection is based on Varien_Data_Collection_Db, so
$collection->addFieldToFilter($field, $value)
from above essentially does call
Varien_Data_Collection_Db::addFieldToFilter()
If you follow the latter, you'll hit Varien_Db_Adapter_Pdo_Mysql::prepareSqlCondition() in the end, params being
$fieldName = 'coupon_code'
$condition = array('null' => 'null')
Excerpt of that method:
public function prepareSqlCondition($fieldName, $condition)
{
$conditionKeyMap = array(
'eq' => "{{fieldName}} = ?",
:
'notnull' => "{{fieldName}} IS NOT NULL",
'null' => "{{fieldName}} IS NULL",
:
'sneq' => null
);
:
$query = '';
if (is_array($condition)) {
:
$key = key(array_intersect_key($condition, $conditionKeyMap));
if (isset($condition['from']) || isset($condition['to'])) {
:
} elseif (array_key_exists($key, $conditionKeyMap)) {
$value = $condition[$key];
if (($key == 'seq') || ($key == 'sneq')) {
:
}
$query = $this->_prepareQuotedSqlCondition($conditionKeyMap[$key], $value, $fieldName);
} else {
:
}
}
:
}
In your case _prepareQuotedSqlCondition() will be called with
$text = '{{fieldName}} IS NULL'
$value = 'null'
$fieldName = 'coupon_code'
which will result in $query = 'coupon_code IS NULL'.
If you take a closer look at the conversion method
protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
{
$sql = $this->quoteInto($text, $value);
$sql = str_replace('{{fieldName}}', $fieldName, $sql);
return $sql;
}
you'll also see, why the value of the 'null' => 'null' key/value pair does not matter at all. That's because $text will be '{{fieldName}} IS NULL', i.e. not containing any binding ?.
Hence, there's nothing to replace for _quoteInto()^^
* see app/code/core/Mage/Sales/etc/api.xml

CakePHP Auth Component Using 2 Tables

CakePHP Version 1.2.5
I would like a single user to have multiple email addresses.
I would like a single user to have a single password.
I would like users to log in using any of their multiple email addresses and their single password.
I have created a users table with an id and a password field.
I have created a user_email_addresses table with an id field a user_id field and an email_address field.
Question:
How do I modify the auth component minimally to look for the "username" in this case, "email_address", in the user_email_addresses table and the "password" in the users table?
Seems as though modifying the identify method in the auth component might do it. But I think modifying the auth component directly is a bad idea - any ideas on how to extend and still possibly modify the identify method? http://cakebaker.42dh.com/2009/09/08/extending-cakephps-core-components/ or possibly nominate a different authenticate object?
Starting line 774:
function identify($user = null, $conditions = null) {
if ($conditions === false) {
$conditions = null;
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
if (empty($user)) {
$user = $this->user();
if (empty($user)) {
return null;
}
} elseif (is_object($user) && is_a($user, 'Model')) {
if (!$user->exists()) {
return null;
}
$user = $user->read();
$user = $user[$this->userModel];
} elseif (is_array($user) && isset($user[$this->userModel])) {
$user = $user[$this->userModel];
}
if (is_array($user) && (isset($user[$this->fields['username']]) || isset($user[$this->userModel . '.' . $this->fields['username']]))) {
if (isset($user[$this->fields['username']]) && !empty($user[$this->fields['username']]) && !empty($user[$this->fields['password']])) {
if (trim($user[$this->fields['username']]) == '=' || trim($user[$this->fields['password']]) == '=') {
return false;
}
$find = array(
$this->userModel.'.'.$this->fields['username'] => $user[$this->fields['username']],
$this->userModel.'.'.$this->fields['password'] => $user[$this->fields['password']]
);
} elseif (isset($user[$this->userModel . '.' . $this->fields['username']]) && !empty($user[$this->userModel . '.' . $this->fields['username']])) {
if (trim($user[$this->userModel . '.' . $this->fields['username']]) == '=' || trim($user[$this->userModel . '.' . $this->fields['password']]) == '=') {
return false;
}
$find = array(
$this->userModel.'.'.$this->fields['username'] => $user[$this->userModel . '.' . $this->fields['username']],
$this->userModel.'.'.$this->fields['password'] => $user[$this->userModel . '.' . $this->fields['password']]
);
} else {
return false;
}
$model =& $this->getModel();
$data = $model->find(array_merge($find, $conditions), null, null, 0);
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
} elseif (!empty($user) && is_string($user)) {
$model =& $this->getModel();
$data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
}
if (!empty($data)) {
if (!empty($data[$this->userModel][$this->fields['password']])) {
unset($data[$this->userModel][$this->fields['password']]);
}
return $data[$this->userModel];
}
return null;
}
AuthComponent::identify() takes two parameters, $user and $conditions
if ($conditions === false) {
$conditions = null;
} elseif (is_array($conditions)) {
$conditions = array_merge((array)$this->userScope, $conditions);
} else {
$conditions = $this->userScope;
}
Looking at the above snippet, if you pass false as the $conditions, the method will execute with no model conditions.
Also, looking at the rest of the code, if you pass a $user value of type string, it won't execute most of the user-related code until it gets here:
} elseif (!empty($user) && is_string($user)) {
$model =& $this->getModel();
$data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
if (empty($data) || empty($data[$this->userModel])) {
return null;
}
}
Here it runs Model::escapeField(), with no parameters, which returns an escaped version of User.id (by default) and maps this field to the string that was passed in. It then merges this with the $conditions array and performs a Model::find().
It should be safe to say that if the string is the user's ID and there are no conditions it will find the person with that ID every time.
As such, you should be able to extend AuthComponent to do what you want like so:
// app/controllers/components/app_auth.php
<?php
App::import('Component', 'Auth');
class AppAuthComponent extends AuthComponent {
/**
* Custom user identification
*/
function identify($user=null, $conditions=null) {
// get the model AuthComponent is configured to use
$model =& $this->getModel(); // default is User
// do a query that will find a User record when given successful login data
$user = $model->find('first', array('conditions' => array(
'EmailAddress.' . $this->fields['username'] => $user[$this->userModel][$this->fields['username']],
'User.' . $this->fields['password'] => $user[$this->userModel][$this->fields['password']],
));
// return null if user invalid
if (!$user) {
return null; // this is what AuthComponent::identify would return on failure
}
// call original AuthComponent::identify with string for $user and false for $conditions
return parent::identify($user[$this->userModel][$model->primaryKey], false);
}
}
?>
You will have to replace all references to Auth with AppAuth in your application unless you follow this handy tip (the approach in the comments is nice).