Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Thanked 0 Times in 0 Posts

    problem with php code

    what is wrong i get an error when i click the button.
    using wampserver and trying it in the local network.

    PHP Code:

    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 
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
    <input type="submit" name="submit" value="Click Me">

  • #2
    Senior Coder
    Join Date
    Apr 2011
    London, England
    Thanked 354 Times in 353 Posts
    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.

    PHP Code:
    <!DOCTYPE html>
        <title>Your Title</title>
    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  

    <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">
    But test your code in different browsers as well, as they have different policies for local-file access.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts