White Page of Death on submit [duplicate] - validation

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this error mean in PHP?
I am having an issue with the following section of code:
I can get the error notices in the validation but the next step = valid code I just get a white page, Any Ideas?
I have checked the error settings and I have set it in the public_html php.ini file and I still don't get errors
function create_sale()
{
$this->template->append_metadata( js('debounce.js', 'sales') );
$this->template->append_metadata( js('new_sale.js', 'sales') );
// -------------------------------------
// Validation & Setup
// -------------------------------------
$this->load->library('form_validation');
$this->sale_rules[1]['rules'] .= '|callback__check_slug[insert]';
$this->form_validation->set_rules( $this->sale_rules );
foreach($this->sale_rules as $key => $rule)
{
$sale->{$rule['field']} = $this->input->post($rule['field'], TRUE);
}
// -------------------------------------
// Process Data
// -------------------------------------
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) ):
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
}
else:
{
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
endif;
redirect('admin/sales');
}
$this->template->set('sale', $sale)
->build('admin/new');
}

You said that your code is valid but you get a white page.
Most of the time when you get a white page you will simply have an error in your code.
As is the case here:
You suddenly have an endif; in your code which you don't want there.
Enable error reporting please:
Include this code in your bootstrap file:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Remember to disable this in production!
To remove the error change:
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) ):
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
}
else:
{
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
endif;
redirect('admin/sales');
}
to:
if ($this->form_validation->run())
{
if( ! $this->sales_m->insert_new_sale( $sale, $this->user->id ) )
{
$this->session->set_flashdata('notice', lang('sales.new_sale_error'));
} else {
$this->session->set_flashdata('success', lang('sales.new_sale_success'));
}
redirect('admin/sales');
}

You have too many closing curly braces, remove the 'endif' in your script and it should work.

