Writing full 100+ lines of html to a file with php - php

I have a system set up where, when the user registers, it creates a custom directory for them and then inside that directory it creates a file called index.html. I would like to write an entire HTML page of 100+ lines to that file. I was using fopen() fwrite($filepath, 'content');, but there are escape characters like '' and "" that mess up the PHP function.
Is there a better way to write large content to these files, or should I just have the file saved somewhere on my webserver and then just transfer it to each new registered user?

If you already have the file on disk, and it will not change for each user, then you should copy the file.
It is a waste of resources to read and then write the file with PHP..
PHP Manual - copy

Have a look at htmlentities($var);
http://php.net/manual/en/function.htmlentities.php

Well that means that where you say 'content' you have a hard coded html file in your script itself. It would be easier to just save a standard html file somewhere on the webserver and to something like this:
file_put_contents('/path/to/user/file', file_get_contents('/path/to/standard/index.html'));
Easier to maintain (no html in your code, but just in a testable html file) and no worries about escaping characters. Easy does it :)
Edit
Someone smarter than me proposed to just copy the file. Which is ofcourse a lot more sensible to do than reading and writing contents...

Related

Creating php file with php code

I wonder if I can create a php file with php code (my project is to write a php based online poker game) and it would be nice if I could add/delete tables from php, but in order to do that I need some code to generate the php file which will be associated with that specific table. (code on every table would be the same, just need something that will allow me to create a .php file for the life time of a table). Also can you tell me how to php-delete it after wards? Thanks ahead.
You can do this simply by having the code written to a file with
file_put_contents($filename, $content).
This will create a new file if it doesn't exist. If it exists it will truncate the file and write the new content.
To read dynamic code you could use eval($codeString). This would interpret the $codeStringas code. NOT RECCOMENDED because if there is ANY user input involved in the $codeString, it would be a huge security risk! (Read the WARNING below!)
To get the contents from a file, you could use $fileContents=file_get_contents($filename)
If you want to write to files with appending text and so on, you need to get deeper in to the php filesystem. A nice place to start is w3 schools: http://www.w3schools.com/php/php_ref_filesystem.asp
You should look at three major functions of writing to files:
fopen();
fwrite();
fclose();
Warning!
Reading dynamic generated code, whether it is from files or just strings, can be really dangerous. Especially if it gets any kind of user- or dynamic input. This is because php-files are capable of editing, creating and deleting ALOT on your server. I would recommend you to find an alternate solution!
You can use file_put_contents Or touch.
file_put_contents() will create the file if not exists and will write provided data in to the file.
touch() will create the file.

Sanatise CSV content in PHP

I've built a bulk user import engine for my web application and it's working perfectly. I'm now sitting here asking myself, is it secure? After all, the content of this file is being pumped into my database!
Not being the wisest security nerd around I need a little advice here.
Users are not able to rename the file after it's uploaded.
When the file is uploaded, its name is instantly changed.
Files must be .csv and have a csv relative mimetype for the upload to work.
The uploaded file is stored in a directory not accessible via the WWW and is deleted as soon as the import has completed, usually a few hundred milliseconds.
I'm opening the file and removing blank lines during the import
What about the actual content of the file? How can I sanitize the file to ensure it doesn't contain any executable code? I looked at the PHP manual and saw that as of PHP 4.3.5 getcsv() is binary safe, but being totally honest, I'm not 100% sure as to what that means.
I'm currently thinking about converting the CSV content into an array and creating a function that escapes the array content. Any other suggestions or is the above completely safe?
You can try using array_walk() to run mysql_escape_string() or your database's equivalent to be doubly sure everything is kosher.
function escape_sql(&$item, $key)
{
$item = mysql_escape_string($item);
}
array_walk($input_array, 'escape_sql');
If your array is multi-dimensional you can use array_walk_recursive(), which operates similarly.

Direction needed - how to create a customizable files?

