Frankie Frankie - 1 month ago 10
PHP Question

Php - passing variable inside an array

my script work fine if this function is written :

$extension_allowed =array(".pdf",".jpg",".jpeg",".png",".txt",".doc",".docx", ".odt", ".rtf", ".xls", ".xlsx", ".ods");


But, if I want config the extensions from application config and extract this extension from a query, how to pass the extensions inside an array?

// extensions
$extensionsUploadFileQ = mysql_query("
SELECT
*
FROM table_config
WHERE field1 = 'EXTENSIONS_UPLOAD'
");
$extensionsUploadFileR=mysql_fetch_array($extensionsUploadFileQ);
$extensionUploadFileParameter=$extensionsUploadFileR['value_extensions'];


the result of query, passing at the variable $extensionUploadFileParameter but not work by this array:

$extension_allowed =array($extensionUploadFileParameter);


How to fix this?

Thanks

Answer

If I understood well in you MySQL DB you have your "EXTENSIONS_UPLOAD" as a string like ".pdf,.jpg,.jpeg,.png,.txt,.doc,.docx" and you want just to convert it to the PHP array type.

If yes then try to use explode PHP function:

// extensionUploadFileParameter = ".pdf,.jpg,.jpeg";
$extension_allowed = explode(",", $extensionUploadFileParameter);

/* 
   $extension_allowed will have:

   array(3)
   (
     [0] => string(4) ".pdf"
     [1] => string(4) ".jpg"
     [2] => string(4) ".jpeg"
   )
*/

OR

// extensionUploadFileParameter = '".pdf",".jpg",".jpeg"';
preg_match_all('/(.\w+)/', $extensionUploadFileParameter, $matches);  
$extension_allowed = $matches[0];

/*
 $extension_allowed will have:

 Array
 (
   [0] => .pdf
   [1] => .jpg
   [2] => .jpeg
 )
*/

I hope it helps.

Good luck.

P.S. Try to avoid using "eval" function:

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Comments