...

View Full Version : problem with php code



dreampixz
07-29-2012, 10:06 AM
what is wrong i get an error when i click the button.
using wampserver and trying it in the local network.


<html>

<?php
if(isset($_POST['submit'])) {
$textfile = "LEDstate.txt"; // Declares the name and location of the .txt file
$fileLocation = "$textfile";
$fh = fopen($fileLocation, 'w ') or die("Something went wrong!"); // Opens up the .txt file for writing and replaces any previous content
$stringToWrite = "1"; // Write either 1 or 0 depending on request from index.html
fwrite($fh, $stringToWrite); // Writes it to the .txt file
fclose($fh);
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="submit" value="Click Me">
</form>
</html>

AndrewGSW
07-29-2012, 03:30 PM
It works for me if I don't use the shorthand tag <?=, but use the full version <?php instead. I prefer to do this anyway as it is more reliable.

It is discussed in several threads that we should not rely on $_POST['submit'] and W3C recommend that we should not name our submit button 'submit'. Instead use a hidden (or other) field to indicate form submission.

It is also preferable to create properly formed HTML, and I add IDs to form elements - in case it's useful to JavaScript at a later stage.


<!DOCTYPE html>
<html>
<head>
<title>Your Title</title>
</head>
<body>
<?php
if(isset($_POST['submitted'])) {
$textfile = "LEDstate.txt"; // Declares the name and location of the .txt file
$fileLocation = $textfile;
$fh = fopen($fileLocation, 'w') or die("Something went wrong!");
// Opens up the .txt file for writing and replaces any previous content
// Write either 1 or 0 depending on request from index.html
$stringToWrite = "1";
fwrite($fh, $stringToWrite); // Writes it to the .txt file
fclose($fh);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="hidden" id="submitted" name="submitted" value="TRUE">
<input type="submit" id="iSubmit" name="iSubmit" value="Click Me">
</form>
</body>
</html>

But test your code in different browsers as well, as they have different policies for local-file access.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum