sqlserver data to excel xlsx using php ? what wrong in this code..? - sql-server

<?php
$serverName = '-'; //serverName\instanceName
$connectionInfo = array( 'Database'=>'-');
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn!='') {
'Connection established.<br />';
}else{
'Connection could not be established.<br />';
die( print_r( sqlsrv_errors(), true));
}
/** Set default timezone (will throw a notice otherwise) */
date_default_timezone_set('Asia/Kolkata');
// include PHPExcel
require('../PHPExcel.php');
// create new PHPExcel object
$objPHPExcel = new PHPExcel;
// set default font
$objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri');
// set default font size
$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
/**
* Define currency and number format.
*/
// currency format, € with < 0 being in red color
$currencyFormat = '#,#0.## \€;[Red]-#,#0.## \€';
// number format, with thousands separator and two decimal points.
$numberFormat = '#,#0.##;[Red]-#,#0.##';
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('My sales report');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:D1')->getFont()->setBold(true)->setSize(12);
// write header
$objSheet->getCell('A1')->setValue('Name');
$objSheet->getCell('B1')->setValue('phone No');
// we could get this data from database, but here we are writing for simplicity
$i = '2';
$que=sqlsrv_query($conn,"SELECT * FROM table");
while($row=sqlsrv_fetch_array($que)){
$name=$row['CustomerName'];
$PhoneNo=$row['CustomerPhone'];
$data[] = array(
'name'=>$name,
'empno'=>$PhoneNo
);
}
$array = stripslashes(json_encode($data));
$json = (object)json_decode($array);
foreach($json AS $datas){
$objSheet->getCell('A'.$i.'')->setValue($datas->name);
$objSheet->getCell('B'.$i.'')->setValue($datas->empno);
$i++;
}
// autosize the columns
$objSheet->getColumnDimension('A')->setAutoSize(true);
$objSheet->getColumnDimension('B')->setAutoSize(true);
//Setting the header type
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="file.xlsx"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
/* If you want to save the file on the server instead of downloading, replace the last 4 lines by
$objWriter->save('test.xlsx');
*/
?>

Related

how to get filename by file_id in telegram

for my new bot i need to get real file name.
when i get the file_id and requesting for generate download link with "get file" commend, the file name is look like "file_370.mp3" but the real file name is:"michaeljackson.mp3".
i tried this code:
$mp3name = $result['message']['audio']['title'];
$mp3fileid = $result['message']['audio']['file_id'];
file_get_contents( $url."/sendaudio?chat_id=118718802&audio=$mp3fileid&performer=awaperformer&title=awatitle");
$bot_url = "https://api.telegram.org/bot".$botToken;
$file_path_gen_url = $bot_url."/getfile?file_id=".$mp3fileid;
// file_get_contents( $url."/sendmessage?chat_id=118718802&text=lastfileid:filegen:$file_path_gen_url");
$file_path_result = file_get_contents($file_path_gen_url);
// echo "last file id: $last_file_id <br>";
$file_path_result = json_decode($file_path_result, TRUE);
$file_path = $file_path_result['result']['file_path'];
// echo "file_path: $file_path <br>";
$file_url = "https://api.telegram.org/file/bot".$botToken."/".$file_path;
how can i get real file name?
You can't get original file name for audio object.
here avaliable attributes : https://core.telegram.org/bots/api#audio
You can get original file name for document object.

