2016-03-11 21:36
浏览 151

使用PHP将Ajax POST数据保存到文件

I am posting some data to a PHP file using ajax and saving it to a MySQL database. This works fine, but I also want to save one of the data elements to a text file (which should be created) on the server but I can't get it to save to a file.

This is how my code looks:

jQuery (snippet)

        var uid = "1";
        var name = "bruno";
        var number = "0889-123-123";
        var location = "{"locationInfo":[{"title":"home","lat":-16.450902223672625,"lng":10.6103515625,"speed":""},{"title":"work","lat":-14.94621907436008,"lng":17.99560546875,"speed":""}]}"
        type: "POST",
        url: "process.php",
        data: {uid:uid, name:name, number:number, location:location},
        dataType: 'json',
        cache: false,

PHP - process.php

    $inputvalues = $_POST;
    $errors = false;
    $result = false;
    $mysqli = new mysqli('localhost', "root", "", "tp");

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s
", mysqli_connect_error());
            foreach ($inputvalues as $key => $value) {
            if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
            } else {
                $errors[$key] = 'The field '.$key.' is empty';

        if( !$errors ) {
                INSERT INTO `table`(`uid`, `name`, `number`) 
                values ('".$inputvalues['uid']."', '".$inputvalues['name']."', '".$inputvalues['number']."');
            file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));
        $returnResult ="success";
        echo json_encode(['result' => $returnResult, 'errors' => $errors]);
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dotaer1993 2016-03-11 21:53

    change this:

    file_put_contents('saved/file.txt', file_get_contents('".$inputvalues['location']."'));

    to this:

    file_put_contents('saved/file.txt', $inputvalues['location']);

    Also, in JS you need to remove the quotations from your location object.

    It should be like this:

    var location = {"locationInfo": [{"title": "home", "lat": -16.450902223672625, "lng": 10.6103515625, "speed": ""}, {"title": "work", "lat": -14.94621907436008, "lng": 17.99560546875, "speed": ""}]};
    打赏 评论
  • duanmi3476 2016-03-11 21:58

    @CodeGodie $inputvalues['location'] doesn't seem to contain a file location.

    Maybe like this?

    file_put_contents('saved/file.txt', $inputvalues['location']);
    打赏 评论

相关推荐 更多相似问题