I have one page where I can upload files. On my localhost everything work fine but on the shared host doesn't work and when I load the page it crashing and showing Error 500 - Internal Server Error.
The only different's between local configuration and configuration on the host is eAccelerator which is enabled by default on the shared host.
I have tried to create php.ini on the host and disable it but no luck so far. In the .htaccess i've put:
<IfModule mod_suphp.c>
suPHP_ConfigPath /home/myuser/public_html/php.ini
</IfModule>
note: myuser is not my real user.. I've changed it just for here.
Then in php.ini I put this but on the phpinfo() is still showing that is enabled.
eaccelerator.enable 0
eaccelerator.optimizer 0
Sadly but there is not errors anywhere so I don't know what exactly going on here. No errors in cPanel. No errors in the directory with the file. No errors when I try with error_reporting(E_ALL); and ini_set('display_errors', 'on');.
When I remove this portion of code the page is loaded and no errors. So the problem is in the code + eaccelator. Here is the code which is located above the HTML form in the same file.
if (array_key_exists("add", $_POST)) {
$pdo = Database::connect();
$allowedFileTypes = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp');
$uploadFolder = "uploads/";
$totalFiles = 0;
$files = (object)[
'file_1' => (object)['name' => ''],
'file_2' => (object)['name' => ''],
'file_3' => (object)['name' => '']
];
$query = "INSERT INTO file_upload (
`file_title`, `file_program`, `file_subject`, `file_1`, `file_2`, `file_3`, `uploaded_by`, `upload_date`
) VALUES (
:file_title, :file_program, :file_subject, :file_1, :file_2, :file_3, :uploaded_by, NOW()
)";
$queryPrepare = $pdo->prepare($query);
foreach (array_keys($_FILES) as $file) {
$filesInCurrentInput = count(array_filter($_FILES[$file]['tmp_name']));
if (!$filesInCurrentInput) {
continue;
}
$totalFiles += $filesInCurrentInput;
for ($i = 0; $i < $filesInCurrentInput; $i++) {
if ($_FILES[$file]['error'][$i]) {
continue;
}
$type = $_FILES[$file]['type'][$i];
if (!in_array($type, $allowedFileTypes)) {
throw new Exception("File type not allowed.");
}
$oldName = $_FILES[$file]['name'][$i];
$getEndOfFile = explode(".", $oldName);
$extension = end($getEndOfFile);
$name = hash("md5", uniqid(rand(), true)) . '.' . $extension;
$temporaryFile = $_FILES[$file]['tmp_name'][$i];
if (!move_uploaded_file($temporaryFile, $uploadFolder.$name)) {
throw new Exception("An error occured while trying to upload a file.");
} else {
$files->$file->name .= $name . ',';
}
}
}
if (!$totalFiles) {
throw new Exception("You must attach files to the lesson.");
}
$title = htmlspecialchars($_POST['file_title']);
$file_program = htmlspecialchars($_POST['file_program']);
$file_subject = htmlspecialchars($_POST['file_subject']);
$uploaded_by = htmlspecialchars($_SESSION['user_username']);
$queryPrepare->bindValue(":file_title", $title);
$queryPrepare->bindValue(":file_program", $upload_program);
$queryPrepare->bindValue(":file_subject", $upload_subject);
$queryPrepare->bindValue(":file_1", trim($files->file_1->name, ','));
$queryPrepare->bindValue(":file_2", $files->file_2->name);
$queryPrepare->bindValue(":file_3", $files->file_3->name);
$queryPrepare->bindValue(":uploaded_by", $uploaded_by);
$queryPrepare->execute();
echo "<p class='bg-success text-center'>File added successfully.</p>";
}
The form is simple form with few fields.. nothing special there. Any help on this?
Please change this:
$files = (object)[
'file_1' => (object)['name' => ''],
'file_2' => (object)['name' => ''],
'file_3' => (object)['name' => '']
];
To this and try to reload the page:
$files = (object)array(
'file_1' => (object)array('name' => ''),
'file_2' => (object)array('name' => ''),
'file_3' => (object)array('name' => '')
);
Related
I'm trying to integrate CKFinder(v.3) with CKEditor(v.4) in my Codeigniter project but getting error "Folder not found" when i tried to upload a file on to server. I hv googled this issue and tried various solutions like below but none had worked:
1) Changing permission for ckfinder folder to FULL for all users
2) Changing permission for data-content/page_assets folder to FULL for all users
3) Set baseURL path in config.php to "http://localhost:8080/project/cms/js/ckfinder/userfiles/"
Below are the editor setup in my view file
// filebrowserBrowseUrl & filebrowserUploadUrl will be different for each module but the base will
// same 'data-content'
CKEDITOR.replace( 'page_content', {
filebrowserBrowseUrl: '<?php echo base_url()?>js/ckfinder/ckfinder.html?Type=Images&rlf=0&start=Images:/project/data-content/page_assets/',
filebrowserUploadUrl: '<?php echo base_url()?>js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images¤tFolder=/project/data-content/page_assets/',
filebrowserWindowWidth: '1000',
filebrowserWindowHeight: '700'
});
Below are the config.php in CKFinder. Listing only what i had changed in this file
$config['authentication'] = function () {
return true;
};
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
//'baseUrl' => '/ckfinder/userfiles/',
'baseUrl' => 'http://localhost:8080/project/cms/js/ckfinder/userfiles/',
// 'root' => '', // Can be used to explicitly set the CKFinder user files directory.
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8',
);
$config['overwriteOnUpload'] = false;
$config['checkDoubleExtension'] = true;
$config['disallowUnsafeCharacters'] = true;
$config['secureImageUploads'] = true;
$config['checkSizeAfterScaling'] = true;
$config['htmlExtensions'] = array('html', 'htm', 'xml', 'js');
$config['hideFolders'] = array('.*', 'CVS', '__thumbs');
$config['hideFiles'] = array('.*');
$config['forceAscii'] = false;
$config['xSendfile'] = false;
// https://ckeditor.com/docs/ckfinder/ckfinder3-php/configuration.html#configuration_options_debug
$config['debug'] = true;
Detail error, after debugging on
Fatal error: Uncaught CKSource\CKFinder\Exception\FolderNotFoundException: Folder not found in C:\xampp\htdocs\project\cms\js\ckfinder\core\connector\php\vendor\cksource\ckfinder\src\CKSource\CKFinder\Filesystem\Folder\WorkingFolder.php:144
These are the concerned code block from WorkingFolder.php file
// Check if resource type folder exists - if not then create it
$currentCommand = (string) $request->query->get('command');
$omitForCommands = array('Thumbnail');
// DEBUGGING the value of EACH PROPERTY
// clientCurrentFolder => /noveltech/data-content/page_assets/
// $currentCommand => QuickUpload
// $resourceTypeDirectory => images
// $this->path => images/noveltech/data-content/page_assets/
if (!in_array($currentCommand, $omitForCommands) && !empty($resourceTypeDirectory) && !$backend->hasDirectory($this->path))
{
if ($this->clientCurrentFolder === '/') {
#$backend->createDir($resourceTypeDirectory);
if (!$backend->hasDirectory($resourceTypeDirectory))
{
throw new AccessDeniedException("Couldn't create resource type directory. Please check permissions.");
}
}
else {
throw new FolderNotFoundException(); // THIS IS LINE NO. 144
}
}
My development environment is XAMPP.
Can any one please help me in integrating CKFinder?
Much Regards,
Javed
I've used PSR logger to get logs. But it will create just one file for all dates. I need to get separate log files to each date. How to do that?
require_once '../../logger/vendor/autoload.php';
require_once '../../logger/Psr/Log/Logger.php';
use Katzgrau\KLogger\Logger;
use Psr\Log\LogLevel;
$logPath = '/var/www/html/logs';
$logger = new Logger($logPath, LogLevel::DEBUG, array ( 'filename' => 'driver_api' , 'extension' => 'log' ));
$logger->log( $level, $message , $context);
`
use log rotator
protected function log_rotate($logpath, $filename, $extention){
$logfilename = $logpath.'/'.$filename.'.'.$extention; //not needed when included
$logfilestokeep = 15;
$fileDate = '';
if (file_exists($logfilename)) {
if (date("Y-m-d", filemtime($logfilename)) !== date('Y-m-d')) {
$fileDate = date("Y-m-d", filemtime($logfilename));
$newName = $logpath .'/'.$filename. "_" . $fileDate.'.'.$extention;
if (file_exists($logfilename)) {
rename($logfilename, $newName);
}
}
}
}
After hours of trying to figure out why php "ZipArchive" does not work as expected, due to Mac OS adding a "__MACOSX" folder in the zip compression process.
How would I go about deleting "__MACOSX" folder in a zip archive during the upload process in a form?
Below is what I'm working with:
<?php
public function uploadZip($file)
{
$advert_index;
$zip = new \ZipArchive;
if (true === $zip->open($file['tmp_name'])) {
$source = trim($zip->getNameIndex(0), '/');
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
// Determine output filename (removing the `$source` prefix).
$substring_name = substr($name, strlen($source)+1);
$file = $this->option['uploads_path'] . $this->option['advert_id'] . '/' . $substring_name;
// Store the adverts `index.html` file URL to be returned.
if ('html' === pathinfo($name, PATHINFO_EXTENSION)) {
$advert_index = basename($name);
}
// Create the directories if necessary.
$dir = dirname($file);
if (! is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Read from Zip and write to disk.
$fpr = $zip->getStream($name);
$fpw = fopen($file, 'w');
while ($data = fread($fpr, 1024)) {
fwrite($fpw, $data);
}
fclose($fpr);
fclose($fpw);
}
$zip->close();
return array(
'status' => true,
'message' => array(
'index' => $advert_index,
'type' => 'text/html', // #HACK: Set MIME type manually. #TODO: Read MIME type from file.
),
);
}
return array(
'status' => false,
'message' => 'Upload failed',
);
}
Any help would be much appreciated :)
Note: I Managed to find the file just can't get it to be removed.
// Check to see the __MACOSX
if($zip->getNameIndex($i) === "__MACOSX/") {
error_log($zip->getNameIndex($i) . ' - Error here continue');
$zip->deleteName("__MACOSX/");
continue; // Move on to the next iteration
// $zip->deleteIndex($i);
} else {
$name = $zip->getNameIndex($i);
}
It was actually very simple, instead to trying to delete the folder within the zip-archive just had to skip all indexes aka filename that begin with a certain string while looping through the files.
if(substr($zip->getNameIndex($i), 0, 9) === "__MACOSX/") {
continue;
} else {
$name = $zip->getNameIndex($i);
}
I've the following problem: i'm working on a filemanager consisting in only one index.php file, that fetches all the files and folders from the actual folder there its located in.
So if i have a folder with the filemanager file on it:
Folder01
-folder-A
-folder-B
-file1.php
-image.png
-index.php
The filemanager will show: folder-A, folder-B, file1.php and image.png
The problem is I can't change the folder to fetch it's content, to be able to view, by default, the content of folder-A for example.
$file = isset($_REQUEST['file']) ? urldecode($_REQUEST['file']) : '.';
if(isset($_GET['do']) && $_GET['do'] == 'list') {
if (is_dir($file)) {
$directory = $file;
$result = array();
$files = array_diff(scandir($directory), array('.','..'));
foreach($files as $entry) if($entry !== basename(__FILE__)) {
$i = $directory . '/' . $entry;
$stat = stat($i);
$result[] = array(
'mtime' => $stat['mtime'],
'size' => $stat['size'],
'name' => basename($i),
'path' => preg_replace('#^\./#', '', $i),
'ext' => pathinfo($i, PATHINFO_EXTENSION),
'is_dir' => is_dir($i),
'is_deleteable' => (!is_dir($i) && is_writable($directory)) ||
(is_dir($i) && is_writable($directory) && is_recursively_deleteable($i)),
'is_readable' => is_readable($i),
'is_writable' => is_writable($i),
'is_executable' => is_executable($i),
);
}
} else {
err(412,"Not a Directory");
}
echo json_encode(array('success' => true, 'is_writable' => is_writable($file), 'results' =>$result));
exit;
}
This snippet is the beginning of its php code, which is in charge of fetching the files of the selected folder.
Any idea about how to change that?
try glob function, its like dir command in dos,
it will list all of the dirs and files in the current working directory and put them in an array, which is the return value of the function.
I would to retrieve from a path all sub (and sub-sub) directories and all files (only with .php and .css extensions) in (last sub) it.
The structre is the following:
my_path/sub-folder1/ // I want to get the sub folder name (and check if allowed)
sub-sub-folder1/file1.php // I want to get the file name and path
sub-sub-folder1/file1.css // I want to get the file name and path
sub-sub-folder2/file2.php // ....
sub-sub-folder2/file2.css
sub-sub-folder3/file3.php
sub-sub-folder3/file3.css
my_path/sub-folder2/
sub-sub-folder1/file1.php
sub-sub-folder1/file1.css
sub-sub-folder2/file2.php
sub-sub-folder2/file2.css
sub-sub-folder3/file3.php
sub-sub-folder3/file3.css
I know the my_pathdirectory name. About sub-folder, I only want to retrieve sub-folder which have the name (sub-folder1, sub-folder2 for example). And I would like to retrieve all sub-sub-folders and inside them and get the name and path of the .css and .php files inside it. I'm not sure if I'm clear with my explanations.
My aim is to store all this information in an array like this:
$data['sub-folder-1']= array(
'sub-sub-folder1' => array(
'name' => 'file1',
'php' => 'file1.php',
'css' => 'file1.css',
),
'sub-sub-folder2' => array(
'name' => 'file2',
'php' => 'file2.php',
'css' => 'file2.css',
),
...
);
$data['sub-folder-2']= array(
'sub-sub-folder1' => array(
'name' => 'file1',
'php' => 'file1.php',
'css' => 'file1.css',
),
'sub-sub-folder2' => array(
'name' => 'file2',
'php' => 'file2.php',
'css' => 'file2.css',
),
...
);
I have started with this code but I have some difficulties to make it works (and it's not finished), I don't use this kind of functionnality a lot...
$dirname = 'my_path';
$findphp = '*.php';
$findcss = '*.css';
$types = array('sub-folder1','sub-folder2');
$sub_dirs = glob($dirname.'/*', GLOB_ONLYDIR|GLOB_NOSORT);
if(count($sub_dirs)) {
foreach($sub_dirs as $sub_dir) {
$sub_dir_name = basename($sub_dir);
if (in_array($sub_dir_name,$types)) {
$sub_sub_dirs = glob($sub_dir.'/*', GLOB_ONLYDIR|GLOB_NOSORT);
if(count($sub_sub_dirs)) {
foreach($sub_sub_dirs as $sub_sub_dir) {
$php = glob($sub_sub_dir.'/'.$findphp);
$css = glob($sub_sub_dir.'/'.$findcss);
$sub_sub_dir_name = basename($sub_sub_dir);
$data[$sub_dir_name][$sub_sub_dir_name]['type'] = $sub_dir_name;
$data[$sub_dir_name][$sub_sub_dir_name]['name'] = basename($php[0], '.php');
$data[$sub_dir_name][$sub_sub_dir_name]['html'] = $php[0];
$data[$sub_dir_name][$sub_sub_dir_name]['css'] = $css[0];
}
}
}
}
} else {
echo "Nothing was found.";
}
print_r($data);
I like using the RecursiveDirectoryIterator class. I think it's more readable. This sample allow you to read all subfolders of a given source.
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source)); // Top source directory
$iterator->setFlags(\FilesystemIterator::SKIP_DOTS); // Skip folders with dot
$allowedExtension = array('php', 'css'); // And other if needed
$skin = array();
while ($iterator->valid()) {
$extension = $iterator->getExtension(); // >= PHP 5.3.6
if ($iterator->isFile() && in_array($extension, $allowedExtension)) {
// Complete this part or change it following your needs
switch ($extension) {
case 'php':
// All your logic here
$skin[$iterator->getPath()]['name'] = $iterator->getFileName(); //eg
break;
default:
break;
}
}
$iterator->next();
}
You can find the whole list of available functions at Directory Iterator.
Hope it's help.