CodeIgniter is notorious for the "white screen of death".
Generally when I've run into it, it's been because of the way they set up their database error handling (it's not good). Database errors aren't handled when $db['default']['db_debug'] is set to FALSE. Any query or connection attempt that fails just returns false. Execution continues after a bad query, which can result in a white screen of death. If you're lucky, you'll get an error message in the logs in some cases, but in most you won't, as the query() function just silently returns false without logging anything.
If you set it to TRUE, then you can be in an even worse position, because any database error will automatically result in CodeIgniter calling it's own show_error() function and generating a 500 HTTP response, and you have no chance of handling it on your own.
This is the most common way to get the WSOD that I'm aware of. I haven't used the 2.0 versions of CI, but it was the case in the 1.7 versions. You may want to try setting db_debug to true in your database.php config file until you find out what's going on.

I suspect that your redirect() is failing to redirect (instead just leaving a blank page sans redirect) for some reason or another. Toss a debug message before it to check.

Related

Laravel 8 - Conditionally remember a value in cache [duplicate]

I'm developing one of my first applications with the Laravel 4 framework (which, by the way, is a joy to design with). For one component, there is an AJAX request to query an external server. The issue is, I want to cache these responses for a certain period of time only if they are successful.
Laravel has the Cache::remember() function, but the issue is there seems to be no "failed" mode (at least, none described in their documentation) where a cache would not be stored.
For example, take this simplified function:
try {
$server->query();
} catch (Exception $e) {
return Response::json('error', 400);
}
I would like to use Cache::remember on the output of this, but only if no Exception was thrown. I can think of some less-than-elegant ways to do this, but I would think that Laravel, being such an... eloquent... framework, would have a better way. Any help? Thanks!
This is what worked for me:
if (Cache::has($key)) {
$data = Cache::get($key);
} else {
try {
$data = longQueryOrProcess($key);
Cache::forever($key, $data); // only stored when no error
} catch (Exception $e) {
// deal with error, nothing cached
}
}
And of course you could use Cache::put($key, $data, $minutes); instead of forever
I found this question, because I was looking for an answer about this topic.
In the meanwhile I found a solution and like to share it here:
(also check out example 2 further on in the code)
<?php
/**
* Caching the query - Example 1
*/
function cacheQuery_v1($server)
{
// Set the time in minutes for the cache
$minutes = 10;
// Check if the query is cached
if (Cache::has('db_query'))
{
return Cache::get('db_query');
}
// Else run the query and cache the data or return the
// error response if an exception was catched
try
{
$query = $server->query(...);
}
catch (Exception $e)
{
return Response::json('error', 400);
}
// Cache the query output
Cache::put('db_query', $query, $minutes);
return $query;
}
/**
* Caching the query - Example 2
*/
function cacheQuery_v2($server)
{
// Set the time in minutes for the cache
$minutes = 10;
// Try to get the cached data. Else run the query and cache the output.
$query = Cache::remember('db_query', $minutes, function() use ($server) {
return $server->query(...);
});
// Check if the $query is NULL or returned output
if (empty($query))
{
return Response::json('error', 400);
}
return $query;
}
I recommend you to use Laravel's Eloquent ORM and/or the Query Builder to operate with the Database.
Happy coding!
We're working around this by storing the last good value in Cache::forever(). If there's an error in the cache update callback, we just pull the last value out of the forever key. If it's successful, we update the forever key.

Server Migration fatal error on contact forms in CodeIgniter

I've been trying to pick my way through this error but I feel like I'm getting nowhere.
We're in the process of migrating a website from one server to another. All pages seem to work on the new site except for the contact form pages which appear to be trying to use 'form_helper.php'. These pages work correctly on the old server but not on the new one. I get an error of:
Fatal error: Call to undefined method CI_Loader::is_loaded() in C:\DATA\XXXX.com\www\application\helpers\form_helper.php on line 1038
Line 1038 of form_helper.php has the following on it:
if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
Any ideas would be GREATLY appreciated as I'm not that familiar with CodeIgniter.
Thanks in advance...
EDIT:
So I've worked out how to seemingly fix it... If I comment out the following code in the form_helper file, the page loads with no error:
/*if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
{
if ( ! isset($CI->$object) OR ! is_object($CI->$object))
{
return $return;
}
return $CI->$object;
}*/
Is this a bad idea? The full function now looks like this:
if ( ! function_exists('_get_validation_object'))
{
function &_get_validation_object()
{
$CI =& get_instance();
// We set this as a variable since we're returning by reference.
$return = FALSE;
/*if (FALSE !== ($object = $CI->load->is_loaded('form_validation')))
{
if ( ! isset($CI->$object) OR ! is_object($CI->$object))
{
return $return;
}
return $CI->$object;
}*/
return $return;
}
}
Make sure you have moved any array values in application/config/autoload.php from $autoload[‘plugins’] to $autoload[‘helpers’] or you will notice stuff break.
is_loaded() function is defined in Code/common.php Make sure the function is in right place.

Magento: ImageCdn bug? (long story)

I have some question related with Magento's free extension OnePica ImageCdn.
A broken image appear in frontend when I uploaded "corrupt image".
Ok, let's start the long story:
I notice it is happened because of ImageCdn extension and "corrupt image".
In some part of ImageCdn's code:
OnePica_ImageCdn_Helper_Image
/**
* In older versions of Magento (<1.1.3) this method was used to get an image URL.
* However, 1.1.3 now uses the getUrl() method in the product > image model. This code
* was added for backwards compatibility.
*
* #return string
*/
public function __toString()
{
parent::__toString();
return $this->_getModel()->getUrl();
}
My question is, anybody know what is the purpose of that code?
I don't understand what is the meaning of their comment above.
I think it is a bug as it always return $this->_getModel()->getUrl();
Is is really a bug or it is just my wrong interpretation?
This is what I've done so far:
I have an image dummy.jpeg
After some investigation, I just realized that is a "corrupt image".
I tested using: <?php print_r(getimagesize('dummy.jpeg')); ?>
Result:
Array
(
[0] => 200
[1] => 200
[2] => 6
[3] => width="200" height="200"
[bits] => 24
[mime] => image/x-ms-bmp
)
Of course I was surprised by the result because it looks good when I open it using Preview (on Mac OSX)
Then I open it using hex editor, the first two bytes is : BM which is BMP's identifier
I tried to upload .bmp image for product -> failed, can not select the image
I asked my colleague to upload it too (on Ubuntu), he was able to change the choices for file type into "any files". When he click "Upload Files", error message shown state that that type of file is not allowed.
What crossed on my mind is: an admin tried to upload .bmp image and failed. Then he rename it into .jpeg and successful. Though I don't get it what kind of images can be renamed without showing broken image logo (out of topic).
Those scenarios trigger an Exception, I'll break down what I've traced.
Trace of the codes:
app/design/frontend/base/default/catalog/product/view/media.phtml
<?php
$_img = '<img id="image" src="'.$this->helper('catalog/image')->init($_product, 'image').'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
From that code, I know that image url is generated using: $this->helper('catalog/image')->init($_product, 'image')
I did Mage::log((string)$this->helper('catalog/image')->init($_product, 'image'));
Result:
http://local.m.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/d/u/dummy.jpeg
.
Mage_Catalog_Helper_Image
public function __toString()
{
try {
if( $this->getImageFile() ) {
$this->_getModel()->setBaseFile( $this->getImageFile() );
} else {
$this->_getModel()->setBaseFile( $this->getProduct()->getData($this->_getModel()->getDestinationSubdir()) );
}
if( $this->_getModel()->isCached() ) {
return $this->_getModel()->getUrl();
} else {
if( $this->_scheduleRotate ) {
$this->_getModel()->rotate( $this->getAngle() );
}
if ($this->_scheduleResize) {
$this->_getModel()->resize();
}
if( $this->getWatermark() ) {
$this->_getModel()->setWatermark($this->getWatermark());
}
Mage::log('pass');
$url = $this->_getModel()->saveFile()->getUrl();
Mage::log('not pass');
}
} catch( Exception $e ) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
The error triggered in $this->_getModel()->saveFile()->getUrl(). In some part of the code, it will eventually reach:
Varien_Image_Adapter_Gd2
private function _getCallback($callbackType, $fileType = null, $unsupportedText = 'Unsupported image format.')
{
if (null === $fileType) {
$fileType = $this->_fileType;
}
if (empty(self::$_callbacks[$fileType])) {
//reach this line -> exception thrown
throw new Exception($unsupportedText);
}
if (empty(self::$_callbacks[$fileType][$callbackType])) {
throw new Exception('Callback not found.');
}
return self::$_callbacks[$fileType][$callbackType];
}
The exception was catched in the previous code:
Mage_Catalog_Helper_Image
public function __toString()
{
...
} catch( Exception $e ) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
...
}
the $url became:
http://local.m.com/skin/frontend/default/default/images/catalog/product/placeholder/image.jpg
So, it should have generated placeholder image right?
(without ImageCdn extension)
No, because
Mage_Catalog_Helper_Image was rewritten by
OnePica_ImageCdn_Helper_Image
public function __toString()
{
parent::__toString(); //the result is http://local.m.com/skin/frontend/default/default/images/catalog/product/placeholder/image.jpg but no variable store/process its value
return $this->_getModel()->getUrl(); //in the end it will return http://local.m.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/d/u/dummy.jpeg
}
In case you all already forgot the question:
Anybody know what is the purpose of that code? I don't understand what is the meaning of their comment above.
Is it really a bug or it is just my wrong interpretation?
No it isn't a bug. It's just legacy support for older Magento systems. I'm wondering, have you ever got around to snoop around earlier versions of magento (as the inline documentation comment references to, < 1.1.3)?
The gist of the matter is before Mage 1.1.3, Mage_Catalog_Helper_Image instances happen to produce URL's from to-string casts e.g.
$image = (some instance of Mage_Catalog_Helper_Image).. ;
$imageUrl = (string) $image;
__toString is probably either protected or private, i'm not sure but what I'm sure is the usual practice is to always code up this Magic Method in order to use it in a class that you are meaning to rewrite something with that expects to use this kind data cast.

Field validation not updating validation message?

I am using the validation.js from http://tetlaw.id.au/view/javascript/really-easy-field-validation to validate user input. This is what I am doing:
Validation.add('someClass', '', function(v, elm){
return myValidateFunction(this, checked.value, $(hID).value, $(wID).value);
});
In myValidateFunction I set the validation message for differnet situations like this:
if(something) {
validator.error = 'my message 1';
return false;
}
if(something else) {
validator.error = 'my message 2';
return false;
}
return true;
Problem is: If the first if was true on the first request the first time, I always get the first validation message (my message 1) on all coming requests, even though the second if was true. I also debugged the JS code and when myValidateFunction returns and I check this in the function call, it has the message I want, its just not displaying it correctly. What am I doing wrong?
Thanks!
I'd double check that 'something' is false on the subsequent calls. If 'something' remains true, then the second if statement will never be reached because you return false from the first if statement and the function exits.
Other than that it's a little hard to debug without some more code to see.

Magento how to stop /checkout/onepage/success/ redirecting

I need to style Magento's order success page /checkout/onepage/success/, but because it redirects when there is no order session I can't refresh the page to check my changes!
Anyone know how I can temporarily stop this redirect for testing purposes?
You can change the /app/code/core/Mage/Checkout/controllers/OnepageController.php file. Modify the successAction, so it looks like this:
public function successAction()
{
/*
$session = $this->getOnepage()->getCheckout();
if (!$session->getLastSuccessQuoteId()) {
$this->_redirect('checkout/cart');
return;
}
$lastQuoteId = $session->getLastQuoteId();
$lastOrderId = $session->getLastOrderId();
$lastRecurringProfiles = $session->getLastRecurringProfileIds();
if (!$lastQuoteId || (!$lastOrderId && empty($lastRecurringProfiles))) {
$this->_redirect('checkout/cart');
return;
}
$session->clear();
*/
$this->loadLayout();
$this->_initLayoutMessages('checkout/session');
Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
$this->renderLayout();
}
Remember to remove the comments when you're done!
You can stop checkout success page redirection after refresh page, for styling and testing purposes, with this below code:
Go to this file:
vendor/magento/module-checkout/Controller/Onepage/Success.php
and comment Out Line No : 22
//$session->clearQuote();
Now you will be able to refresh and debug success page without redirecting.
Don't forget to uncomment after working.
If anyone would be searching same solution for Magento 2 to stop redirecting from success page after page reload - here it is:
Quick and dirty solution for debug:
Open /vendor/magento/module-checkout/Controller/Onepage/Success.php
Comment out code
/* if (!$this->_objectManager->get('Magento\Checkout\Model\Session\SuccessValidator')->isValid()) {
return $this->resultRedirectFactory->create()->setPath('checkout/cart');
}
$session->clearQuote(); */
Right solution using module can be found here https://gielberkers.com/style-checkoutonepagesuccess-page-magento-2/
I suggest to replace your successAction with this code:
/**
* Order success action
*/
public function successAction()
{
$session = $this->getOnepage()->getCheckout();
$session->setLastSuccessQuoteId(20); // <<< add your order entity ID
$session->setLastQuoteId(20); // <<< add your order entity ID
$session->setLastOrderId(20); // <<< add your order entity ID
if (!$session->getLastSuccessQuoteId()) {
$this->_redirect('checkout/cart');
return;
}
$lastQuoteId = $session->getLastQuoteId();
$lastOrderId = $session->getLastOrderId();
$lastRecurringProfiles = $session->getLastRecurringProfileIds();
if (!$lastQuoteId || (!$lastOrderId && empty($lastRecurringProfiles))) {
$this->_redirect('checkout/cart');
return;
}
#$session->clear(); // <<< comment it
$this->loadLayout();
$this->_initLayoutMessages('checkout/session');
Mage::dispatchEvent('checkout_onepage_controller_success_action', array('order_ids' => array($lastOrderId)));
$this->renderLayout();
}
Regards
Whilst the code changes might be desirous, there is an extension specifically for this:
https://www.yireo.com/blog/1672-testing-the-magento-checkout-success-page
Disclosure: I am by no means a coder/dev, so the extension route appeals to me (even though I am comfortable making these changes).
Firefox would let you disable HTTP redirects, but you may have to temporarily hack a controller to let you stay on the page anyway.

Resources