PHP Variable Behavior

Hi E's, Something very strange happening in php variable behaviors.
In practice I want resize pictures in Imagemagick, but if I declare the variable in one way the script work, if I declare in other way the script don't work:
In real situation I have to declare the variable in this way:
Var 1 - $novonome = "mod1_" . "$numero" . "." . "jpg"; //The script don't work
and I made a test by declaring the variable differently:
Var 2 - $novonome = "anyname.jpg"; //the script work
Note: I test the variable $numero and work (so, the issue not is the variable $numero)
The line of imagemagick is this one:
exec("/usr/local/bin/convert mod1_imagem_ftp/$novonome -resize 120x120 mod1_imagem_ftp/$novonome");

Why the script work with Var 2 and don't work with Var 1? How I resolve this issue? Will I have to declare the variable differently?

Regards, JC
LVL 4
Pedro ChagasWebmasterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
>Var 1 - $novonome = "mod1_" . "$numero" . "." . "jpg"; //The script don't work

is $numero assigned before that line, or after?
if it's after that line, that's the problem...

you might try this:
$novonome = 'mod1_{$numero}.jpg";
0
VenabiliCommented:
Try:
$novonome = "mod1_" . $numero . "." . "jpg";
?

Other from this - had you tried to pring the value of $novonome just to verofy how it get built?
0
Pedro ChagasWebmasterAuthor Commented:
Hi, I try both solutions and don't work, so I decide post entire code, maybe will more easily get a solution if expert's see all code.
About print the variable $novonome, I test and the result was mod1_78.jpg....mod1_79.jpg etc.

Where it could be the problem?

Regards, JC
<? session_start(); ?>
<? //VERIFICAÇÃO DE DADOS DE LOGIN
if ($_SESSION[estado] != activo) { ?>
	<META HTTP-EQUIV=Refresh CONTENT="0; URL=entrada_login.php?erro=2"> <?
		exit;
			} ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<? include ("../database.php"); //incluir a base de dados ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>M1 - FTP Upload</title>
<style type="text/css" media="screen">
@import "../estilo/painel.css";
</style>
</head>
<? if($_POST['envia'] == 1){ //2000
// Root directory to the files below 
$files_directory = "mod1_imagem_ftp/";

$fdirectory = opendir("$files_directory");

    while ($file=readdir($fdirectory)) { //4000
	//atribuir nome á foto
	$nfoto_result = mysql_query("SELECT * FROM base_mecanica where id = '1'", $db);
	$nfoto_rows = mysql_num_rows($nfoto_result);
	$nfoto = mysql_fetch_object($nfoto_result);
	$numero = $nfoto->mod1_imagem;
	$numero++;
	
	//verificar primeiro se trata de jpg, caso sim executa os procedimentos normais, caso nao apaga o ficheiro
	if (strstr($file, ".jpg") || strstr($file, ".JPG")) { //3000 verificar se se trata de um jpg
		$original = $file; //obter nome original para gravar na bd
		
		//renomear a imagem que fica para tratamento
		$novonome = "mod1_" . "$numero" . "." . "jpg";
		rename("mod1_imagem_ftp/$file", "mod1_imagem_ftp/$novonome");
		
		//copiar uma versao para a pasta de originais
		copy("mod1_imagem_ftp/$novonome", "mod1_imagem_originais/$novonome");
		
		//redimensionar a foto
		exec("/usr/local/bin/convert mod1_imagem_ftp/$novonome -resize 120x120 mod1_imagem_ftp/$novonome");
		
		//copiar a imagem para a pasta para tratar
		copy("mod1_imagem_ftp/$novonome", "mod1_imagem_para_tratar/$novonome");
		
		//remover a foto da pasta de ftp
		unlink("mod1_imagem_ftp/$novonome");
		
		//faz o upgrade para a proxima foto já assumir outro nome
		mysql_query("update base_mecanica set mod1_imagem='$numero' where id='1'", $db);
		//cria uma nova linha para posterior identificação
		$ip = $REMOTE_ADDR;
		$data = date('Y-m-d');
		$hora = date('H:i:s');
		mysql_query("insert into mod_1 set nome='$novonome', nome_original='$original', data='$data', hora='$hora', ip='$ip'", $db);
		
		$sucesso = 1;
		
           } else { //3000 //apaga o que não for jpg's
		   		if("$file" != '.' && "$file" != '..'){
		   unlink("mod1_imagem_ftp/$file"); }
		   	} //3000
    } //4000
closedir($fdirectory);

clearstatcache();
} //2000
?>

