1

Im trying to write a new file to the server using the following code

error_reporting(E_ALL); ini_set('display_errors', 1);

if($_SERVER['REQUEST_METHOD'] == "POST") {

$html = $_POST['html'];
$filename = $_POST['fileName'];

     $file = fopen('"$filename".php', 'w');

     fwrite($file, $html);
//     fwrite($file, $_POST["cssContent"]);
     fclose($file);

The file being created is a new html page and the html content is being copied using jquery post, in the echo statements I can see the html is there as well as the filename I would like to call this new file, however after the script is run the file hasn't been created and the php error report is not reporting an error. The $file echo shows the file as Resource id #3

The html page code

<?php
include_once '../../../includes/db_connect.php';
include_once '../../../includes/functions.php';

sec_session_start();

error_reporting(E_ALL); ini_set('display_errors', 1);



$first_name = $_SESSION['memberInfo']['memberFirstName'];
$surname = $_SESSION['memberInfo']['memberLastName'];
$hash = $_SESSION['memberInfo']['hash'];
$newTemplateSrc = $_SESSION['memberInfo']['templateSrc'];


$sql = "SELECT * FROM members WHERE firstName = '$first_name' AND surName = '$surname' AND passWord = '$hash'  AND templateFileSrc = '$newTemplateSrc'";

$result=mysqli_query($mysqli, $sql);

while($row = mysqli_fetch_array($result) ){
        $dateofBirth = $row['dateofBirth'];
        $deceasedName = $row['deceasedName'];
        $dateofDeath = $row['dateofDeath'];
        $aboutDeceased = $row['aboutDescription'];
        $directoryId = $row['directoryid'];
        $templateFileSrc = $row['templateFileSrc'];
        $deceasedImage = $row['deceasedPhoto'];
};
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- TemplateBeginEditable name="doctitle" -->
<title>RIDERS in the SKY CREATE MEMORIAL</title>
<!-- TemplateEndEditable -->
<link rel="stylesheet" type="text/css" href="../../../style/rits2.css">
<link rel="stylesheet" type="text/css" href="../../../Valums-File-Uploader-file-uploader-9991748/client/fileuploader.css">

<style type="text/css">
a:link {
    text-decoration: none;
    color: rgba(135,206,235,1);
}
a:visited {
    text-decoration: none;
    color: rgba(135,206,235,1);
}
a:hover {
    text-decoration: none;
    color: rgba(0,0,0,1);
}
a:active {
    text-decoration: none;
    color: rgba(135,206,235,1);
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- TemplateBeginEditable name="head" -->
<!-- TemplateEndEditable -->
</head>

<body>
<div class="container">
  <header>
    <table id="head_top">
      <tbody>
        <tr>
          <td width="10%" rowspan="3" class="logo"><a href="../../../index.html" target="_self"><img src="../../../images/riders-in-the-sky.png" alt="RIDERS IN THE SKY LOGO - CLICKING HERE TAKES YOU TO THE HOME PAGE" title="RIDERS IN THE SKY LOGO - CLICKING HERE TAKES YOU TO THE HOME PAGE" class="logo_image"/></a></td>
          <td width="80%" colspan="3" class="title">RIDERS IN THE SKY </td>
          <td width="10%" rowspan="3" class="login_register"><table class="log_nav">
            <tbody>
              <tr>
                <td><form action="../../../register.php"><input name="register" type="submit" class="register"  title="REGISTER HERE" id="register" value="Register"></form></td>
              </tr>
              <tr>
                <td><form action="../../../login.php"><input name="login" type="submit" class="login" title="LOGIN HERE" id="login" value="Login"></form>
                  </td>
              </tr>
              <tr> </tr>
            </tbody>
          </table></td>
        </tr>
        <tr>
          <td colspan="3" class="title_tagline">MEMORIALS AND FUNERAL RESOURCES FOR BIKERS AND MOTORCYCLISTS</td>
        </tr>
        <tr>
          <td><div class="3but_nav volunteer"><a href="../../../volunteer.php" title="VOLUNTERR HERE">VOLUNTEER</a></div></td>
          <td><div class="3but_nav resource hover"><a href="../../../resources.php" title="FIND FUNERAL RESOURCES HERE">FUNERAL RESOURCES</a></div></td>
          <td><div class="3but_nav about"><a href="../../../about.php" title="FIND OUT MORE ABOUT RIDERSin the SKY HERE">ABOUT US</a></div></td>
        </tr>
      </tbody>
    </table>
    <table class="top_nav">
      <tbody>
        <tr>
          <td class="create"><form><input name="create" type="button" class="create_but" id="create" value="Create Memorial" title="CTREATE A MEMORIAL HERE" onClick="window.location.href='../../../create.php'"></form></td>
          <td class="view"><form><input name="view" type="button" class="view_but" id="view" value="View Memorials" title="VIEW A MEMORIAL HERE" onClick="window.location.href='../../../view.php'"></form></td>
          <td class="faq"><form><input name="faq" type="button" class="faq_but" id="faq" value="Faq's" title="GO TO OUR FAQ's and HELP PAGE" onClick="window.location.href='../../../faq.php'"></form></td>
          <td class="contact"><form><input name="contact" type="button" class="contact_but" id="contact" value="Contact Us" title="NEED TO CONTACT US? CONTACT US HERE" onClick="window.location.href='../../../contact.php'"></form></td>
          <td class="donate"><form><input name="donate" type="button" class="donate_but" id="donate" value="Make a Donation" title="WANT TO MAKE A DONATION TO RIDERSin the SKY? GO TO OUR DONATIONS PAGE" onClick="window.location.href='../../../donation.php'"></form></td>

        </tr>
      </tbody>
    </table>

  </header>
  <!-- TemplateBeginEditable name="content_main" -->
  <main class="content">
  <div id="deceasedName" class="#" contenteditable="false"><?php echo $deceasedName ?></div>
  <div id="DeceasedDetail" contenteditable="false">
  <div id="dob" contenteditable="false"><?php echo $dateofBirth ?></div>
  <div id="deceasedImage" contenteditable="false"><img class="deceasedImage" src="<?php echo $deceasedImage ?>"></div>
  <div id="dod" contenteditable="false"><?php echo $dateofDeath ?></div>
  <div id="deceasedProfile">
  <h1 id="aboutTitle" contenteditable="false" >About <?php  echo $deceasedName?></h1>
  <h2 id="aboutDesciption" contenteditable="false" ><?php echo $aboutDeceased ?></h2>  

  </div>
  <input name="button" type="button" class="editMemorial" value="Edit/Create Memorial">


  </div>
  <div class="editMenu" style="display:none">
    <button id="editDOB" class="editMenuNav">Edit/Add D.O.B</button>
    <button id="editPic" class="editMenuNav">Change/Add Deceased Photo</button>
    <button id="editDOD" class="editMenuNav">Edit/Add Deceased D.O.D</button>
    <button id="editDeceasedTitle" class="editMenuNav">Edit/Add About the Deceased Title</button>
    <button id="editDeceasedDescription" class="editMenuNav">Edit/Add About the Deceased</button>    
    <button id="editName" class="editMenuNav">Edit/Add Deceased Name</button>
    <button id="saveEdits" class="editMenuNav">Save Changes</button>      
  </div>  





  </main>
  <!-- TemplateEndEditable -->
  <footer class="footer">
    <div class="breadcrumb">
      <p class="breadcrumb"><a href="../../../resources.php">Funeral Resources</a> | <a href="../../../terms.php">Terms of Use</a> | <a href="../../../privacy.php">Privacy</a> | <a href="../../../about.php">About Us</a> | <a href="../../../contact.php">Contact Us</a> | <a href="../../../faq.php">Faq's</a></p>
      <p class="copyright"><span>©2015 RIDERS IN THE SKY</span></p>
    </div>
</footer>



</div>


<div id="uploadDeceasedImage" style="display: none">
  <div id="closeDeceasedUpload">Close Upload X</div>
<noscript>          
  <p>Please enable JavaScript to use file uploader.</p>
     or put a simple form for upload here 
</noscript> 
    <div id="preview">
<img src="../../../images/riders in the sky no text.png" alt="" width="100px" height="100px" class="deceasedThumb"/>
    </div>

<!--<form id="deceasedImageUpload">
        <label class="deceasupload">Upload a Picture of the Deceased</label>
        <input type="file" size="20" id="imageUpload" class=" ">
        <button type="submit" class="saveDeceasedImage">Save Photo</button>
</form>-->
<div id="uploadDeceasedImageWrapper">
</div>




        <input id="file_upload" name="file_upload" type="file" multiple style="display:none">
        <input type="button" id="upload_but" href="javascript:$('#file_upload').uploadifive('upload')" style="display: none" value="Upload Images">





</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../../../Valums-File-Uploader-file-uploader-9991748/client/fileuploader.js"></script>

<script type="text/javascript">

$(".editMemorial").on('click', function() {
    $('.editMenu').show();
    $('.editMemorial').hide();  
});

$("#saveEdits").on('click', function() {

    var dateofBirth = ($('#dob').text());
    var deceasedName = ($('#deceasedName').text());
    var dateofDeath = ($('#dod').text());
    var aboutTitle = ($('#aboutTitle').text());
    var aboutDescription = ($('#aboutDesciption').text());  
    var firstName = ("<?php echo $first_name?>");
    var surName = ("<?php echo $surname?>");
    var hash = ("<?php echo $hash?>");
    var templateSrc = ("<?php echo $newTemplateSrc?>");


//  console.log(dateofBirth, deceasedName, dateofDeath, abouttheDeceased,firstName, surName, hash, templateSrc);

    $.post('../../../includes/editContent.php', {dateofBirth:dateofBirth,deceasedName:deceasedName,dateofDeath:dateofDeath, aboutTitle:aboutTitle,aboutDescription:aboutDescription,firstName:firstName,surName:surName,hash:hash,templateSrc:templateSrc }, function(json) {

    if(json.result === "success") {



    $('.editMenu').hide();
    $('.editMemorial').show();
    $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'false'); 
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'false');      
    $('#deceasedName').attr('contenteditable', 'false');

    $('#dob').attr('class','#')
    $('#dod').attr('class','#')
    $('#aboutDesciption').attr('class','#')
    $('#aboutTitle').attr('class','#')      
    $('#deceasedName').attr('class','#')
    $('#uploadDeceasedImage').hide();

    }else{

            };



    });//json call
});//onclick

