I have been working on a little MVC project to assist in my self-learning and I have come across an issue that completely baffled me. I made a blog section in this MVC-ish system and pulled user permissions from an ACL with no problem whatsoever.
I moved onto creating a member section and as soon as i added any permissions checking I get the following error from Chrome:
No data received
Unable to load the web page because the server sent no data.
Here are some suggestions:
Reload this web page later.
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
I thought it was weird, so I double checked my error logs and nothing had shown up. So I decided to copy and paste the working blog code into the member file, reloaded and i got the EXACT same error, the only difference between the two files right now is the file name and the class name.
Here is the Blog code:
<?php
class blog extends frontController {
public $model;
public $user;
public function __construct()
{
parent::__construct();
$this->model = $this->autoload_model();
$this->user = $this->load_user();
$this->user->getUserRoles();
}
public function index()
{
//Will only list the latest post ;)
if(!$this->user->hasPermission('blog_access'))
{
$array = $this->model->list_posts();
if(empty($array))
{
$this->variables(array(
'site_title' => 'View Blog Posts',
'post_title' => 'Sorry but there are no posts to display'
));
} else {
$this->variables(array(
'site_title' => 'View Blog Posts',
'list' => $array[0],
'post_title' => $array[0]['entry_title'],
'link' => str_replace(' ', '_',$array[0]['entry_title']),
));
}
} else {
$this->variables(array(
'site_title' => 'Error :: Design Develop Realize',
'body' => 'Sorry, but you do not have permission to access this',
));
}
$this->parse('blog/list', $this->toParse);
}
This is the member file:
<?php
class member extends frontController {
public $model;
public $user;
public function __construct()
{
parent::__construct();
$this->model = $this->autoload_model();
$this->user = $this->load_user();
$this->user->getUserRoles();
}
public function index()
{
//Will only list the latest post ;)
if(!$this->user->hasPermission('blog_access'))
{
//$array = $this->model->list_posts();
if(empty($array))
{
$this->variables(array(
'site_title' => 'Design Develop Realize :: View Blog Posts',
'post_title' => 'Sorry but there are no posts to display'
));
} else {
$this->variables(array(
'site_title' => 'Design Develop Realize :: View Blog Posts',
'list' => $array[0],
'post_title' => $array[0]['entry_title'],
'link' => str_replace(' ', '_',$array[0]['entry_title']),
));
}
} else {
$this->variables(array(
'site_title' => 'Error :: Design Develop Realize',
'body' => 'Sorry, but you do not have permission to access this',
));
}
$this->parse('blog/list', $this->toParse);
}
In the member class, if I comment out $this->user = $this->load_user(); then the error disappears!!!
Just for reference here is that function:
protected function load_user()
{
if(!$this->loader->loaded['acl'])
{
$this->loader->loadCore('acl');
}
return $this->loader->loaded['acl'];
}
Any help or suggestions would be appreciated as I am stumped!
PS yes I do have error reporting set to cover everything and no it does not log anything!
EDIT: Because all files go through index.php I have placed the error reporting there:
<?php
error_reporting(E_ALL);
ini_set('date.timezone', "Europe/London");
require_once('system/library/loader.php');
$loader = new loader();
$loader->loadCore(array('frontController', 'routing'));
EDIT 2: loadCore() is below
public function loadCore($toLoad, $params = false)
{
//important task first, check if it is more then 1 or not
if(is_array($toLoad))
{
//more then one so lets go to the task!
foreach($toLoad as $file)
{
if(file_exists('system/library/' . $file . '.php'))
{
require_once('system/library/' . $file . '.php');
if($params)
{
$this->loaded[$file] = new $file($params);
} else {
$this->loaded[$file] = new $file;
}
} else {
trigger_error("Core File $file does not exist");
}
}
} else {
//Phew, less work, it is only one!
if(file_exists('system/library/' . $toLoad . '.php'))
{
require_once('system/library/' . $toLoad . '.php');
if($params)
{
echo(__LINE__); exit;
$this->loaded[$toLoad] = new $toLoad($params);
} else {
$this->loaded[$toLoad] = new $toLoad;
}
}
}
}
Update: I modified loadCore so that if it was the acl being called it would use a try...catch() and that has not helped as it will not display an error just the same chrome and IE pages
Update 2: I have spoken with my host and it seems that everytime this error occurs, apache logs the following (not sure why I cannot see it in my copy of the logs!)
[Wed Feb 22 08:07:11 2012] [error] [client 93.97.245.13] Premature end
of script headers: index.php
You have commented out
//$array = $this->model->list_posts();
So now array is null and you are trying to use
'list' => $array[0],
'post_title' => $array[0]['entry_title'],
which definitely will generate an error.
EDIT:-
I see you have
'body' => 'Sorry, but you do not have permission to access this' , )); }
That is in second else which is a syntax error. and generates an output. If you have enabled, compress output in CI, that will cause this error.
"Premature end of script headers" are internal server errors. Which generally occurs when script breaks and does not send any HTTP headers before send the error messages. There might be several causes to this.
One might be output buffering. May be the server you are using buffers the output by default. I will suggest turning off the output_buffering using output_buffering = off on php.ini [docs here].
Make sure you are sending correct HTTP headers also
print "Content-type: text/html\n\n";
There are few more suggestion on this link.
To learn more about this error, go here.
Hope it helps
I'd be interested in seeing what's inside the loadCore function.
Have you used error_log anywhere? It might help shed some light on the issue.
Have you tested this page in different browsers? Googled your error, and it's indicating that it may be chrome specific?
Your statement that commenting out the loadCore('acl') is interesting, so obviously I would start there. You're sure that it is getting the system/library/acl.php page via the loader? Aka, it is triggering that line 2 below the exit in loadCore()? var_dump the return imo to make sure you're getting the object.
First of all. This error is produced when your server disconnect before it send any data.
A few suggestions.
your code is broken and let crash the application
your error logging should be enhanced by NOTICES
write tests to check every part
u should enable and use a debugger (zend_debugger, xdebug)
post a few more connection infos (e.g. wget -O - --debug 'url')
There is/was a special chrome issue for that problem
http://www.google.pl/support/forum/p/Chrome/thread?tid=3aa7b40eb01a95c8&hl=en#fid_3aa7b40eb01a95c80004ae797939c267
I suggest checking whether there are any blank lines before the tags.
What file names are you using?, are there any conventions you have to follow to fit a framework you might be using?
I wonder if this is a server problem and not a code problem?
This thread suggests that the server error you are seeing (500 premature end to headers) could be the result of Apache logs that are too full and need to be rotated. However it really could be anything - it seems to suggest simply that the script returns no output at all to the browser.
The other thing I'd check is file permissions, and the functioning of the include_once and file_exists in the loadCore method, as that looks the likeliest area to cause problems that might stop the script without even throwing a php error.
Maybe it´s a character/encoding error, open both files with notepad++ , goto Encoding, then select Convert to UTF-8, save the file and test it again.
Good Luck!
Related
I doing tutorial follow http://book.cakephp.org/3.0/en/development/errors.html#exception-renderer but it is not working and display blank page.
In config/bootstrap.php
use App\Error\AppError;
$errorHandler = new AppError();
$errorHandler->register();
In src/Error/AppError.php
<?php
namespace App\Error;
use Cake\Error\BaseErrorHandler;
class AppError extends BaseErrorHandler
{
public function _displayError($error, $debug)
{
return 'There has been an error!';
}
public function _displayException($exception)
{
return 'There has been an exception!';
}
public function handleFatalError($code, $description, $file, $line)
{
return 'A fatal error has happened';
}
}
I create my_error.ctp in src/Template/Layout/my_error.ctp. And in my src/Template/Error/error404.ctp I change layout to my_error.ctp.
$this->layout = 'my_error';
Finally, In my controller
use Cake\Network\Exception\NotFoundException;
$staff = $this->Staff->find()->where(['Staff.StaffId = '=> $id, 'Staff.PartnerId = ' =>$this->partnerId])->first();
if (empty($staff)) {
throw new NotFoundException(__('Staff not found'));
}
Whenever encountering blank pages, enabled debug mode, visit the URL again, and check your error logs.
However, problem in this case is most likely that the docs are incorrect/misleading, as the example app error won't do anything at all. The _ prefixed methods are ment to be protected, having them return something has no effect, and handleFatalError is ment to return a boolean.
Just look at the source of Cake\Error\BaseErrorHandler and the core error handler Cake\Error\ErrorHandler, the methods that you are overwriting are ment to generate output!
You may want to report that as an issue over at GitHub.
If all you want to do, is create a custom 4xx error page, then all you need to do is to edit the src/Template/Error/error400.ctp template accordingly.
I found my mistake. :(
Because in bootstrap.php I copy below code at the end of file. Therefore Cake cannot understand it. Please close this issue. Thank you for support.
use App\Error\AppError;
$errorHandler = new AppError();
$errorHandler->register();
In my class I've got a Method, that includes diffrent Files based on the input.
The Files are included correctly => var_dump shows "true".
BUT!! If I want to access the included variable, it tells me, that it's not defined....
The included file:
<?php
$cpucooler = array(
array(
"Name" => "Boxed CPU Lüfter",
"Sockel" => "Alle",
"Leistung" => 20,
"RPM" => 2000,
"Preis" => 0
));
?>
The Class Method:
/**
* Get Hardware for classes
* #param string $type Hardware type
* #return array
*/
public static function getHardware($type) {
switch ($type) {
case 'cpucooler':
require_once "hardware/cpucooler.php";
var_dump($cpucooler); // undefined variable...
return $cpucooler;
break;
}
}
Hope someone can help me
File was correctly included, the Problem was, that I used
require_once $file;
return $cpucooler;
instead of
require $file;
return $cpucooler;
Don't know why...
I get that error when I cannot include the file.
If including works, I also get the data.
In conclusion, since failing to open the file is not a fatal error (just a warning), you probably have disabled outputting warnings, so you don't see them. If you enable error reporting, you should see the warning.
The exact cause of failure is a guess. Maybe the path is incorrect, because you made a typo, or the case of the name is wrong, or the current directory is different from what you think. (try using an absolute path and/or check using the __DIR__ constant.
Make sure that hardware/cpucooler.php is really being included. It's a good practice to use is_file to make sure that you require file that exists in your application.
try {
$filepath = 'hardware/cpucooler.php';
if( ! is_file( $filepath ) ) {
throw new Exception( $filepath . ' do not exists.' );
}
// If exception is thrown, the following code is not executed.
require $filepath;
return $cpucooler;
} catch( Exception $e ) {
echo $e->getMessage();
}
am setting up a sand box for a T-Hub Integration with Magento and quickbooks. I've set my life site up locally using WAMP server, and now Its on to trying to tie that local Magento site into T-hub.
The first error that I received stated the
"Connection to Magento store failed. Service authentication failure - Notice: Undefined index: httponly in c:\wamp\www\testsite\appcode\core\mage\Core\Model\Session\Abtract\Varien.php on line 98."
After some searching I found the the general consensus on that one was I had to put an ssl on my local server, done, that problem's gone. Now I'm get a general error message that simply says "Connection to Magento Failed"
I used the test page that atandra included with their files which returned this:
<RESPONSE Version="4.1">
<Envelope>
<Command>GETORDERS</Command>
<StatusCode>9001</StatusCode>
<StatusMessage>
Service authentication failure - Warning: array_key_exists() expects parameter 2 to be array, string given in C:\wamp\www\adamsarms\app\code\core\Mage\Captcha\Model\Observer.php on line 166
</StatusMessage>
<Provider>Magento</Provider>
</Envelope>
</RESPONSE>
Which kicks back to this is the php file:
public function checkUserLoginBackend($observer)
{
$formId = 'backend_login';
$captchaModel = Mage::helper('captcha')->getCaptcha($formId);
$loginParams = Mage::app()->getRequest()->getPost('login', array());
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
if ($captchaModel->isRequired($login)) {
if (!$captchaModel->isCorrect($this->_getCaptchaString(Mage::app()->getRequest(), $formId))) {
$captchaModel->logAttempt($login);
Mage::throwException(Mage::helper('captcha')->__('Incorrect CAPTCHA.'));
}
}
$captchaModel->logAttempt($login);
return $this;
}
This line is the one it directly points to:
$login = array_key_exists('username', $loginParams) ? $loginParams['username'] : null;
I'm not sure which direction I need to go to fix this error to make t-hub start talking to magento proper, I've included everything that I've got, if someone needs more information please let me know, I just need a better understanding of what might be causing this error to possibly find a path to fixing it.
This is an issue with a Legacy codebase with the T-Hub extension. It was created for PHP 5.3 & Magento versions 1.4 & below. They really should update this thing since people are using it.
The companies official response is this: http://support4.atandra.com/index.php?/Knowledgebase/Article/View/92/4/magento-array_key_exists-error
Which is horrible because it relies on overriding core files.
What's going on is Mage_Captcha_Model_Observer has an event checkUserLoginBackend() that gets fired. This expects the POST info for 'login' to be a certain format. This is something that has changed over the years since legacy code does not have it in this format.
This is a really hacky fix. But it's better than overriding core magento files.
Change the CheckUser() function of Mage/Thub/Model/Run/Run.php to this (I've removed some of their comments):
public function CheckUser()
{
try {
$username = $this->RequestParams['USERID'];
$password = $this->RequestParams['PASSWORD'];
//here we just set the POST to our specified format..
//which is what the observer model thinks it should be
Mage::app()->getRequest()->setPost('login', array(
'username' => $username,
'password' => $password
));
$user = Mage::getSingleton('admin/user');
$userRole = Mage::getSingleton('admin/role');
if ($user->authenticate($username, $password)) {
$loadRole = $userRole->load($user->getRoles($user));
} else {
print($this->xmlErrorResponse($this->RequestParams['COMMAND'], '9000',
'Order download service authentication failure - Login/Password supplied did not match', $this->STORE_NAME, ''));
exit;
}
} catch (Exception $e) {
$this->Msg[] = "Critical Error CheckUser (Exception e)=" . $e->getMessage(); //BB 11Nov2014
print($this->xmlErrorResponse($this->RequestParams['COMMAND'], '9001',
'Service authentication failure - ' . " " . $e->getMessage(), $this->STORE_NAME, ''));
// End - <TIBB> 13Dec2011
exit;
}
}
Another alternative is to extend the Mage_Captcha_Model_Observer class with your own version that removes those array checks in checkUserLoginBackend().
I'm trying to implement dropzone.js into my CakePHP application. So far it all went fine. Except When I receive an error, it displays the whole HTML error page, not rendered. Which turns into a bunch of HTML code, not quite readable and because the error box becomes so big I cannot click the "remove" button. See picture below:
As soon as I receive an error:
When I hover the box, after receiving an error:
I know the reason is that dropzone.js recognizes the error because of the 500 header of the Ajax page (I throw an Exception if something goes wrong). And CakePHP renders a complete layout for a 500 error page. So it's not possible for me to just view a one row error. And I really need the 500 header, because else dropzone.js thinks everything went fine....
So my question: Is it possible to NOT render the 500 error layout, when getting a 500 error within a specific Controller method? I don't want to completely disable the 500 error layout rendering. Only for AJAX pages.
public function admin_add($slug = null) {
if(!$slug || !$client = $this->Video->Client->find('first', array('conditions' => array('slug' => $slug)))) {
throw new NotFoundException(__('Invalid client'));
}
if ($this->request->is('post')) {
// If request contains files, continue
if (!empty($_FILES)) {
// Get slug from URL
$slug = substr( $this->referer(), strrpos( $this->referer(), '/' )+1 );
// Create new folder for the movies if it doesn't exist already
if (!file_exists(WWW_ROOT.'/files/'.$slug)) {
mkdir(WWW_ROOT.'/files/'.$slug, 0777, true);
}
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = '/files/'.$slug.'/';
$targetFile = $targetPath. $_FILES['file']['name'];
// Create variable filename without the extension
$fileWithoutExt = preg_replace("/\\.[^.\\s]{3,4}$/", "", $_FILES['file']['name']);
// Add file to Video array
$video['Video'] = array('video' => $targetFile, 'screenshot' => '/files/'.$slug.'/screenshots/'.$fileWithoutExt.'.jpg', 'client_id' => $client['Client']['id']);
// unset($video);
// Try moving the file to their final directory
if(!move_uploaded_file($tempFile, WWW_ROOT.$targetFile)) {
throw new NotFoundException(__('Move image to "'.WWW_ROOT.$targetPath.'" failed'));
}
// Create new folder for the screenshots if it doesn't exist already
if (!file_exists(WWW_ROOT.'/files/'.$slug.'/screenshots/')) {
mkdir(WWW_ROOT.'/files/'.$slug.'/screenshots/', 0777, true);
}
// Try saving video to Video table in the database
if(!$this->Video->save($video)){
throw new NotFoundException(__('Failed connecting client with "'.$targetFile.'" in the database'));
}
}
$this->Session->setFlash(__('Videos successfully uploaded'), 'default', array(), 'success');
$this->redirect($this->referer());
}
$title_for_layout = $client['Client']['name'];
$this->set(compact('title_for_layout', 'client'));
}
You can change retuned status code by use statusCode method of CakeResponse class. Something like this: $this->response->statusCode(404);
It's a little not correct to use NotFoundException to return http status code. At least you can create your own application exception
Please, check Creating your own application exceptions
You will easily to define one exceptions:
class MissingWidgetException extends CakeException {};
And after that you can use it and send http status code which you need Creating custom status codes :
throw new MissingWidgetHelperException('Its not here', 501);
501 is http status code.
Hope, this will help to find out right solution.
i just want an Action to print a barcode image, but i can´t get this working in MVC, i just do the following:
public function barcodeAction() {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
Zend_Barcode::render($_GET['barcodeType'], 'image', $_GET, $_GET);
}
but when I call
/barcode?barcodeType=code39&text=ZEND-FRAMEWORK
I just obtain:
"The image couldn't be displayed because it has errors" (or something like that, browser-dependant).
Thanks!
You're likely getting an error that you can't see due to the Content-Type header that's sent by Zend_Barcode. Make sure you have log_errors turned on and a valid/writeable destination for the log configured. This way you can check the error log for anything that you normally would have read through your browser.
http://us3.php.net/manual/en/errorfunc.configuration.php#ini.log-errors
I have no problem with your code, I call this url: http://localhost/index/barcode?barcodeType=code39&text=ZEND in my browser (your code is in the IndexController) and I receive the correct image.
If I put <img src="http://localhost/index/barcode?barcodeType=code39&text=ZEND" /> in a view, I have also the image.
Mickael
I know this may be outdated now but when I had the same problem I just added
ob_clean();
in my controller so now my action looks like this
public function generateBarcodeAction() {
ob_clean();
$number = $this->params()->fromRoute('number');
$barcodeOptions = array('text' => $number);
$rendererOptions = array('imageType'=>'png');
Barcode::render(
'ean13', 'image', $barcodeOptions, $rendererOptions
);
}
and it's working like a charm