If you are just creating a single PHP file on it's own and not checking any parameters, then the user is not in any course at all (imagine, for a moment, the user has 3 tabs open, with 3 different courses displayed - if you open a 4th tab with your script in it, then which course is the user in?)
When you link to your script, you are going to need to include some sort of URL param to indicate which course (or activity, etc.) this page access relates to, you can then do:
$courseid = required_param('courseid', PARAM_INT);
After that, you can use $PAGE->course or $COURSE as the course that the user is part of.