Create a CSV file in php [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to create a new CSV File with some values in it and store under my upload directory. Can anyone guide me how I can create a CSV and what code to be written in PHP. Also I want the CSV file with name of input parameter of the form and with current date.
Example: Test_24-04-2014.csv.
Also It will great if you can advise me how I can define a Column Header.
Example:
----------------------------------------
Sr. No Name Invt.
----------------------------------------

Consider this as an example, first off, of course you need a form:
Sample Form:
<!-- HTML -->
<form method="POST" action="processes_the_form.php">
Sr No.: <input type="text" name="srno" /><br/>
Name: <input type="text" name="name" /><br/>
Invt.: <input type="text" name="invt" /><br/>
<input type="submit" name="submit" value="Add to CSV" />
</form>
Then process it in PHP:
<?php
// set delimitter (tab or comma)
$delimitter = chr(9); // this is a tab
$newline = "\r\n"; // CRLF or whatever you want
// handle form submit
if(isset($_POST['submit'])) {
// gather values
$srno = $_POST['srno'];
$name = $_POST['name'];
$invt = $_POST['invt'];
// check for the csv file
$directory = ''; // sample: path/to/csv/
$prefix = 'Test_';
$date = date('d-m-Y');
$file_path = $directory . $prefix . $date . '.csv';
// initial creation
if(!file_exists($file_path)) {
$file = fopen($file_path, 'w');
// add the headers
$headers = array('SrNo', 'Name', 'Invt');
fputcsv($file, $headers, $delimitter);
fclose($file);
}
$formatted_data = array($srno, $name, $invt);
// put them inside the file and append on end
$file = fopen($file_path, 'a');
fputcsv($file, $formatted_data, $delimitter);
fclose($file);
}
?>
Note: You may need to set your permissions to that PHP to create/write on that particular path

To define column headers in CSV, you imply add one line at the beginning containing your columns headers. For example:
"First name", "Family name", "Age"
"John", "Doe", "21"
"Jack", "Smith, "34"
To generate CSV files from PHP, you can use the fputcsv function

Related

How to use php echo to display user input multiple times [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I need someone to help me with php guides on how i can echo every user input to the screen...
Example:
Html
<form action"bot.php" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
Php Code
<?php
//request name from form
$username = $_REQUEST['username'];
//create function
function msg()
{
$username = $_POST['username'];
echo "$username";
echo "\r\n";
}
//echo input to screen
if (isset($_POST['submit']))
{
msg();
}
If I click submit button it will display my input text to the screen, that's fine, If I input another username click on submit button again to display under my previous output to screen...Instead PHP overide my previous output with new username submitted..
Will be glad if anyone can help
This example uses a session. You don't need anything external other than a working PHP installation. I've added comments in the code, but the basic flow is,
start a session
read the names from the session. If this is a new session, default the names to an empty array
read the submitted name
append the submitted name to the existing names
write the existing names to the session
<form action="bot.php" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
<?php
// Always start the session
session_start();
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Read the existing names from the session. Default to an empty array if none are set
$existingNames = $_SESSION['names'] ?? [];
// Grab the submitted name
$name = $_POST['name'];
// Add it to the end of the list
$existingNames[] = $name;
// Overwrite the entire session's list
$_SESSION['names'] = $existingNames;
// Output something interesting
echo 'Welcome ' . $name;
echo '<br>';
echo 'There are ' . count($existingNames) . 'name(s).';
echo '<br>';
foreach ($existingNames as $storedName) {
echo $storedName;
echo '<br>';
}
}

solved: HTML checked checkboxes in a FORM to a file.txt PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I have a Form with Check Boxes and When I submit the form I want the values of the boxes that are selected to be sent to a text file?
Question: How do I know what boxes are selected and then retrieve those values?
this is my form, it is all automated once someone selects a value from a drop down box
echo '<form action="test.php" method="post">'
sqlCheckbox();
echo '<input type="submit" value="save to text file" name="Save To Text File"'
echo '</form>
sqlCheckbox() does this for each result
echo '<input type="checkbox" name="check[]" value="SQL_QUERY">SQL_QUERY <br>'
I found the solution, this is what i fixed/did.
change 1: changed my checkbox name to an array ([] at the end of name)
change 2: once the submit is clicked it goes to my test.php page
here is my other page code
<?php
echo "saved to file";
$array = $_POST['check'];
information = "";//Justin for the variable Idea
foreach ($array $value) {//turns out only the checked checked boxes get submitted
$information .= $value . "<br>";
}
$file = "test.txt" //Flo draven had this idea
file_put_contents($file, $information, FILE_APPEND | LOCK_EX);
?>
this saves the values that were selected and sends them to the test.txt file, so I now have my sql queries in a text file
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
instead of "Hello World" , take the contents of your checkboxes.
you can of course define a variable with the path to any file you want to put the contents into.
a better option probably would be :
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
Check out using fopen and fclose on the Php Manual. That opens a file, then you will be able to send the data to it and save it.

Make mail() php file safe from SQL Injections [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After reading a lot of tutorials I just want to be sure to be on the safe side.
I made a contact formular which looks like this
<form name="contakt" accept-charset="UTF-8" method="post" action="./mail.php">
<input type="text" name="name" />
<input type="text" name="email" />
<input type="text" name="tel" />
<input type="submit" value="Send" name="submit" />
<textarea name="message"></textarea>
</form>
I validate via jQuery if the name and message is not empty and not only full of spaces
and I check the email via jquery with the following script
function ismailornot(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Now when my variables get passed and I am on my mail.php is it more then enough to check on top my of script the $_SERVER['HTTP_REFERER'] and look if those variables came from my own script ? Or can you modify $_SERVER variables too ?
Or do I have basicly to check EVERY passed variable again to be on a safe side ?
For example : http://www.w3schools.com/php/php_secure_mail.asp
is this script 1oo% safe from injections ?
Thanks for helping me out :)
The way: Check EVERY passed variable again to be on a safe side
Try this after some mods to fit your needs its a piece from Larry Ullman book :
function spam_scrubber($value) {
// List of very bad values:
$very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:','multipart-mixed:',
'content-transfer-encoding:', '<script>');
// If any of the very bad strings are in
// the submitted value, return an empty string:
foreach ($very_bad as $v) {
if (stripos($value, $v) !== false){ return '';}
}
// Replace any newline characters with spaces:
$value = str_replace(array( "\r", "\n", "%0a", "%0d"), ' ', $value);
//remove html tags:
$value = htmlentities($value,ENT_QUOTES);
// Return the value:
return trim($value);
} // End of spam_scrubber() function.
// Clean the form data:
$scrubbed = array_map('spam_scrubber', $_POST);
if(isset($from)) {
$from = $scrubbed['from'];
}else{
$from = '';
}
// Minimal form validation:
if (!empty($from) && !empty($scrubbed['comments']) ) {
// Create the body:
$body = "Name: {$from}\n\nComments: {$scrubbed['comments']}";
$body = wordwrap($body, 70);
// Send the email:
mail('YOUR_EMAIL', 'Contact Form Submission', $body, "From: {$from}");
}

Echoing success after uploaded [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to echo "success" on the same page the form is on if it uploaded correctly, but Im new to php so dont know how its done?
index.php
<form action="upload" method="POST">
<input name="field1" placeholder="First name" type="text" />
<input type="submit" name="submit" value="Submit">
upload.php
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
fwrite($fp,$content);
fclose($fp);
I also need it to redirect back to same page index.php
You cannot do this when using a regular form post. When a form is posted the user navigates away from the current page and is given a new page by the server. The one they were looking at no longer exists, so you cannot inject a message.
If you want to perform the task as you describe you will need to use an AJAX-based file uploader.
See:https://stackoverflow.com/search?q=php+jquery+ajax+upload
If you need to echo on the same page and you don't want to use ajax there are 2 possible solution.
a) Use a GET parameter on upload script, and thread this on the index.php (As #Brad also said at comment)
upload.php
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
fwrite($fp,$content);
fclose($fp);
header('Location: /index.php?m=success');
index.php
//Check for message parameter
if (isset($_GET['m']{0}) && $_GET['m'] === 'success')
echo 'Form uploaded successfully';
//Display the upload form
echo '<form action="upload" method="POST">' .
'<input name="field1" placeholder="First name" type="text" />' .
'<input type="submit" name="submit" value="Submit">';
b) Within the same script
index.php
//Check if form is submitted
if (isset($_POST['field1']))
{
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
fwrite($fp,$content);
fclose($fp);
//Do anything else
}
//Display form. Use index.php as the action, instead of upload
echo '<form action="/index.php" method="POST">' .
'<input name="field1" placeholder="First name" type="text" />' .
'<input type="submit" name="submit" value="Submit">';
Update after comment:
When you open a file with the fopen function, you define 2 arguments. The first argument is the filename, and the second argument is the flags.
You need the 'a' (append) flag, instead of 'w' (write):
'a' Open for writing only; place the file pointer at the end of the
file. If the file does not exist, attempt to create it.
'w' Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file does
not exist, attempt to create it.
Take a look here
$content = "".$_POST["field1"];
$fp = fopen("upload/test.txt","wb");
if (fwrite($fp,$content))
{
echo "Successful upload!";
} else {
echo "Not successful!";
};
fclose($fp);
You will need to use some javascript along with php to get what you are looking for.
ajax-file-upload-with-php-and-jquery
I haven't tried it, but at first glance looks like a great place to start.
Try the following code
if (! move_uploaded_file ( $_FILES ['attachment'] ['tmp_name'], UPLOAD_DIR )) {
//handle if file not uploaded
header("Location:index.php?m=fail");
}else{
header("Location:index.php?m=success");
}

Save the whole PHP file to another one with $_POST variables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
For example, I have a simple form with POST target to PHP file:
<form action="language_foo.php" method="post">
<input type="text" name="fname" />
<input type="text" name="age" />
<input type="Submit" name="Submit">
</form>
In language_foo file, I have:
$lang = "$_lang['item.desc']" = $_POST['fname'];
How can I save the user input with exact the same structure, e.g:
$lang = "$_lang['item.desc']" = "Jane";
To another PHP file? I can do file_put_contents, but it will only put "Jane" to file.
Any suggestions?
Simply file_put_contents the below variable $variable_to_put_in_file
$variable_to_put_in_file = '$lang = "$_lang[\'item.desc\']" = "' . $_POST['fname'] . '";';
Are you looking for serialize() ? After filling your $_lang array, you can serialize the whole array to a string and dump it into a file by doing file_put_contents(..., serialize($_lang)), and load it back later with $_lang = unserialize(file_get_contents(...)).

Categories