// editable clicks
$("#editDOB").on('click', function() {
    $('#dob').attr('contenteditable', 'true');
    $('#dod').attr('contenteditable', 'false'); 
    $('#deceasedName').attr('contenteditable', 'false');
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'false');

    $('#dob').attr('class','deceasedNameHighlight');
    $('#dod').attr('class','#');
    $('#deceasedName').attr('class','#');               
    $('#aboutDesciption').attr('class','#');
    $('#aboutTitle').attr('class','#');
    $('#uploadDeceasedImage').hide();               
});

$("#editName").on('click', function() {
    $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'false'); 
    $('#deceasedName').attr('contenteditable', 'true');
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'false');

    $('#dob').attr('class','#');
    $('#dod').attr('class','#');
    $('#deceasedName').attr('class','deceasedNameHighlight');               
    $('#aboutDesciption').attr('class','#');
    $('#aboutTitle').attr('class','#');
    $('#uploadDeceasedImage').hide();       
});

$("#editDOD").on('click', function() {
    $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'true');  
    $('#deceasedName').attr('contenteditable', 'false');
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'false');

    $('#dob').attr('class','#');
    $('#dod').attr('class','deceasedNameHighlight');
    $('#deceasedName').attr('class','#');               
    $('#aboutDesciption').attr('class','#');
    $('#aboutTitle').attr('class','#');
    $('#uploadDeceasedImage').hide();       
});

