I have a site where users can upload images and then download them. I have moved my project on a live web host but the problem is that when I try to download the file I just uploaded, it downloads it but cant open it afterwards, it says it is corrupted... I had no problems in local though.
heres my download action:
public function getfile($accesskey) {
$this->autoRender = false;
if ($accesskey != null) {
$data = $this->getfileinfo($accesskey);
if (!empty($data)) {
$this->response->file(WWW_ROOT.$data['Document']['dlpath'], array('download' => true, $data['Document']['name']));
return $this->response;
} else {
$this->redirect(array('controller' => 'documents', 'action' => 'upload'));
}
} else {
$this->redirect(array('controller' => 'documents', 'action' => 'upload'));
}
}
$data['Document']['dlpath'] contains the following:
/home/vol2_2/byethost17.com/b17_15357734/htdocs/app/webroot/uploads/2014/09/26/filekey/imagename.extension
this is the first time i'm doing this so i might have made a mistake.. the path is wrong or something i'm confused
EDIT: It seems that the error i was getting was much deeper than it seemed. I opened the corruted file in a text editor and saw some error concerning set_time_limit() and php safe mode...
here's the error:
Warning (2) : set_time_limit() has been disabled for security reasons [ CORE/Cake/Network/CakeResponse.php , line 1458 ] Code Context
set_time_limit - [internal], line ??
CakeResponse::_sendFile() - CORE/Cake/Network/CakeResponse.php, line 1458
CakeResponse::send() - CORE/Cake/Network/CakeResponse.php, line 429
MediaView::render() - CORE/Cake/View/MediaView.php, line 96
Controller::render() - CORE/Cake/Controller/Controller.php, line 954
Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 198
Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 165
[main] - APP/webroot/index.php, line 108
Related
I'm having this problem while seeding my PGSQL Database:
Illuminate\Database\QueryException : SQLSTATE[22021]: Character not in repertoire: 7 ERROR: secuencia de bytes no válida para codificación «UTF8»: 0xe3 0x83 0xe2 (SQL: insert into "races" ("name", "public_name", "members", "updated_at", "created_at") values (harp��a, HarpÃa, 23, 2018-04-21 20:30:20, 2018-04-21 20:30:20) returning "id")
at C:\Sandbox\rpgforum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[22021]: Character not in repertoire: 7 ERROR: secuencia de bytes no válida para codificación «UTF8»: 0xe3 0x83 0xe2")
C:\Sandbox\rpgforum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:330
2 PDOStatement::execute()
C:\Sandbox\rpgforum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:330
Please use the argument -v to see more details.
And this is my Seeder's code:
<?php
use Illuminate\Database\Seeder;
use App\Models\Race;
class RaceTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$races = [
'Humano',
'Orco',
'Elfo',
'Harpía',
'Enano',
];
for ($i = 0; $i < count($races); $i++) {
$race_i = utf8_encode($races[$i]);
$race = Race::create([
'name' => strtolower($race_i),
'public_name' => $race_i,
'members' => mt_rand(10,30),
]);
} // for
}
}
My database configuration:
pgsql database
My config.database file config:
config.database file
Is there any solution for this problem? I can find the way to get rid of this problem...
EDIT:
I just noticed something weird. I got two records in my database:
database records
And both of them have symbols that gave me problem with the seeder. Maybe the problem is within the seeders logic? I'm doing the exact same thing I do the whole time with my Laravel/Postgresql projects so i can't find the reason why i can't seed words with accent mark but i can use a simple form to store that kind of information. Any ideas ?
I have never written an PHP Download File Script neither have any experience with it and I am really not a pro. I got the snippet of code you can see below from another website and tried to make use of it. I understand what is written in the script but I just don't get the message of the errors or rather said, I don't know how to prevent these.
Here is the download.php script - I have put it into the /download/ folder below my main domain:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Now in the /download/ folder, which contains the download.php I have a folder /downloads, which contains the .pdf that should be downloaded.
The link I use on my webpage is:
PHP download file (why isn't it displayed, included the 4 white spaces :
Now I get the following errors when I click on the link:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(/downloads/test.pdf): failed to open stream: No such file or directory in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
If I use an absolute path (https://www.my-domain.de/downloads/) for the $path variable, I get these errors:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /var/www/xxx/html/download/download.php on line 12
Warning: fopen(https://www.my-domain.de/downloads/test.pdf): failed to open stream: no suitable wrapper could be found in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
I am thankful for any advices!
<?php
ignore_user_abort(true);
//set_time_limit(0); disable the time limit for this script
$path = "downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
?>
Try this code
Your server is probably not allowing you for a maximum execution time limit for infinite seconds. Check it in php.ini file
Also the relative path was wrong, and "https://www.my-domain.de/downloads/" is not a path, it's a url for the server
pulling my hair out with this one.
When I developed this cakephp (2.2) app on my local machine, I could email via gmail using smtp without a problem. Since then I've deployed it onto a 1and1 server and I can no longer send. What even more frustrating is that I cant seem to get any decent debugging info from cake.
Heres the code:
if($fu['name']) {
$url = Router::url('/admin/', true );
$ms = $url;
$ms = wordwrap($ms,1000);
//============Email================//
// SMTP Options
$this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>'myemail#gmail.com',
'password'=>'password'
);
$this->Email->template = 'newExpenseClaim';
$this->Email->from = 'Expense Tracker <myemail#email.co.uk>';
$this->Email->to = 'myemail#fakeemail.com';
$this->Email->subject = 'New Expense Claim Submitted - Please Review';
$this->Email->sendAs = 'both';
$this->Email->delivery = 'smtp';
// Set username & url in email
$this->set('user', $fu['name']);
$this->set('ms', $ms);
//$this->Email->send();
if(!$this->Email->send()) {
CakeLog::write('debug', $this->Email->smtpError);
}
$this->set('smtp_errors', $this->Email->smtpError);
//============EndEmail=============//
}
I get the following debug info each times it fails (printed on screen, nothing goes into the debug log which is massively anoying).
Connection refused
Error: An Internal Error Has Occurred.
Stack Trace
CORE/Cake/Network/Email/SmtpTransport.php line 95 → CakeSocket->connect()
CORE/Cake/Network/Email/SmtpTransport.php line 60 → SmtpTransport->_connect()
CORE/Cake/Network/Email/CakeEmail.php line 1059 → SmtpTransport->send(CakeEmail)
CORE/Cake/Controller/Component/EmailComponent.php line 345 → CakeEmail->send(null)
APP/Controller/ExpenseClaimsController.php line 236 → EmailComponent->send()
APP/Controller/ExpenseClaimsController.php line 278 → ExpenseClaimsController->notifyAdminsOfNewClaims()
[internal function] → ExpenseClaimsController->add()
CORE/Cake/Controller/Controller.php line 485 → ReflectionMethod->invokeArgs(ExpenseClaimsController, array)
CORE/Cake/Routing/Dispatcher.php line 186 → Controller->invokeAction(CakeRequest)
CORE/Cake/Routing/Dispatcher.php line 161 → Dispatcher->_invoke(ExpenseClaimsController, CakeRequest, CakeResponse)
APP/webroot/index.php line 92 → Dispatcher->dispatch(CakeRequest, CakeResponse)
Can anyone help? Thanks in advance
** Updated with wrapper and soctet info **
These are the wrappers and sockets I get returned from those functions:
Wrappers:
array(
(int) 0 => 'https',
(int) 1 => 'ftps',
(int) 2 => 'compress.zlib',
(int) 3 => 'compress.bzip2',
(int) 4 => 'php',
(int) 5 => 'file',
(int) 6 => 'data',
(int) 7 => 'http',
(int) 8 => 'ftp',
(int) 9 => 'zip'
)
Sockets
array(
(int) 0 => 'tcp',
(int) 1 => 'udp',
(int) 2 => 'unix',
(int) 3 => 'udg',
(int) 4 => 'ssl',
(int) 5 => 'sslv3',
(int) 6 => 'sslv2',
(int) 7 => 'tls'
)
In first you should check what your hosting support outgoing connection. Simple check is similar
echo implode("", file("http://google.com"));
In second you should check what PHP support SSL connection and it have stream wrapper for SSL.
I now not remember how you can check it. But search in google by keywords: PHP stream wrapper SSL
I can't seem to use a component in AppController?
class AppController extends Controller {
var $helpers = array('Facebook', 'Session', 'Menu', 'Html', 'Form'); // Facebook is a custom helper.
var $components = array('Cookie');
function beforeFilter ( )
{
$this->Cookie->name = '[removed]';
$this->Cookie->path = '/cake/';
$this->Cookie->domain = 'localhost';
$this->Cookie->key = '[removed]';
$this->_initUser();
}
function _initUser ( ) // Using this for a cleaner default.ctp
{
#Controller::loadModel('User');
// DEFINE facebook variables globally
$GLOBALS['APP_ID'] = '[removed]';
$GLOBALS['APP_SECRET'] = '[removed]';
$GLOBALS['REDIRECT_URI'] = 'http://localhost/cake';
// Check if logged in with Facebook.
if($this->Cookie->read('User') == null && isset($_GET['code'])) // Line 57.
.
.
.
Here is the error PHP is throwing up:
Notice (8): Undefined property: View::$Cookie [APP\app_controller.php, line 57]Code
// Check if logged in with Facebook.
if($this->Cookie->read('User') == null && isset($_GET['code'])) AppController::_initUser() - APP\app_controller.php, line 57
include - APP\views\layouts\default.ctp, line 47
View::_render() - CORE\cake\libs\view\view.php, line 731
View::renderLayout() - CORE\cake\libs\view\view.php, line 489
View::render() - CORE\cake\libs\view\view.php, line 435
Controller::render() - APP\controller.php, line 909
PagesController::display() - APP\controllers\pages_controller.php, line 83
Dispatcher::_invoke() - CORE\cake\dispatcher.php, line 204
Dispatcher::dispatch() - CORE\cake\dispatcher.php, line 171
[main] - APP\webroot\index.php, line 83
Fatal error: Call to a member function read() on a non-object in C:\xampp\htdocs\cake\app\app_controller.php on line 57
Please help, I have no idea about what I should do!
Aha! I fixed it finally. The problem was that my Facebook component read class FacebookHelper accidentally.
I fixed this issue and then it continued to execute the rest of AppController normally and it worked.
Never going to code post-midnight again.
i am getting the error as
Array to string conversion [CORE/cake/libs/file.php, line 96]
$path = array(
"name" => "23_50_11[1].gif",
"type" => "image/gif",
"tmp_name" => "/tmp/phpbBWxAT",
"error" => 0,
"size" => 25230
)
$create = false
$mode = 493
dirname - [internal], line ??
File::__construct() - CORE/cake/libs/file.php, line 96
FormsController::add() - APP/controllers/forms_controller.php, line 528
Object::dispatchMethod() - CORE/cake/libs/object.php, line 117
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 245
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 211
require - APP/webroot/index.php, line 88
[main] - CORE/index.php, line 61
Notice (8): Array to string conversion [CORE/cake/libs/file.php, line 97]
$path = array(
"name" => "23_50_11[1].gif",
"type" => "image/gif",
"tmp_name" => "/tmp/phpbBWxAT",
"error" => 0,
"size" => 25230
)
$create = false
$mode = 493
is_dir - [internal], line ??
File::__construct() - CORE/cake/libs/file.php, line 97
FormsController::add() - APP/controllers/forms_controller.php, line 528
Object::dispatchMethod() - CORE/cake/libs/object.php, line 117
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 245
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 211
require - APP/webroot/index.php, line 88
[main] - CORE/index.php, line 61
Warning (2): basename() expects parameter 1 to be string, array given [CORE/cake/libs/file.php, line 98]
The code that i have used is,
<h1>Form Fill</h1>
<?=$form->create('Form',array('type'=>'file'));?>
<?=$form->input('date',array('label'=>'Publication Date '));?>
<?=$form->input('headline');?>
<?=$form->input('content');?>
<?=$form->input('image',array('type'=>'file'));?>
<?=$form->end('Submit');?>
in the Formscontroller
function add($formid)
{
echo "Imaage ".$this->data['Form']['image'];// shows me the Imaage Array
if ($this->data['Form']['image']) {
$file = new File($this->data['Form']['image']);// this is not working
//$ext = $file->ext();
//echo "Extension ".$ext;
echo "Fiel ".$file;
$date = $this->data['Form']['date'];
$filename = $date['year'].'-'.$date['month'].'-'.$date['day'].'-form-image.'.'gif';
$data = $file->read();
echo "Data ".$data;
$file->close();
$file = new File(WWW_ROOT.'/img/'.$filename,true);
$file->write($data);
$file->close();
}
}
Instance for File is not working?? Please help me . actually i m trying to upload the image FIle and i m using Ubuntu linux machine ..
To recap:
$this->data['Form']['image']; // shows me the Imaage Array
$file = new File($this->data['Form']['image']); // this is not working
Error: Array to string conversion
The problem:
new File() expects a string as argument, but you're giving it an array.
Solution:
Supply a string as argument for new File(), preferably the path of the file:
$file = new File($this->data['Form']['image']['tmp_name']);
To be a little more detailed and help you fix these kinds of problems yourself next time (hopefully), it's not actually File that expects a string argument. If you look at the trace again:
dirname - [internal], line ??
File::__construct() - CORE/cake/libs/file.php, line 96
FormsController::add() - APP/controllers/forms_controller.php, line 528
...
This says the problem actually occurred in dirname, which is a PHP internal function. It was called on line 96 in File::__construct, which in turn was called from FormsController::add etc. pp.
Since PHP is a dynamic language it doesn't usually crap out completely when you supply arguments of the wrong type. Rather it'll try to make the best out of it and actually try to convert an array to a string, and just notify you that it did so with Notice (8): Array to string conversion. Since the result of an Array -> String conversion is literally the string "Array", your program will usually crap out later, since now you're trying to do things like is_dir("Array"), which is nonsense.
As you can see the program actually struggles on, with quite a few notices, and basename() on line 98 even complaining a little harder with a Warning:
94: function __construct($path, $create = false, $mode = 0755) {
95: parent::__construct();
96: $this->Folder =& new Folder(dirname($path), $create, $mode);
97: if (!is_dir($path)) {
98: $this->name = basename($path);
Warning (2): basename() expects parameter 1 to be string, array given [CORE/cake/libs/file.php, line 98]
Now, it would be good style for File to check if the parameter actually is a string or not and fail gracefully, but it doesn't bother. Because as a developer you should read the documentation to see what the function expects. If it's not on the website, look directly in the file /cake/libs/file.php:
/**
* Constructor
*
* #param string $path Path to file
* #param boolean $create Create file if it does not exist (if true)
* #param integer $mode Mode to apply to the folder holding the file
* #access private
*/
function __construct($path, $create = false, $mode = 0755) {
...