PHP Download File Script (doesn't work)

I have never written an PHP Download File Script neither have any experience with it and I am really not a pro. I got the snippet of code you can see below from another website and tried to make use of it. I understand what is written in the script but I just don't get the message of the errors or rather said, I don't know how to prevent these.
Here is the download.php script - I have put it into the /download/ folder below my main domain:
<?php
ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script
$path = "/downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
Now in the /download/ folder, which contains the download.php I have a folder /downloads, which contains the .pdf that should be downloaded.
The link I use on my webpage is:
PHP download file (why isn't it displayed, included the 4 white spaces :
Now I get the following errors when I click on the link:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(/downloads/test.pdf): failed to open stream: No such file or directory in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
If I use an absolute path (https://www.my-domain.de/downloads/) for the $path variable, I get these errors:
Warning: Cannot set max_execution_time above master value of 30 (tried to set unlimited) in /var/www/xxx/html/download/download.php on line 4
Warning: fopen(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /var/www/xxx/html/download/download.php on line 12
Warning: fopen(https://www.my-domain.de/downloads/test.pdf): failed to open stream: no suitable wrapper could be found in /var/www/xxx/html/download/download.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /var/www/xxx/html/download/download.php on line 34
I am thankful for any advices!
<?php
ignore_user_abort(true);
//set_time_limit(0); disable the time limit for this script
$path = "downloads/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
break;
// add more headers for other content types here
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
?>
Try this code
Your server is probably not allowing you for a maximum execution time limit for infinite seconds. Check it in php.ini file
Also the relative path was wrong, and "https://www.my-domain.de/downloads/" is not a path, it's a url for the server

Calculation in virtual field not working

I am trying to calculate distance between two geographical locations. one location is entered by user.
User entered location is calculated by model and is stored in the variable.
$ulatitude=$userLocation['Location']['latitude'];
$ulongitude=$userLocation['Location']['longitude'];
I have used below code to calculate the distance.
$this->User->virtualFields['lowestDistance'] = 'round(3959 * acos(cos(radians($ulatitude)) * cos(radians(Profile.latitude )) * cos(radians(Profile.longitude) - radians($ulongitude)) + sin(radians($ulatitude)) * sin(radians(Profile.latitude)))) ';
$order = "User.lowestDistance";
$options = array(
'fields' => '
User.*, Profile.*,
round(3959 * acos(cos(radians($ulatitude)) * cos(radians(Profile.latitude )) * cos(radians(Profile.longitude) - radians($ulongitude)) + sin(radians($ulatitude)) * sin(radians(Profile.latitude)))) AS lowestDistance,
',
'order' => array($order =>'asc'),
);
Above code throws error : unknown column $ulatitude.
Is there any other way of doing this ?
Single quotes are not interpreted
Consider:
<?php
$foo = "A VARIABLE";
echo 'foo is $foo' . "\n";
echo "foo is $foo" . "\n";
This would output:
-> php example.php
foo is $foo
foo is A VARIABLE
In the question everything is in single quotes, they are literal strings.
Fields should be an array
Also note that this:
'fields' => 'User.*, Profile.*, ...
Is normally an array, which makes more sense when there's multiple values:
'fields' => [
'User.*',
'Profile.*',
...
]
But since you're declaring all fields plus a virtual field, it'd be included in a find call anyway - just remove the fields from the find parameters:
$this->User->virtualFields['lowestDistance'] = "round(...";
$options = [
//'fields' => [], Not necessary
'order' => [$order =>'asc']
];
$withLowestDistance = $this->User->find('all', $options);

PHPMailer : Cant send attachement

I have a probleme with PHPMailer .
First i used it without FTP , but all email was SPAM .
So i tried to use my FTP login and now all email are not junk .
But problem ... my attachement ( .rar and . zip ) doest work .
i tried with txt files and its ok ... i'm becoming crazy
require('class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->SMTPDebug = 1;
$mail->IsSMTP();
$mail->Host = "r******";
$mail->Port = "465";
//usually the port for TLS is 587, for SSL is 465 and non-secure is 25
$mail->SMTPSecure = "ssl";
//TLS, SSL or delete the line
$mail->SMTPAuth = true;
$mail->Username = 's*****';
$mail->Password = '##';
$mail->From = 'sales#*****';
$mail->FromName = '****';
$mail->AddAddress("$payer_email", "$payer_business_name");
$mail->Subject = "SUBJET";
$mail->Body = " MY MESSAGE";
if( $custom == 1 )
{
$mail->AddAttachment('test.txt');
}
if( $custom == 2 )
{
$mail->AddAttachment('test2.txt');
}
$mail->Send() ;
}
}
fclose ($fp);
}
i use if and else because its a paypal button with param . ( if 1 i send this file by mail )
this is working with txt files . but not with RAR or ZIP files ... No email send
any idea ?
thanks a lot

Cakephp: add minutes to datetime object

I am new to cakephp and i wish to do the following:
I have a dateTime object and i want to add and subtract 30 minutes to it.
Following is my code in controller :
$time = $this->request->data['Rideoffer']['DepartureTime'];
$date = new DateTime($time['hour'] . ':' . $time['min'] . ' ' . $time['meridian']);
$currentDate = strtotime($date['date']); // this line gives error
$futureDate = $currentDate+(60*30);
$formatDate = date("Y-m-d H:i", $futureDate);
when i debug $date i get the following result:
object(DateTime) {
date => '2013-03-08 05:54:00'
timezone_type => (int) 3
timezone => 'UTC'
}
i wish to extract date from this object. How do i do so?
solved it:
$currentDate = strtotime($date->format('Y-m-d H:i:s'));
but i still dont get it that why cant i use $date['date'], i mean $date like an array.

Resources