$("#editDeceasedDescription").on('click', function() {
    $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'false'); 
    $('#deceasedName').attr('contenteditable', 'false');
    $('#aboutDesciption').attr('contenteditable', 'true');
    $('#aboutTitle').attr('contenteditable', 'false');

    $('#dob').attr('class','#');
    $('#dod').attr('class','#');
    $('#deceasedName').attr('class','#');               
    $('#aboutDesciption').attr('class','deceasedNameHighlight');
    $('#aboutTitle').attr('class','#'); 
    $('#uploadDeceasedImage').hide();           
});

$("#editDeceasedTitle").on('click', function() {
    $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'false'); 
    $('#deceasedName').attr('contenteditable', 'false');
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'true');

    $('#dob').attr('class','#');
    $('#dod').attr('class','#');
    $('#deceasedName').attr('class','#');               
    $('#aboutDesciption').attr('class','#');
    $('#aboutTitle').attr('class','deceasedNameHighlight');
    $('#uploadDeceasedImage').hide();           
});

$('#editPic').on('click', function() {

    $('#uploadDeceasedImage').show();
        $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'false'); 
    $('#deceasedName').attr('contenteditable', 'false');
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'false');

    $('#dob').attr('class','#');
    $('#dod').attr('class','#');
    $('#deceasedName').attr('class','#');               
    $('#aboutDesciption').attr('class','#');
    $('#aboutTitle').attr('class','#');

});