Here is the flow I would like to achieve:
I have a set of template .php files on server.
Visitor of the website chooses some options
Options are added to template files as pieces of code
Visitor downloads customized files (.zip should contain both default template files if not customised, and customized ones)
Original files remain intact for the next visitor
The flow is similar to bootstrap customisation, only difference is that on bootstrap visitors are editing .less files, and my visitors would edit .php files
I would appreciate if you could point me to general direction how to execute steps 3,4 and 5, baring in mind that user input will be stored in objects and arrays with javascript.
My php knowledge is very rudimentary, so I don't know where would I start.
If you need any clarifications please do not hesitate to ask.
Thanks!
If the users only modify configuration options it seems the best way forward would be to use JSON as it is very easy to encode/decode with JS & PHP with $.parseJSON (jQuery) and json_decode() & json_encode() respectively.
You would provide a form and then convert these user inputs into the JSON format and store it in a .json file which can then be zipped up and sent as a download to your user.
This would also allow users to upload their zip files and have the form inputs defaulted to their original options.
So lets run through how bootstrap does it.
Page to customize the bootstrap file, you would do the same with a similar form.
Once the form is POSTed, take the array of form inputs and validate them for malicious input, correct data types such as a number etc and remove any form inputs that should not be there.
Convert the input into JSON, without validation this is easy as json_encode($_POST).
Write that to a JSON file and allow the user to download it (zip it up if you want).
In your case you have multiple PHP files, this seems a bit off and you should not be using PHP files to hold this sort of variable configuration data, JSON seems a lot better suited.
Take a look at this SO question: What is the best file format for configuration file?
Three methods are mentioned, PHP's way, JSON & XML. Take your pick, but I'm willing to bet that the easiest one for you is JSON.
If you have not used JSON before, create a new PHP script and try out the functions with multi-dimensional arrays and have a play around.
PHP Documention for JSON
If you are using JavaScript to store user selections etc., I recommend you don't actually use php for any of the functionality you described. So do it like this:
Store templates as static text file with demarcated sections to insert user options. Make the demarcated sections different from php syntax like ###Your option here###.
This is easy.
Fetch the relevant template using AJAX and do a simple string replace in JavaScript on the demarcated sections.
Put the resulting php code into a <textarea> using JavaScript for them copy and paste into Notepad or something
Original files are static and code is client-side, so this is fine
So I understand you want to ship php scripts customised for the user.
Consider having php files that cater for all possible user inputs. Then capture the user options into a configuration file where the structure is predictacable and easy to create.
For example
# config.inc.php
# Created by script that captures user options
$config['allow_shipping'] = true;
then in the php script
# file1.php
include config.inc.php
if ($config[$config['allow_shipping'] === true) {
some_php_code;
}
Your steps will be
I have a set of .php scripts files on server.
Visitor of the website chooses some options
Options are sent to a server script which creates a config file.
Visitor downloads customized files (.zip should contain both script files and config file)
Original files remain intact for the next visitor (less the config file)
Some posts to guide you
How I can create installer for website. PHP mysql
and
PHP Installer Script
I would consider making default code snippets and have every "option" link to various required snippets. That way every time an option is selected it uses the right code.
To continue with #Crafter's example, you could have the following code snippets
if (
$config[
]
===
) {
}
I have done this once before when I tried something similar in Java, and even though it seems to be more work than it should, it will end up quite useful once you get a sizeable "database" of code snippets.
Hope it was of any use?
-Peter

PHP secure writing to a text file?

An HTML form, a php file and a text file.
The form has one input box, it sends the inputted string to the PHP file using GET or POST. The PHP file writes the string to the text file using fopen 'a', fwrite and fclose and does no sanitization at all.
The text file is set to permission 777 and is in the same folder as the other files.
Are there any security concerns here? Is it possible for someone to send something using the form that will do any damage? If yes, what?
What about if the txt file is set to 666?
Never execute
Depending on what the use of this file, there shouldn't be much risk involved. Just make sure the file is never executed.
This means, never eval() the content of this file, or change it into a .php or any other executable file.
However, if the content is ever to be written on a page, or viewable by the user, you will have security risks doing this.
I typically use 3 ways to improve security writing to files. 1) Move file out of webroot and into some folder with restricted access like cgi-bin. The path to the file and any passwords should also be saved outside of the webroot. 2) Then you include the sensitive data by including it on your page. So if PHP parser fails people only see a variable name and no details. 3) If your are doing a post or get to the file which is doing the writing you can also check the values carefully and stip out characters, script, etc. that could cause problems.
From a web-security point of view, I do not see any problems, as long as the path of the text file is hardcoded or secured in any other way. You haven't said anything though about what happens if the file is missing or read-only (yes, it can happen, for example if the file system is mounted read-only by the administrator).
That being said, this use case is also completely useless, as the text file serves only as a data sink. A data sink that is never read from is useless. The problems may arise when you want to read from the file.

mySQL images upload

I need a simple code to upload images to mySQL using PHP... short! snippet... and is it possible to upload an html, css file to mySQL?... its reason is complicated but all answers are appreciated!... EDIT:: say I have 1000 users.. and they each have their own layout for their page.. So inside their MYSQL record will be a html file, css file(possibly), and image(s)...
I am a big fan of using a filesystem for storing physical files, i've yet to see any solid reason why they are better off in a database.
To automate this process you could have a shell script called through exec
exec("/home/some/path/my_filesystem_creator.sh ".escapeshellarg($args));
or PHP's native mkdir or anything really. If you went for a structure like:
/common/
/userdirs/1/
/userdirs/2/
essentially all i would imagine you would need to do is create a user dir, and copy into it the default versions of their site assets - images/css/html etc.
This should be easy enough to manage
Are you asking how to store a file in the database?
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx
Or do you need to know how to upload a file to your web server in order to display it in a PHP/MySQL website?
Your page would be faster, if you generate a directory on your filespace for each user and store their css/js/image files there.
The reason for this is, that when you like to output your images to the browser, you will need to establish an own db connection for each file (since each is an own HTTP request to a PHP file, selecting the image).
You might want to take a look at http://mysqldump.azundris.com/archives/36-Serving-Images-From-A-Database.html and http://hashmysql.org/index.php?title=Storing_files_in_the_database before doing that. Storing files in mysql is generally considered a bad idea.
Just use different CSS rules for each user. Create the CSS dynamically though PHP based on user-specific variables. For example, if they have a div with an avatar or some other personal image, just create a class that uses variables for images, and then you really only need one or two files at most to do the whole thing. I would use a heredoc, but you could just use quotation marks to integrate the PHP.
php creates your css -
.useravatar{ 'background: url($baseurl.$urseridpic)'}
In the html, the div just needs the class of 'useravatar' never needing to be changed.

Categories