0

I am learning php. I want to write string to file, but nothing happens. How can I debug it? I have experience with python. there I could use terminal to try small code snippets, but I don't know how check code in php.

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
$stringData = "Bobby Bopper\n";
$myvar = fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
1
  • 2
    Be sure you have write permissions in the folder you are writing. If you are on unix style OS, permissions should be 777(read write execute) Commented May 30, 2012 at 18:34

3 Answers 3

5

Unless you really need to use file handlers, just do this:

$myFile = "testFile.txt";
$stringData = "Bobby Bopper\nTracy Tanner\n";
file_put_contents($myFile,$stringData);
Sign up to request clarification or add additional context in comments.

Comments

4

Debugging in php always starts with turning up error reporting

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);


$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
$stringData = "Bobby Bopper\n";
$myvar = fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

chances are good that you will now see a somewhat descriptive error message. googling php error messages is often helpful.

Comments

0

This looks like correct code. Try checking to make sure you have the right file path. An easy way to do this is

$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

$fh = fopen($myFile, 'r');
$value = fgets($fh);
echo $value;
fclose($fh);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.