I have an error about my fuction on this line:
$FILE_LIST[$key]['name'] = str_replace('.' . $ext, '', $result);
Warning: Illegal string offset 'name'
I tried different way but i don't find the solution.
I look other post like Warning: Illegal string offset 'name'
but it do not resolve the problem (or I fogot something).
the function
public function getFiles($source_folder, $filename, $ext = 'php') {
if(is_dir( $source_folder)) {
$FILES = glob($source_folder . $filename . '.' . $ext);
$FILE_LIST[] = '';
if (is_array($FILES)) {
foreach($FILES as $key => $file) {
$result = str_replace($source_folder, '', $file);
$name = str_replace('.' . $ext, '', $result);
if (!empty($name)) {
$FILE_LIST[$key]['name'] = $name;
}
}
}
if (is_array($FILE_LIST)) {
return $FILE_LIST;
}
}
}
Change this:
if (!empty($name)) {
$FILE_LIST[$key]['name'] = $name;
}
to this:
if (!empty($name)) {
$FILE_LIST[$key] = Array();
$FILE_LIST[$key]['name'] = $name;
}
Related
I'm dealing with this php script, which when executed on the host gives a 500 error, apparently the line where the preg_match is is the one that contains the error...
this file is going to be executed as a cron to validate.
<?php
$encoded = wordwrap($encoded, 80, "\xa", true);
$license_file = $dir . "/modules/addons/Kayako/license.php";
if ($key != $sellKey) {
die("Invalid "license . php" file!");
}
function getWhmcsDomain() {
if (!empty($_SERVER["SERVER_NAME"])) {
return $_SERVER["SERVER_NAME"];
}
}
$license["checkdate"] = date("Ymd");
$keyName = $modleName . "_licensekey";
$dir = __DIR__;
$encoded = strrev($encoded);
$license["status"] = "Active";
$sellKey = "ModulesGarden_Kayako_54M02934WH301844E_HackbyRicRey";
$license["checktoken"] = $checkToken;
$key_data = WHMCS\Database\Capsule::table("tblconfiguration")->where("setting", "kayako_localkey")->first();
$license = array("licensekey" => $key, "validdomain" => getWhmcsDomain(), "validip" => getIp(), "validdirectory" => $dir . "/modules/addons/Kayako," . $dir . "/modules/addons," . $dir . "/modules/addons/Kayako," . $dir . "/modules/addons/Kayako," . $dir . "/modules/addons," . $dir . "," . $dir . "/modules");
$secret = "659c08a59bbb484f3b40591";
include_once "init.php";
function getIp() {
return isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : $_SERVER["LOCAL_ADDR"];
}
if (!$key_data) {
WHMCS\Database\Capsule::table("tblconfiguration")->insert(array("setting" => "kayako_localkey", "value" => ''));
}
$checkToken = time() . md5(rand(1000000000, 0) . $key);
$modleName = "kayako";
$encoded = $encoded . md5($encoded . $secret);
$encoded = serialize($license);
preg_match("/kayako_licensekey\s?=\s?"([A - Za - z0 - 9_] +) "/", $content, $matches);
$encoded = md5($license["checkdate"] . $secret) . $encoded;
$key = $matches[1];
$encoded = base64_encode($encoded);
if (file_exists($license_file)) {
$content = file_get_contents($license_file);
} else {
echo "Please Upload "license . php" File Inside: " . $dir . "/modules/addons/Kayako/";
}
$content = '';
try {
WHMCS\Database\Capsule::table("tblconfiguration")->where("setting", "kayako_localkey")->update(array("value" => $encoded));
echo "Done!";
}
catch(\Throwable $e) {
echo "There is an issue, contact.";
} ?>
You have extra double quotes in the regular expression. You also have extra spaces inside the [] in the regexp. You can replace that character class with \w, which matches alphanumerics and underscore.
preg_match('/kayako_licensekey\s?=\s?(\w+)/', $content, $matches);
Another problem: You use a number of variables before you assign them:
$modleName
$checkToken
$key
$sellKey
$dir
Did you post the code out of order?
Here is my code to get a list of the file URLs inside a specific directory:
PHP
<?php
function getDirContents($directories, &$results = array()){
$files = array_diff(scandir($directories), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories.DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents($path, $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
return $results;
}
$directories = "directory_A";
echo json_encode(getDirContents($directories));
The result for directory_A:
https://example.com/directory_A/voice1.mp3
https://example.com/directory_A/Media/inside_media_1/voice2.mp3
https://example.com/directory_A/Media/inside_media_1/voice3.mp3
What if we want to get URLs from multiple directories?
I tried to loop through those directories using a for loop like this:
<?php
function getDirContents($directories, &$results = array()){
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents($path, $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
return $results;
}
$directories = array("directory_A", "directory_B");
echo json_encode(getDirContents($directories));
But I only get the files inside those directories and code dosn't go to the folders inside each directory so I only get this for directory_A:
https://example.com/directory_A/voice1.mp3
What I'm missing and how to fix this?
You are passing an array and a string to the function. You have two options. You can always send in an array, or you can look for a string and convert it to an array.
class GoDir
{
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$directories = array("storage", "config");
echo json_encode($this->getDirContents($directories));
}
public function getDirContents($directories, &$results = array())
{
// See if we got a string and convert to array
if ( is_string($directories) ) {
$directories = [$directories];
}
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
$this->getDirContents($path, $results);
} else {
$directory_path = '/';
$results[] = $directory_path . $path;
}
}
}
return $results;
}
// Here is an alternative solution:
public function getDirContents($directories, &$results = array())
{
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
// Turn the param into an array
$this->getDirContents([$path], $results);
} else {
$directory_path = '/';
$results[] = $directory_path . $path;
}
}
}
return $results;
}
}
I have a situation showed in the PHP code below, and I want to make a recursive function called check_recursive().
I have made the check_recursive() function below, but I want a recursive function, if it is possible.
Thank You!
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = $this->check_recursive($old_menu);
function check_recursive($old_menu)
{
$i = 0;
$new_menu = [];
foreach ($old_menu as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$e = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$y = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['id'] = $menu_item['id'] . '|' . $name;
if(isset($menu_item['children']))
{
$a = 0;
foreach ($menu_item['children'] as $menu_item)
{
if($name = $this->check_menu($menu_item['id']))
{
$new_menu[$i]['children'][$e]['children'][$y]['children'][$a]['id'] = $menu_item['id'] . '|' . $name;
}
$a++;
}
}
}
$y++;
}
}
}
$e++;
}
}
}
$i++;
}
return $new_menu;
}
function check_menu($string){
//Check if string exists in database
if($string){
return 'String exists';
}
return false;
}
I came up with this :
$menu = '[{"id":"3|case_studies","children":[{"id":"2|case_studies","children":[{"id":"1|custom_links","children":[{"id":"2|faqe"}]}]}]},{"id":"11|klientet","children":[{"id":"8|klientet","children":[{"id":"7|klientet"}]}]},{"id":"9|klientet","children":[{"id":"10|klientet"}]},{"id":"4|klientet"}]';
$old_menu = json_decode($menu, true);
$new_menu = check_recursive($old_menu);
function check_recursive($old_menu)
{
$new_menu = array();
foreach ($old_menu as $item) {
$name = check_menu($item['id']);
if($name){
$new_item = array(
'id' => $item['id'] . '|' . $name,
);
if(isset($item['children'])){
$new_item['children'] = check_recursive($item['children']);
}
$new_menu[] = $new_item;
}
}
return $new_menu;
}
function check_menu($string)
{
//Check if string exists in database
if ($string) {
return 'String exists';
}
return false;
}
Let me know if it suits your needs.
I'm Using this PHP IMAP Class: http://code.google.com/p/php-imap/source/browse/trunk/ImapMailbox.php on a current project. After a few modifications the class is working. However whenever the class downloads .docx files they are always corrupt and have to be recovered by office.
protected function initMailPart(IncomingMail $mail, $partStruct, $partNum) {
$data = $partNum ? $this->imap_fetchbody($this->mbox, $mail->mId, $partNum, FT_UID) : $this->imap_body($this->mbox, $mail->mId, FT_UID);
if($partStruct->encoding == 1) {
$data = $this->imap_utf8($data);
}
elseif($partStruct->encoding == 2) {
$data = $this->imap_binary($data);
}
elseif($partStruct->encoding == 3) {
$data = $this->imap_base64($data);
}
elseif($partStruct->encoding == 4) {
$data = $this->imap_qprint($data);
}
$data = trim($data);
$params = array();
if(!empty($partStruct->parameters)) {
foreach($partStruct->parameters as $param) {
$params[strtolower($param->attribute)] = $param->value;
}
}
if(!empty($partStruct->dparameters)) {
foreach($partStruct->dparameters as $param) {
$params[strtolower($param->attribute)] = $param->value;
}
}
if(!empty($params['charset'])) {
$data = iconv($params['charset'], $this->serverEncoding, $data);
}
// attachments
if($this->attachmentsDir) {
$filename = false;
$attachmentId = $partStruct->ifid ? trim($partStruct->id, " <>") : null;
if(empty($params['filename']) && empty($params['name']) && $attachmentId) {
$filename = $attachmentId . '.' . strtolower($partStruct->subtype);
}
elseif(!empty($params['filename']) || !empty($params['name'])) {
$filename = !empty($params['filename']) ? $params['filename'] : $params['name'];
$filename = $this->decodeMimeStr($filename);
$filename = $this->quoteAttachmentFilename($filename);
}
if($filename) {
if($this->attachmentsDir) {
$filepath = rtrim($this->attachmentsDir, '/\\') . DIRECTORY_SEPARATOR . $filename;
file_put_contents($filepath, $data);
$mail->attachments[$filename] = $filepath;
}
else {
$mail->attachments[$filename] = $filename;
}
if($attachmentId) {
$mail->attachmentsIds[$filename] = $attachmentId;
}
}
}
if($partStruct->type == 0 && $data) {
if(strtolower($partStruct->subtype) == 'plain') {
$mail->textPlain .= $data;
}
else {
$mail->textHtml .= $data;
}
}
elseif($partStruct->type == 2 && $data) {
$mail->textPlain .= trim($data);
}
if(!empty($partStruct->parts)) {
foreach($partStruct->parts as $subpartNum => $subpartStruct) {
$this->initMailPart($mail, $subpartStruct, $partNum . '.' . ($subpartNum + 1));
}
}
}
protected function decodeMimeStr($string, $charset = 'UTF-8') {
$newString = '';
$elements = $this->imap_mime_header_decode($string);
for($i = 0; $i < count($elements); $i++) {
if($elements[$i]->charset == 'default') {
$elements[$i]->charset = 'iso-8859-1';
}
$newString .= iconv($elements[$i]->charset, $charset, $elements[$i]->text);
}
return $newString;
}
Try wading into the binary files with a good editor, both before and after the round-trip from IMAP, to see if there's something obvious. I've had similar problems where whitespace made its way into the PHP script (e.g. at the end of a file after the close ?> tag); most formats won't blink but .docx may get kicked into a recovery if there's whitespace left over at the end.
I have this function that checks for a filename. If it exists, it increments it by one following this patter:
image.jpg
image1.jpg
image2.jpg
The problem comes on the 4th image, it comes back with 0.jpg.
Here is the relevant code:
...
$filetarget = $this->make_image_filename($directory, $new_filename, $extension);
if(!move_uploaded_file($file['tmp_name'], $filetarget)){
$error[$index] = 'copy';
}
...
private function make_image_filename($directory, $name = '', $extension){
if(empty($name)) $name = 'NULL';
$filetarget = $directory.$name.$extension;
if(file_exists($filetarget)){
$name = $this->increment_filename($name);
return $this->make_image_filename($directory, $name, $extension);
} else {
return $filetarget;
}
}
private function increment_filename($name){
$index = $this->get_filename_index($name);
if(is_numeric($index)){
$pos = strpos($name, $index);
$name = substr($name, 0, $pos);
}
if(is_null($index)){
$index = 0;
}
++$index;
return $name.$index;
}
private function get_filename_index($name){
// CHECK FOR INDEX
$i = 1;
$index = substr($name, -$i);
$last_chars = substr($name, -$i);
while(is_numeric($last_chars)){
++$i;
$last_chars = substr($name, -$i);
if(is_numeric($last_chars)){
$index = $last_chars;
}
}
if(is_numeric($index)){
return $index;
} else {
return NULL;
}
}
I am in the process now of isolating this code on my local server to run some tests. Can you see anything inherently flawed in this process?
Here is a function I use to do the same thing:
function make_unique($full_path) {
$file_name = basename($full_path);
$directory = dirname($full_path).DIRECTORY_SEPARATOR;
$i = 2;
while (file_exists($directory.$file_name)) {
$parts = explode('.', $file_name);
// Remove any numbers in brackets in the file name
$parts[0] = preg_replace('/\(([0-9]*)\)$/', '', $parts[0]);
$parts[0] .= '('.$i.')';
$new_file_name = implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
return $directory.$file_name;
}
(except it make file names like image(1).jpg image(2).jpg)
How about this:
function get_next_file_name($file) {
if (!preg_match('/^(\D+)(\d*)(\.\S+)$/', $file, $match)) {
throw new Exception('bad file name format');
}
return $match[1] . (empty($match[2]) ? 1 : ($match[2] + 1)) . $match[3];
}
echo get_next_file_name('image.jpg'), "\n"; // prints image1.jpg
echo get_next_file_name('image1.jpg'), "\n"; // prints image2.jpg
echo get_next_file_name('image999.jpg'), "\n"; // prints image1000.jpg