The question references bargraph.html
- presumably the php code that you have is NOT on that page but a separate script? If that is the case then if you were to use exception handling to try to track down the issue it might help. Also, I have always found better success when using full paths as opposed to relative ones
<?php
if( isset( $_GET['mn'], $_GET['di'] ) ){
try{
$filename='cred.txt';
$mobile_num=filter_input( INPUT_GET, 'mn', FILTER_SANITIZE_STRING );
$device_id=filter_input( INPUT_GET, 'di', FILTER_SANITIZE_STRING );
/*
I have always found it is best to use a full path rather than relative
Change `path/to/` to the appropriate path
*/
$path=$_SERVER['DOCUMENT_ROOT'] . '/path/to/cred';
/* If the path does not exist, warn user */
if( !realpath( $path ) ){
throw new Exception( sprintf( 'Unable to find path: %s', $path ) );
}
/* Can the chosen directory be read? */
if( is_readable( $path ) && is_writable( $path ) ){
$file=$path . '/' . $filename;
#$text=$mobile_num . PHP_EOL . $mobile_num . PHP_EOL;
/* I think this is probably what you intended? */
$text=$device_id . PHP_EOL . $mobile_num . PHP_EOL;
$status=file_put_contents( $file, $text, FILE_APPEND | FILE_TEXT );
throw new Exception( $status ? sprintf('All good! Saved %s',$file) : sprintf('Error - unable to save %s',$file) );
} else {
/*
should set permissions if reading/writing of target folder failed
chmod($path,0777); etc
*/
throw new Exception( sprintf( 'The path %s is either not readable or writable',$path ));
}
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
?>
Using a plain HTML page you could send an ajax request to the above PHP script ( in code below called bargraph.php
)
<html>
<head>
<title>ajax-store credentials</title>
</head>
<body>
<form id='bg'>
<input type='text' name='mn' id='mn' placeholder='Mobile number: eg 0141 353 3874' />
<input type='text' name='di' id='di' placeholder='Device ID: eg yellow banana' />
<input type='button' id='bttn' value='Go' />
</form>
<script>
document.getElementById('bttn').onclick=function(e){
var mn=document.getElementById('mn').value;
var di=document.getElementById('di').value;
if( mn != '' && di != '' ){
var xhr=new XMLHttpRequest();
xhr.onload=function(r){
document.getElementById('status').innerHTML=this.response;
};
xhr.onerror=function(r){
document.getElementById('status').innerHTML=err.message;
};
xhr.open('GET','?mn='+mn+'&di='+di,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
}
</script>
<div id='status'></div>
</body>
</html>