Rahul Mukati
Rahul Mukati

Reputation: 734

PHP to insert into file

I am using php to insert something into a file. I want that what i want to insert get inserted in file after 5 lines from top.

Like Below is a .txt file example.

This is 1st line

This is 2nd line

This is 3rd line

This is 4th line

This is 5th line

Here should be my content inserted with PHP
Here is my previous content inserted with PHP 

This is some other text in file.

Well i am able to insert but not after lines i want. I am using below php code to insert:-

<?php
$file = ( $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt' );;
$current = file_get_contents($file);
$current .= "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK\n";
file_put_contents($file, $current);
?>

Upvotes: 2

Views: 3916

Answers (5)

sandy
sandy

Reputation: 1

//header

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">

<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>

<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>

<style type="text/css">

.dataTables_processing {

    top: 64px !important;

    z-index: 11000 !important;

}

//del data

$(document).on('click','.del_data',function(){

     var id=$(this).attr('id');
     
     $.ajax({

           type:'delete',

           url: url + '/' + id,

           dataType:'JSON',

           success:function(data)

           {

              alert(data.message);

              bustype_tb.ajax.reload();

           }

        });

  });

//show data

$data=EmployeeModel::find($id);

    return view('employee.view',compact('data')) ;

//destroy

$stud=EmployeeModel::find($id)->delete();

    return response()->json(['message'=>'deleted successfully'], 200);  

//index

if($request->ajax())

    {

        $data = EmployeeModel::latest()->get();

        return DataTables::of($data)

                    ->addIndexColumn()
                   
                   ->addColumn('action', function($data){
                    $button = '<a href="empEdit/'.$data->id.'" > <button type="button" name="edit" id="'.$data->id.'" class="edit_data edit btn btn-primary btn-sm">Edit</button></a>';

                    $button .= '&nbsp;&nbsp;&nbsp;<button type="button" name="delete" id="'.$data->id.'" class="del_data delete btn btn-danger btn-sm">Delete</button>';
                    $button .= '&nbsp;&nbsp;&nbsp;<a class="dropdown-item" href="empView/'.$data->id.'" role="menuitem">
                    <i class="icon md-eye text-primary" aria-hidden="true"></i><button type="button" name="view" id="'.$data->id.'" class=" view btn btn-primary btn-sm">View</button></a>';


                    return $button;

                })

                ->rawColumns(['action'])

                ->make(true);

    }

    return view('employee.list');

//ajax datatable

var bustype_tb = '';

$(function () {

bustype_tb = $('#studtable').DataTable({

    processing: true,

    serverSide: true,

     ajax:{

       url: "{{ route('student.index') }}",

   },

    columns: [
           
             {
                data: 'DT_RowIndex', 

                name: 'DT_RowIndex',

                 orderable: false,

                 searchable: false

                 },

             {

                 data: 'sname', 

                 name: 'sname' 

                 },

             {

                 data: 'fname',

                  name: 'fname'

                   },

             {

                 data: 'dob',

                  name: 'dob'

                   },

         
             {

                data: 'action',

                 name: 'action', 

                 orderable: false

           },

          ],

 });


 bustype_tb.ajax.reload();

});

Upvotes: 0

afein
afein

Reputation: 1

$.ajaxSetup({
  headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  }

}); var url="http://localhost/larasampleold/";