$('#closeDeceasedUpload').on('click', function() {  

    $('#uploadDeceasedImage').hide();
    $('#dob').attr('contenteditable', 'false');
    $('#dod').attr('contenteditable', 'false'); 
    $('#deceasedName').attr('contenteditable', 'false');
    $('#aboutDesciption').attr('contenteditable', 'false');
    $('#aboutTitle').attr('contenteditable', 'false');

    $('#dob').attr('class','#');
    $('#dod').attr('class','#');
    $('#deceasedName').attr('class','#');               
    $('#aboutDesciption').attr('class','#');
    $('#aboutTitle').attr('class','#');

});

</script>

<script type="text/javascript">

        // DOM-ready event is a much option here, just using onload in demo for simplicity
        // jQuery users can use $(function()) { ...
        window.onload = function() {

            var uploader = new qq.FileUploader({

                // pass the dom node (ex. $(selector)[0] for jQuery users)
                element: document.getElementById('uploadDeceasedImageWrapper'),

                // path to server-side upload script
                // action: '/server/upload'
                action: '../../../includes/uploadDeceased_image.php',
                     params: {
                                directoryId: '<?php echo $directoryId ?>',
                                templateSrc: '<?php echo $templateFileSrc ?>'
                             },         

                allowedExtensions: ['jpg', 'png'],
                sizeLimit: 100000000,   // 100mb
                minSizeLimit: 500,

                debug: true
            }); 
        };

    </script>


   <script type="text/javascript">

   $('#saveEdits').on('click', function() {
       var html = $("html").html();
       var fileName = <?php echo $directoryId  ?>;
       console.log(html);
       $.post('../../../includes/memorialSave.php', {html:html, fileName:fileName}, function(json)  {

       });




   });
   </script> 

</body>
</html>

The html and filename are being sent to the php by the jquery code as shown below

   <script type="text/javascript">

   $('#saveEdits').on('click', function() {
       var html = $("html").html();
       var fileName = <?php echo $directoryId  ?>;
       console.log(html);
       $.post('../../../includes/memorialSave.php', {html:html, fileName:fileName}, function(json)  {

       });




   });
   </script> 

I'm aware that there is a lot of jquery that could be better scripted but I'm new to jquery and initially I'm just getting stuff to work

Tiny
  • 363
  • 2
  • 6
  • 20

3 Answers3

1

Error in quotes it would be

 $file = fopen($filename.".php", 'w');

Also read this single quotes vs double quotes

For examlpe

$filename = "text.php";
echo '$filename'; // $filename.
echo "$filename"; // text.php.
Community
  • 1
  • 1
Saty
  • 22,443
  • 7
  • 33
  • 51
1

I see $filename = $_POST['fileName']; and that tells me we're dealing with files.
Sidenote: fileName and filename are not the same, should that be the case for the input.

This also tells me you're using a form and wanting to upload a file.

Since you have not provided the rest of the code, your form needs to have a POST method, including a valid enctype.

I.e. method="post" enctype="multipart/form-data". Make sure that's included.

