GenesisTepait
GenesisTepait

Reputation: 73

How to change a variable outside an "if" clause

I am still a student and new to PHP and web development in general. I wanted to update the $f1 variable via a button but i could not seem to do it. Is there something that I have been missing?

I have tried the following (simplified) code:

<?php

$f1="s";

//user presses a button to change the variable
if(isset($_POST['emp_sig']) && !empty($_POST['emp_sig'])){

$upload_dir1 = "signatures/EmployeeSignatures/";
$file1= $upload_dir1 . mktime() . ".png";
$GLOBALS['f1'] = $file1;
$success = file_put_contents($file1, $data1);
print $success ? $file1 : 'Unable to save the file.';


}


//user now presses another button to echo the updated variable
if(isset($_POST['submit'])){


echo $GLOBALS['f1'];

}

?>

It does not echo an updated variable but it echoes "s". Any help would be greatly appreciated. Thanks.

Upvotes: 1

Views: 58

Answers (2)

GenesisTepait
GenesisTepait

Reputation: 73

Using $_SESSION solved my problem.

<?php

session_start();

//user presses a button to change the variable
if(!empty($_POST['emp_sig'])){

$upload_dir1 = "signatures/EmployeeSignatures/";
$file1= $upload_dir1 . mktime() . ".png";
$_SESSION["path1"] = $file1;
$success = file_put_contents($file1, $data1);
print $success ? $file1 : 'Unable to save the file.';


}


//user now presses another button to echo the updated variable
if(isset($_POST['submit'])){


echo $f1 = $_SESSION["path1"];

}

?>

Thank you for all those who helped

Upvotes: 0

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2190

You don't have to use globals, you can directly access the variable.

$f1="s";

//user presses a button to change the variable
if(!empty($_POST['emp_sig'])){
    $upload_dir1 = "signatures/EmployeeSignatures/";
    $file1= $upload_dir1 . mktime() . ".png";
    $f1 = $file1;
    $success = file_put_contents($file1, $data1);
    print $success ? $file1 : 'Unable to save the file.';
}

//user now presses another button to echo the updated variable
if(isset($_POST['submit'])){
    echo $f1;
}

Upvotes: 1

Related Questions