$(function() {

var formgenre =$("#productForm");

formgenre.validate({ // ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input',

rules: {

// banner_title:{

//    required:true,

  // // trimWhiteSpace:true,

//   remote:
//             {

//                 global: false,

//                 url: base_url +"/title_exist",

//                 type: "post",

//                 data:
//                         {
//                             name: function () {
  
//                                 return $('#banner_title').val();

//                             }
//                         }
//             }, 
    
// },

// seo_keyword:{

//     required:true

// },

// image:{

// extension: "jpeg,jpg,png,bmp",

// filesize: 20000000,

// },

},
messages: {

//     banner_title: {

//     required: "Enter the banner title.",

//      remote: "Banner title is already exist.",

// },

//     seo_keyword: {
  
//         required: "Enter seo keyword.",
        
//     }

},

focusInvalid: true,

invalidHandler: function (form, validator) 
{
    if (!validator.numberOfInvalids())
        
        return;

    validator.errorList[0].element.focus();

},

//errorElement: "span", //errorClass: "help-block help-block-error", errorElement: "p",

        errorClass: "invalid-feedback",

errorPlacement: function (error, element) {

  

           
   
        error.insertAfter(element);
        
           
},
highlight: function (e) {

$(e).closest(".form-group").addClass("has-error");

},
unhighlight: function (e) {

$(e).closest(".form-group").removeClass("has-error");

},
success: function (e) {

e.closest(".form-group").removeClass("has-error");

},

submitHandler: function (form) {

if (formgenre.valid() == true) {
  
        // if(maxSize())
        // {
var formData = new FormData(formgenre[0]);
    
    $.ajax({
    url: url +'employee/insert',
    type: "POST",
    dataType: "JSON",
    cache: false,
    data: formData,
    contentType: false,
    processData: false,
    success: function (response) {
    if (response.rs) {
    //formcity[0].reset();
       window.location= url +'employee';
    } else {
    
    (response.errType == 'v') ? formgenre.prepend(showAlert('Required', response.msg)) : technoNotify('', response.msg, 'error');
    }
        
    } ,
    error: function (jqXHR, textStatus, errorThrown) {
    var $errmsg = '<p>Status code: ' + jqXHR.status + '</p><p>Error Thrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p>';
 
    console.log($errmsg);
    },
    beforeSend: function () {
    
    $('#axloader').show();
    },
    complete: function () {
    $('#axloader').hide();
    
    },
    timeout: 100000
    }).fail(function (jqXHR, textStatus) {
    if (textStatus === 'timeout') {
    console.log('Failed from timeout');
    }
    });
    
     
    }
//}
    return false;
    }
    
    
    });

});
    

//file upload

if($request->hasFile('photo')) {

        $file=$request->file('photo');

        $extension=$file->getClientOriginalExtension();
       

        $filename="employee-".strtotime(date('Y-m-d H:i:S')).'.'.$extension;

        $file->move(base_path('public/employee'),$filename);

        $stud->photo=$filename;
      
    }

Upvotes: 0

ml-
ml-

Reputation: 412

SKIP_LINES says how many lines you want to skip. The new content that you want to add should be an array so it's handled properly.

The function file() does the job.

OLD:

<?php
define('SKIP_LINES', 5); 
$file = 'existing.txt';

// read existing file into array
$existing = file($file);

// fill new array with existing data to SKIP_LINES
$new = array();
for ($i = 1; $i <= SKIP_LINES; $i++)
    $new[] = array_shift($existing);

// this is the new content that you want to add (as array)                                                                   
$addThis = file("newcontent.txt");

// merge skipped 5 lines, new content, and the rest of the existing file
$new = array_merge($new, $addThis, $existing);

// write the new file
file_put_contents($file, $new);

Edit:

NEW version adjusted to your thingy.

<?php
define('SKIP_LINES', 5); 

$file = $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt';                                                                                               

// read existing file into array
$existing = file($file);

// add this array with the new content
$addThis = [ "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK\n" ];

/* splice array after SKIP_LINES. $existing now has Line 1-5 and $addThis
   $new contains all lines after the 5th (SKIP_LINES) line */
$new = array_splice($existing, SKIP_LINES, 0, $addThis);

// merge 5 lines with the new content and the other lines
$new = array_merge($existing, $new);

// write the new file
file_put_contents($file, $new);

Upvotes: 0

dev777
dev777

Reputation: 3

You can use file to get the file as an array of lines, then change the line you need, and rewrite the whole data back to the file.

<?php
$file = ( $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt' );;
$current = file_get_contents($file);
$current .= "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK\n";

$line_i_need_to_change = 5-1; // Since line array starts from 0

$lines = file( $file , FILE_IGNORE_NEW_LINES );

$lines[$line_i_need_to_change] = $current.$lines[$line_i_need_to_change];

//I noticed that $current have \n that helps to move the old data to next line 

file_put_contents( $file , implode( "\n", $lines ) );

?>

Upvotes: 0

P. Kumar
P. Kumar

Reputation: 207

Try this:

<?php
    $test = "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK";
    $file = ( $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt' );
    $contents = explode("\n", file_get_contents($file), 6);
    file_put_contents($file, $contents[0]."\n".$contents[1]."\n".$contents[2]."\n".$contents[3]."\n".$contents[4]."\n".$test."\n".$contents[5]);
?>

Upvotes: 2

Related Questions