This $filename = $_POST['fileName']; will need to be changed to
$filename = $_FILES['fileName']; while making sure the input for it also bears the fileName name attribute.

  • Make sure your form contains the POST method.
  • Forms default to GET if omitted <form action=""> and will fail silently.
  • While doing <form action="" method="post"> will specify it exactly.

Also $file = fopen('"$filename".php', 'w'); quotes are wrong which should be
$file = fopen($filename.".php", 'w');

or simply $file = fopen($filename, 'w'); - unsure what the file is to be.

  • Post the rest of your code in order to be sure.
  • If I'm wrong here, I'll just delete this.

Edit: Test.

Using the following test code, worked for me and created a file called filename1.php with "content" inside it.

$_POST['html'] = "content";

$_POST['fileName'] = "filename1";

$html = $_POST['html'];
$filename = $_POST['fileName'];

$file = fopen($filename.".php", 'w');

As did

$_POST['html'] = "<b>content</b>"; with <b>content</b> inside it.


2nd edit:

The $file echo shows the file as Resource id #3

You haven't shown us where you're trying to pull that content/file from.

Answer/example pulled from: https://stackoverflow.com/a/2408630/

The file did open just fine, you cannot echo it like that because it's a file pointer, not the contents of the file itself. You need to use fread() to read the actual contents, or better yet, use file_get_contents() the get the content straight away.

Doing it your way:

$handle = fopen("test.txt", "r");
$fileip = fread($handle, filesize($filename));
fclose($handle);

echo $fileip;

Or, using file_get_contents():

$fileip = file_get_contents("test.txt");

echo $fileip;

Path example:

$path = "/var/user/home/httpdocs/folder_to_write_in/";
$file = fopen($path.$filename.".php", 'w');
Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • The fileName is just that just a name and not a file and is being echoed out correctly. I tried a number of quote marks in various places thinking the file wasnt being created due to ' ' echoing just the $fileName and not its content, so tried the " " as I believe that opens the variable – Tiny May 23 '15 at 13:09
  • @Tiny I've made an edit to my answer with using `$file = fopen($filename, 'w');` have you tried that? – Funk Forty Niner May 23 '15 at 13:10
  • @Tiny Or see the other answers given. I might have missed something. – Funk Forty Niner May 23 '15 at 13:12
  • I'm not sure if I have described what I'm doing very well as I am trying to ask a question without being told off for putting up too much code and keeping explanations as brief and concise as possible, also not getting told off for having a conversation on the comments, is there anyway I can message you in anyway? – Tiny May 23 '15 at 13:16
  • @Tiny Reload my answer and near the end under **Edit** test, which is what I used to test this with, and successfully. Something else in your code that you've not shown may be causing its failure. – Funk Forty Niner May 23 '15 at 13:19
  • I tried the code and still no new page is appearing, maybe that might have something to do with where it's trying to be created – Tiny May 23 '15 at 13:30
  • @Tiny reload my answer again in its entirety. I've added a few things to it which I hope should shed a bit more light on the subject. – Funk Forty Niner May 23 '15 at 13:33
  • 1
    I have just realised where my error is, because the process is being run in the includes folder the created pages are being created there instead of where I was looking for them which is a different directory, so how do I create the page in the correct directory – Tiny May 23 '15 at 13:35
  • @Tiny Try and use the same method as you did for the way you're including the files, such as `../../` etc. or use a full server system path such as `/var/user/you/httpdocs/folder/` - I added an example under **Path example:** near the bottom – Funk Forty Niner May 23 '15 at 13:39
  • Thankyou very much for your assistance, without I wouldn't have realised my error and I am now another step forward in creating my ultimate aim – Tiny May 23 '15 at 13:44
  • @Tiny You're quite welcome and I for one am glad we were able to find a final solution, *cheers* and all the best with your project :-) – Funk Forty Niner May 23 '15 at 13:45
1

PHP will only parse variable within double quotes, so in your case you need to do this:

$file = fopen("\"$filename\".php", 'w');

or

$file = fopen($filename.'.php', 'w');

also you need to make sure PHP has enough permission to create file

Mohammadhzp
  • 498
  • 7
  • 20