The issue is that the global
keyword doesn't make an existing variable a global one. Instead, it tells PHP that when you refer to a variable by that name, it should look in the global scope.
You have two options to fix this:
1. Use different variable names for parameters than you do for the globals
<?php
function addImage($imgFolder, $imgName) {
global $imageName;
$imageName = 'stackoverflow'.$imgName;
if (condition) {
global $imageFolder;
$imageFolder = $imgFolder;
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return true;
}
}
}
if(addImage('image/', $imageName)){
echo $imageName;
echo $imageFolder;
}
?>
2. Use the $GLOBALS
variable
<?php
function addImage($imageFolder, $imageName) {
$imageName = 'stackoverflow'.$imageName;
$GLOBALS['imageName'] = $imageName;
if (condition) {
$GLOBALS['imageFolder'] = $imageFolder;
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return true;
}
}
}
if(addImage('image/', $imageName)){
echo $imageName;
echo $imageFolder;
}
?>
3. Don't use globals (probably a better solution) [Thanks Robbie Averill]
<?php
function addImage($imageFolder, $imageName) {
$imageName = 'stackoverflow'.$imageName;
if (condition) {
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return $imageName;
}
}
return false;
}
$imageFolder = 'image/';
if($imageName = addImage($imageFolder, $imageName)){
echo $imageName;
echo $imageFolder;
}
?>