简体   繁体   中英

PHP fopen() and fwrite() dont work?

I wanted a php script to execute when the user press the button. In my html file i used a jquery script

<script>
        $(document).ready(function(){
            $(".btn").click(function(){

                var firstname = $("#firstname").val();
                var lasname = $("#lastname").val();
                var dataNames = { 'firstnameVal' : firstname};
                $.post("SaveNames.php",dataNames,function()
                       {
                    alert("hi");
                });
            });   
        });                
    </script>

and

<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">

in my php file i used some help from here

<?php

if (isset($_POST["fistname"]))
{
        $firstname = $_POST["firstname"];
        $SavedNames = fopen("Names.txt","w");

        $NamesText = "Its Work!";

        fwrite($SavedNames,$NamesText);
        fclose($SavedNames);
}
?>

The problem is the fopen() doesn't work (don't create file) and I tried to create the file to check if fwrite() works but it's also didn't worked.

I use localhost wamp server.

Try to set the complete path to your file:

fopen("c:\\folder\\Names.txt", "w");

Make sure file permissions are set correctly (writeable) to c:\\\\folder\\\\ . Pay attention to lower-/uppercase naming.

Try if this works:

if (isset($_POST["firstname"]))
{
        $firstname = $_POST["firstname"];
        if(file_put_contents("Names.txt", $firstname) !== false)
            echo "It works!\n";
}

Firstly, isset($_POST["fistname"]) , you mispelled "firstname".

Secondly, on the php side you use $_POST['firstname'] . But in the javascript, you have

var dataNames = { 'firstnameVal' : firstname};

Try it with

var dataNames = { 'firstname' : firstname};

As saided, try checking if the folder in which you are trying to write exist and have privileges to write in. But first clear your mispelling errors and variable names. Code below will post value with name which you declared in brackets. So in your example firstnameVal. So you need to check if this POST value exist.

var dataNames = { 'firstnameVal' : firstname};

If this didn't work use php function var_dump['variableName']; to display data after post method. So you can get handle on data flow in your files.

问题是从wampserver重新安装的,它确实起作用了

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM