if(!empty($_POST['newdir'])) {
$dir_base= preg_replace("/[^a-zA-ZÀ-ÿ0-9\s]/",'',$_POST['newdir']);
$dir_path=$pattern.$dir_base;
$dir_path_lwr = strtolower($dir_path);
$old_dirs = glob($pattern.'*', GLOB_ONLYDIR);
$old_dirs_lwr = array_map('strtolower', $old_dirs);
$i = 1;
$cond = true;
while($cond) {
if(in_array($dir_path_lwr, $old_dirs_lwr)) {
$i++;
$new_base=$dir_base.' '.$i.'';
$new_path= $pattern.$new_base;
$dir_path_lwr = strtolower($new_path);
}
elseif(!in_array($dir_path_lwr, $old_dirs_lwr)) {
mkdir($dir_path, 0755);
$cond = false;
}
}
}
EDIT Have changed the above to the most recent version. For testing, I am now simply echoing out the $cond var rather than creating directories all over the place. The 'Not In' argument works fine - when a duplicate name IS found, the page takes about 10 to 12 seconds to load, before white screening. There's something wrong with my while loop i think...
What I'm trying to do is:
Submit a new directory name to the script
Clean and escape that name
Check it against existing directories in that location ($pattern)
If there is no conflict, create the directory (works)
If there is a conflict, append a number (eg, My Directory 2) and then create the directory (doesn't work)
So, basically how to check against existing file names, and create a uniquely name directory dynamically. All help appreciated :)
Fixed it - i was confusing the vars within the loop.
Posting for future reference:
if(!empty($_POST['newdir'])) {
$dir_base= preg_replace("/[^a-zA-ZÀ-ÿ0-9\s]/",'',$_POST['newdir']);
$dir_path=$pattern.$dir_base;
$dir_path_lwr = strtolower($dir_path);
$old_dirs = glob($pattern.'*', GLOB_ONLYDIR);
$old_dirs_lwr = array_map('strtolower', $old_dirs);
$i = 1;
$cond = true;
while($cond) {
if(in_array($dir_path_lwr, $old_dirs_lwr)) {
$i++;
$new_base=$dir_base.' '.$i.'';
$dir_path= $pattern.$new_base;
$dir_path_lwr = strtolower($dir_path);
}
elseif(!in_array($dir_path_lwr, $old_dirs_lwr)) {
mkdir($dir_path, 0755);
$cond = false;
}
}
}
Related
I have paths that goes like this template:
`/dir1/dir2/dirN/dirNplus1/dirNplus2/`
And for an example to demonstrate this template:
`/var/www/sei/modules/module1/`
I would like to be able to have a function where I could input a full path and a specific directory and get in return only the right part of the path, removing the left part including the directory specified in the parameter.
In the example given, if I would use:
`function('/var/www/sei/modules/module1/', 'sei')`
Then I would like to get the result as:
`/modules/module1/`
Any ideas on how to achieve this?
As #ADyson suggested, I wrote this code below:
const DIRETORIO_SEI = 'sei';
private static $caminho;
public static function getCaminhoModulo($append = '') {
if (self::$caminho != null) {
return self::$caminho;
}
$diretorio = explode('/', realpath(__DIR__.'/../../../'));
$caminho = '';
$incluir = false;
for ($i = 0; $i < count($diretorio); $i++) {
if ($incluir) {
$caminho = $caminho . $diretorio[$i] . '/';
}
if ($diretorio[$i] == self::DIRETORIO_SEI) {
$incluir = true;
}
}
self::$caminho = $caminho;
return $caminho.$append;
}
I want to check if there are any image record in my database that is not in my folder of images, but I cant seem to find a way to do this and I dont know why, I made this code:
$result = mysql_query("SELECT imagen FROM galerias", $dbh);
$flag = true;
mysql_data_seek($result, 0);
while($row2 = mysql_fetch_assoc($result)) {
$directorio = opendir("../galeria/programas");
while ($archivo = readdir($directorio)) {
if($archivo == $row2["imagen"]){
$flag = false;
}
}
if ($flag) {
echo "IM NOT IN THE FOLDER ".$row2["imagen"]."<br>";
}
}
?>
It's only load one record only..
I think the mistakes is on the $flag, you did not reset the $flag after each check. So if there is one file that equals to the one on the DB, which makes the $flag false, the rest will be considered equals since $flag will be always false after that.
And it is better using strcmp for comparing string rather use "==". It is more binary safe.
I have a php application where users upload specific images, and the number of images can be different per user. I have a variable set on startup as false for each image that i change to true once its done.
For example one user might have to upload 3 and have so far done 2 so:
$required = 3;
$houseImageStatus1 = true;
$houseImageStatus2 = true;
$houseImageStatus3 = false;
Another then may have to upload 5 and have done them all:
$required = 5;
$houseImageStatus1 = true;
$houseImageStatus2 = true;
$houseImageStatus3 = true;
$houseImageStatus4 = true;
$houseImageStatus5 = true;
I need to be able to check that all required images have been uploaded before continuing. At the moment i have a very long-winded and ugly way be doing:
if($required==3){
if($houseImageStatus1==true &&
$houseImageStatus2==true &&
$houseImageStatus3==true){
// allow continue
}
else {
// pause
}
}
if($required==5){
if($houseImageStatus1==true &&
$houseImageStatus2==true &&
$houseImageStatus3==true &&
$houseImageStatus4==true &&
$houseImageStatus5==true){
// allow continue
}
else {
// pause
}
}
Can i do the above but in a much shorter and cleaner way? Maybe in some sort of array and loop through them as a function?
Use arrays for this purposse:
$houseImageStatus[1] = true;
$houseImageStatus[2] = true;
$houseImageStatus[3] = false;
and then check if all are true:
if (count(array_unique($houseImageStatus)) === 1 && $houseImageStatus[0] === true) {
// here you go
} else {
// nope
}
You Could use either:
Array and check for falses in array and by checking the index of array, You could determine the size (here you named it as $required).
OR
Using a counter which increments with each uploading of images....
Use different counters with different users . You dont have to give seperate variables for each user.. You could use any existing user dependant variables like user_id or user_name..
Store the boolean values in an array, use array_filter to remove the false values and then check the array size against your variable $required:
$houseImageStatus = array();
$houseImageStatus[0] = true;
$houseImageStatus[1] = true;
$houseImageStatus[2] = false;
// and so on
if(sizeof(array_filter($houseImageStatus)) == $required){
// everything is okay
}
else{
// something is wrong
}
You can do array with all values set to false:
$houseimages = array();
$n = 5; // How many pictures
for($i = 0; $i < $n; $i++) $houseimages[$i] = false; // Set all to false
And now, when user uploads one picture, just set $houseimages[0] = true; and so on.
Later just look through array and check if all values are true or not.
$required = 3;
$filled =0;
$houseImageStatus1 = true; $filled=$filled+1;
if ($required==$filled){//continue} else {//pause}
I'm just working on the Backend of a project an have a small problem with this snippet
if (isset($_POST['id'])) {
$cat_delete = "DELETE FROM category WHERE categoryid='".$_POST['id']."' ";
$cat_delete_ex = mysql_query($cat_delete);}`
But if the id is set with post, nothing happens.
The mysql query is working when I delete the
if (isset($_POST['id']))
anyone have an idea ?
Well I am not sure if your method is safe or not, but I would do it like this, might even throw in a regex to check for just numbers if the id is numeric:
EDIT: I made a revision, since you are dealing with an ID, I will assume the ID is numeric only, so instead of escaping it, I just will strip out everything but numbers. This may be a better fit for your situation. I also converted the function to a class so you will be able to reuse the script for several types of sanitizing strings. Maybe its because I am an overachiever too, I don't know. ADD, OCD, etc. Blame it on that :)
$postID = isset($_POST['id']) ? sanitize::ID($_POST['id']) : '';
if (sanitize::email("test#example.com")){
echo "Real email";
} else {
echo "Fake email";
}
if ($postID != ''){
$cat_delete = "DELETE FROM category WHERE categoryid='".$postID."' ";
$cat_delete_ex = mysql_query($cat_delete);
}
class sanitize{
function ID($string){
$string = preg_replace('/[^0-9,]|,[0-9]*$/','',$string);
return $string;
}
# I added another sanitize function so you can see what you can do
# with it. Add phone numbers, domain names, etc... Each one could
# be called with sanitize::{FUNCTION}
function email($string){
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $string)) {
return false;
}
$email_array = explode("#", $string);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",$local_array[$i])) return false;
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) return false;
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) return false;
}
}
return true;
}
}
are you sure you are using post for the id?(asking because is the right way, but i have one too many times
<form action="action.php?id=hereistheid"
which will bring the id in the $_GET not $_POST.
next the checking
$id=(int)$_POST['id'];
if($id)
{
//do smth
}
I have 2 questions
1.) how to write update_defile($array_value){...} function?
define_file.php
<?php
define("FIST_NAME", "something1");
define("LAST_NAME", "something2");
define("ADDRESS", "something3");
?>
"something" is not a constant value that can be change every method Call(update_defile($array_value)
value set
$array_value = ("FIST_NAMe" => "duleep", "LAST_NAME" => "dissnayaka", "AGE" => "28" );
after call method(update_defile($array_value){.....}) "define_file.php"
file want to be look like bellow
<?php
define("FIST_NAME", "duleep");
define("LAST_NAME", "dissnayaka");
define("ADDRESS", "something3");
define("AGE", "28");
?>
2).
My datbase is Oracle. I already saved configuration value in the data base but frequently use these configuration value for my application. So i get value form database and save in the define_file.php as increase performance(down rate database call) but I'm not sure i can increase performance keep configuration value in the PHP file please explain. what is the best way increase performance my application and other alternative solutions welcome.
Why cant u use session to store such values , then u can access and modify from anywhere
in the script.
<?php
session_start();
$_SESSION["FIST_NAME"]= "something1";
$_SESSION["LAST_NAME"]= "something2";
$_SESSION["ADDRESS"]= "something3";
?>
public function update($form_config_arr)
{
if( (is_readable($config_file_path)) && is_writable($config_file_path))
{
if(!$config_old_file_content = file_get_contents($config_file_path))
{
throw new Exception('Unable to open file!');
}
$i = 0;
$config_old_arr = array();
$config_new_arr = array();
foreach ($form_config_arr as $constant => $value){
$config_old_line = $this->getLine($constant);
$config_old_arr[$i] = $config_old_line;
if(($value == 'true') || ($value == 'false')){
$config_new_arr[$i] = "define ( '$constant', $value );\n";
}else{
$config_new_arr[$i] = "define ( '$constant', '$value' );\n";
}
$i++;
}
$config_new_file_content = str_replace($config_old_arr, $config_new_arr, $config_old_file_content);
$new_content_file_write = file_put_contents($config_file_path, $config_new_file_content);
foreach ($config_new_arr as $constant => $value)
{
echo $value.'<br/>';
}
return true;
}else{
throw new Exception('Access denied for '.$config_file_path);
return false;
}
}
/**
*
* #param string $constant
* #return string
*/
private function getLine($constant)
{
$match_line = '';
$config_file = fopen($config_file_path, "r");
if($config_file)
{
//Output a line of the file until the end is reached
$i = 0;
while(!feof($config_file))
{
$i++;
$config_old_line = fgets($config_file);
$pos = strpos($config_old_line, $constant);
if( $pos !== false )
{
$match_line= $config_old_line;
}
}
fclose($config_file);
return $match_line;
}else{
throw new Exception('Unable to open file!');
}
}
What you are trying to do is edit a file.
Simply create another php script: updater.php
It should poll the database, fetch the values and update the values in define_file.php
Look for php file handling functions here: http://www.w3schools.com/php/php_file.asp