<body>
<div id="geral_painel_base">
<div id="logo_principal"><a href="painel_principal.php"><img src="../imagem/logo_preto.jpg" border="0"/></a></div>
<div id="texto_painel_controle">M1 - FTP Upload</div>
<div id="inst_user">Upload via FTP. Ecrã para tratamento de imagens que foram guardadas no servidor através do sistema de FTP.<br />
Caso existam imagens na pasta de FTP, ao carregar em optimizar, estas passarão a estar disponíveis para serem geridas.</div>

<?php
//verificar quantas imagens existem na pasta para serem tratadas
$total_jpg_file=count(glob("mod1_imagem_ftp/*.jpg"));
$total_jpg_file_grande=count(glob("mod1_imagem_ftp/*.JPG"));
$total_jpg = $total_jpg_file + $total_jpg_file_grande;

if($total_jpg_file > 0 || $total_jpg_file_grande > 0){?>
<div id="frases_meio">Existe(m) <strong><? echo $total_jpg; ?> imagen(s)</strong>, as quais aguardam tratamento para posterior gestão.</div>
<? } else { ?>
<? if($sucesso == 1){ ?><div id="erros_user_sucesso">Imagens Convertidas com Sucesso</div> <? } ?>
<div id="frases_meio_red">Não existem imagens para tratamento.</div>
<? } ?>

<? if($total_jpg_file > 0 || $total_jpg_file_grande > 0){?>
<div id="form_base">
<form id="form1" name="form1" method="post" action="painel_modelo1_upload_ftp.php">
<input name="envia" type="hidden" value="1" />
  <label>
  <input type="submit" name="Submit" value="Enviar para tratamento e gestão" />
  </label>
</form>
</div>
<? } ?>

<? //listar as imagens jpg
if($total_jpg_file > 0 || $total_jpg_file_grande > 0){ 1000?>
<div id="listar_ficheiros">
<?
$files = array();

// Root directory to the files below 
$files_directory = "mod1_imagem_ftp/";

$fdirectory = opendir("$files_directory");

    while (false!==($file=readdir($fdirectory))) {
        if (($file != ".") && ($file != ".." )) {
        $files[$file] = filemtime("$files_directory/$file");
        }
    }
closedir($fdirectory);

clearstatcache();
arsort($files);

echo "<table>";
while(list($key, $val)=each($files))
    echo "<tr><td>$key</td><td>".date("M j, h:ia", $val)."</td></tr>\n";
echo "</table>";
} //1000
?>
<div id="botao_atalho_dois"><a href="painel_produtos.php" class="edita_principal">Painel de Produtos</a></div>
</div>





</div>
</body>
</html>

Open in new window

0
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Pedro ChagasWebmasterAuthor Commented:
What code above do is, get pictures from folder, and resize and copy to different folders.
Imagemagick line is in line 43.

Regards, JC
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
ok, debugging...

$test = "/usr/local/bin/convert mod1_imagem_ftp/$novonome -resize 120x120 mod1_imagem_ftp/$novonome";
print $test;
exec($test);
0
Pedro ChagasWebmasterAuthor Commented:
The debugging result (I put your debugging code after line 36):
/usr/local/bin/convert mod1_imagem_ftp/mod1_82.jpg -resize 120x120 mod1_imagem_ftp/mod1_82.jpg
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
so, this shows the problem is elsewhere..
aka, exec will run another "path" location than your php process.
please try to prefix the mod1_imagem_ftp path in your exec by the actual full folder location ...
0
Pedro ChagasWebmasterAuthor Commented:
Hi, I don't understand what I have to do?
Please can you be more clear?
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>$files_directory = "mod1_imagem_ftp/";

this is not the full path... only a relative path.
set the full path ...
0
Pedro ChagasWebmasterAuthor Commented:
I test in this way:
$files_directory = "../painel_controle/mod1_imagem_ftp/";
still not resize the picture

It that the path you want? I can try with http://www.domain.com/etc/etc
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>$files_directory = "../painel_controle/mod1_imagem_ftp/";
is still a relative path ...
please try to put the full path /usr/apache/htdocs/... etc .etc /
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
of course:
$test = "/usr/local/bin/convert mod1_imagem_ftp/$novonome -resize 120x120 mod1_imagem_ftp/$novonome";
will need to be:

