I wrote small script that send an email to me when the IP was modified on my computer.
The script works. I just have small PHP question:
I declare $filename at the beginning of the script. So $filename I suppose should be available from everywhere.
In these function I use this variable in order to open the file:write_ip_to_the_file & get_old_ip.
However, when I use the variable from the top I get such message:
<b>Warning</b>: fopen("", "r") - Operation now in progress in...
But When I declare the variable locally in each function I don't get the message. Any ideas why?
How variable should be declare, in order to be availabe from functions?
<?php
//Curl request
$filename = "existingIP.dat";
$ch = curl_init("ip.php");
ob_start();
curl_exec($ch);
curl_close($ch);
$retrievedhtml = ob_get_contents();
ob_end_clean();
//String parsing and removing unnecessary data
$withnotags = strip_tags($retrievedhtml);
//$length_of_string = strlen($withnotags);
$last_occurance = substr($withnotags,0,15);
$previous_ip = get_old_ip();
if($last_occurance != $previous_ip) {
echo 'Changed IP';
send_email_with_ip($last_occurance);
write_ip_to_the_file($last_occurance);
}
//#########################################################
//SEND_EMAIl_WITH_IP: returns none
//#########################################################
function send_email_with_ip($last_occurance) {
//Creating Send Email Data
$to = 'root@localhost';
$today = date("F j, Y, g:i a");
$new_ip = $last_occurance."\t".$today;
$Data = $last_occurance."\t".$today;
//Creating header for Email
$headers = "From:".$to."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
mail($to, $new_ip, $Data, $headers);
}
//#########################################################
//WRITE_IP_TO_THE_FILE: returns none
//#########################################################
function write_ip_to_the_file($last_occurance) {
$filename = "existingIP.dat";
if(!$handle = fopen($filename, 'w')){
print "Cannot open file ($filename)";
exit;
}
if(is_writable($filename)) {
if(!fwrite($handle, $last_occurance)){
print "Cannot write to file ($filename)";
exit;
}
}
fclose($handle); //Close the file
}
//#########################################################
//GET_OLD_IP: returns old_ip
//#########################################################
function get_old_ip() {
$filename = "existingIP.dat";
//Open the file
if(!$handle = fopen($filename, "r")) {
print "Cannot open file ($filename)";
exit;
}
if(is_readable($filename)) {
if(!$old_ip = fread($handle,15)) {
print "Cannot read from the ($filename)";
}
}
fclose($handle);//Close the file
return $old_ip;
}
?>