$test = "/usr/local/bin/convert $files_directory/$novonome -resize 120x120 $files_directory/$novonome";
0
Pedro ChagasWebmasterAuthor Commented:
I try to use also (I think is the full path):
$files_directory = "/home/luis/public_html/painel_controle/mod1_imagem_ftp/";
Still not work.

I test: exec("/usr/local/bin/convert $files_directory/$novonome -resize 120x120 $files_directory/$novonome");
WITH:
$files_directory = "/home/luis/public_html/painel_controle/mod1_imagem_ftp/";
and
$files_directory = "mod1_imagem_ftp/";

Nothing new! Still not work.
0
Pedro ChagasWebmasterAuthor Commented:
For help I put phpinfo here:
http://w.e-e.com/ZXQDHD
0
Pedro ChagasWebmasterAuthor Commented:
Another thing is, if I put directly the name of the file in this way the script work:
exec("/usr/local/bin/convert mod1_imagem_ftp/$novonome -resize 120x120 mod1_imagem_ftp/nameofthefile.jpg");

As you can see I use $novonome for call the picture, so I supose $novonome don't have any problem!

Never seen anything so weird in the language of PHP
0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
I am lost, then ....
0
VenabiliCommented:
Hold on a second - are you trying to actually trying to replace the original files?

Because in all cases when this works above, you seem to be specifying a different name for the new file than the name of the original one. While in the case that does not work (incidently being teh one with the variable), it is the same name as the original.

So does
exec("/usr/local/bin/convert mod1_imagem_ftp/nameofthefile.jpg -resize 120x120 mod1_imagem_ftp/nameofthefile.jpg");
work? (replace nameofthefile.jpg with a real file name. )

And even if it does - can you just try renaming using another filename (because otherwise it really makes no sense... :(
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Pedro ChagasWebmasterAuthor Commented:
Hi, @thanks Venabili, The solution is change the name of pictures, I had to restructure the whole PHP code because I have to assign a new name. Can check the new changes in the snippet code, I had a little more work, but it works.

@angellll, thanks for you too.

The best regards, JC
<? session_start(); ?>
<? //VERIFICAÇÃO DE DADOS DE LOGIN
if ($_SESSION[estado] != activo) { ?>
	<META HTTP-EQUIV=Refresh CONTENT="0; URL=entrada_login.php?erro=2"> <?
		exit;
			} ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<? include ("../database.php"); //incluir a base de dados ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>M1 - FTP Upload</title>
<style type="text/css" media="screen">
@import "../estilo/painel.css";
</style>
</head>
<? if($_POST['envia'] == 1){ //2000
// Root directory to the files below 
$files_directory = "mod1_imagem_ftp/";

$fdirectory = opendir("$files_directory");

    while ($file=readdir($fdirectory)) { //4000
	//atribuir nome á foto
	$nfoto_result = mysql_query("SELECT * FROM base_mecanica where id = '1'", $db);
	$nfoto_rows = mysql_num_rows($nfoto_result);
	$nfoto = mysql_fetch_object($nfoto_result);
	$numero = $nfoto->mod1_imagem;
	$numero++;
	
	//verificar primeiro se trata de jpg, caso sim executa os procedimentos normais, caso nao apaga o ficheiro
	if (strstr($file, ".jpg") || strstr($file, ".JPG")) { //3000 verificar se se trata de um jpg
		$original = $file; //obter nome original para gravar na bd
		
		//arranjar 4 digitos aleatorios para juntar ao nome da fotografia para protejer de ser vista directamente atraves do directorios pelo usuario
		$chavegrande = md5(rand());
		$chave = substr($chavegrande, 0, 4);
		
		//renomear a imagem que fica para tratamento
		$novonome = "mod1_" . "$numero" . "." . "jpg";
		$novonomedois = "mod1_" . "$chave" . "_" . "$numero" . "." . "jpg";
		rename("mod1_imagem_ftp/$file", "mod1_imagem_ftp/$novonome");
		
		//copiar uma versao para a pasta de originais
		copy("mod1_imagem_ftp/$novonome", "mod1_imagem_originais/$novonomedois");
		
		//copiar para a pasta de fotos grandes
		copy("mod1_imagem_ftp/$novonome", "mod1_imagem_grandes/$novonome");
		
		//redimensionar a foto pequena
		exec("/usr/local/bin/convert mod1_imagem_ftp/$novonome -resize 120x120 mod1_imagem_ftp/$novonomedois");
		
		//redimensionar a foto grande
		exec("/usr/local/bin/convert mod1_imagem_grandes/$novonome -resize 380x380 mod1_imagem_grandes/$novonomedois");
		
		//copiar a imagem para a pasta para tratar
		copy("mod1_imagem_ftp/$novonomedois", "mod1_imagem_para_tratar/$novonomedois");
		
		//remover a foto da pasta de ftp
		unlink("mod1_imagem_ftp/$novonome");
		unlink("mod1_imagem_ftp/$novonomedois");
		unlink("mod1_imagem_grandes/$novonome");
		
		//faz o upgrade para a proxima foto já assumir outro nome
		mysql_query("update base_mecanica set mod1_imagem='$numero' where id='1'", $db);
		//cria uma nova linha para posterior identificação
		$ip = $REMOTE_ADDR;
		$data = date('Y-m-d');
		$hora = date('H:i:s');
		mysql_query("insert into mod_1 set nome='$novonomedois', nome_original='$original', data='$data', hora='$hora', ip='$ip'", $db);
		
		$sucesso = 1;
		
           } else { //3000 //apaga o que não for jpg's
		   		if("$file" != '.' && "$file" != '..'){
		   unlink("mod1_imagem_ftp/$file"); }
		   	} //3000
    } //4000
closedir($fdirectory);

clearstatcache();
} //2000
?>

<body>
<div id="geral_painel_base">
<div id="logo_principal"><a href="painel_principal.php"><img src="../imagem/logo_preto.jpg" border="0"/></a></div>
<div id="texto_painel_controle">M1 - FTP Upload</div>
<div id="inst_user">Upload via FTP. Ecrã para tratamento de imagens que foram guardadas no servidor através do sistema de FTP.<br />
Caso existam imagens na pasta de FTP, ao carregar em optimizar, estas passarão a estar disponíveis para serem geridas.</div>

<?php
//verificar quantas imagens existem na pasta para serem tratadas
$total_jpg_file=count(glob("mod1_imagem_ftp/*.jpg"));
$total_jpg_file_grande=count(glob("mod1_imagem_ftp/*.JPG"));
$total_jpg = $total_jpg_file + $total_jpg_file_grande;

if($total_jpg_file > 0 || $total_jpg_file_grande > 0){?>
<div id="frases_meio">Existe(m) <strong><? echo $total_jpg; ?> imagen(s)</strong>, as quais aguardam tratamento para posterior gestão.</div>
<? } else { ?>
<? if($sucesso == 1){ ?><div id="erros_user_sucesso">Imagens Convertidas com Sucesso</div> <? } ?>
<div id="frases_meio_red">Não existem imagens para tratamento.</div>
<? } ?>

<? if($total_jpg_file > 0 || $total_jpg_file_grande > 0){?>
<div id="form_base">
<form id="form1" name="form1" method="post" action="painel_modelo1_upload_ftp.php">
<input name="envia" type="hidden" value="1" />
  <label>
  <input type="submit" name="Submit" value="Enviar para tratamento e gestão" />
  </label>
</form>
</div>
<? } ?>

<? //listar as imagens jpg
if($total_jpg_file > 0 || $total_jpg_file_grande > 0){ 1000?>
<div id="listar_ficheiros">
<?
$files = array();

// Root directory to the files below 
$files_directory = "mod1_imagem_ftp/";

$fdirectory = opendir("$files_directory");

    while (false!==($file=readdir($fdirectory))) {
        if (($file != ".") && ($file != ".." )) {
        $files[$file] = filemtime("$files_directory/$file");
        }
    }
closedir($fdirectory);

clearstatcache();
arsort($files);

echo "<table>";
while(list($key, $val)=each($files))
    echo "<tr><td>$key</td><td>".date("M j, h:ia", $val)."</td></tr>\n";
echo "</table>";
} //1000
?>
<div id="botao_atalho_dois"><a href="painel_produtos.php" class="edita_principal">Painel de Produtos</a></div>
</div>





</div>
</body>
</html>

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.