Is there a way to display a blob image in TCPDF in Yii? I've tried calling this function but it doesn't show any pictures.
public function actionDisplayAgencyIcon()
{
$info = BaseAgencyInfo::model()->find();
$id = $info->agencyID;
if($id == null || trim($id)=='') {
echo "error in image, bad ID value [{$id}]";
exit();
}
$model=BaseAgencyInfo::model()->find("agencyID = '{$id}'");
if($model->agency_logo == null){
echo "error in image, using ID [{$id}] ";
exit();
}
header('Content-Type: gif,jpeg,png');
echo $model->agency_logo;
}
Any ideas?
Try to specify a proper header:
header('Content-Type: image/jpeg');
echo $model->agency_logo;
Related
I have created an uploaded script to receive the file sent to it using the CKeditor 5 simple upload adapter build. I have tested it with a standard upload filetype, using $_POST from a filetype field that I've adapted and it generates the correct json response for the editor to receive.
However, I am unsure how I actually detect the input from editor itself as it's not coming from an input field.
<?php
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Methods: PUT,GET,POST");
$uploadOk = 1;
$err = 0;
//getting the file
$mentionFilename = basename($_FILES["fileToUpload"]["name"]);
if ($mentionFilename == ""){
$err = 1;
}else{
//setting the uploaddir
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
//echo "File is an image - " . $check["mime"] . ".<BR>";
$uploadOk = 1;
} else {
//echo "File is not an image.<BR>";
$err = 2;
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$err = 3;
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
//echo "Sorry, your file is too large.<BR>";
$err = 4;
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "pdf" ) {
//echo "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.<BR>";
$err = 5;
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk > 0) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<BR>";
} else {
//echo "Sorry, there was an error uploading your file.<BR>";
$err = 6;
$uploadOk = 0;
}
}
}
switch ($err){
case "1":
//no fileneame in submissions
$errMsg = "There appeared to be no filename in the submission";
break;
case "2":
//the file is not an image
$errMsg = "The file submitted was not a permitted image type.";
case "3":
//file exists
$errMsg = "The file already exists.";
break;
case "4":
//file is too large
$errMsg = "The filesize of the upload is too large.";
case "5":
//Wrong filetype
$errMsg = "The file had the wrong filetype";
case "6":
//Problem uploading file
$errMsg = "There was a problem uploading the file.";
default:
//file was uplaoded succesfully
break;
}
if ($uploadOk > 0){
//return success message
$returnArr = array(
"url" => $target_file
);
}else{
//return error message
$returnArr = array(
"error" => array(
"message" => $errMsg
)
);
}
//sending back the response
echo json_encode($returnArr);
?>
I have an app the uses an SFTP connection to download files. It was working correctly in PHP 5.6, not so much in PHP 7. The error I get is as follows:
PHP Warning: filesize(): stat failed for ssh2.sftp ...
My code is as follows:
public function retrieveFiles($downloadTargetFolder,$remoteFolder = '.') {
$fileCount = 0;
echo "\nSftpFetcher retrieveFiles\n";
$con = ssh2_connect($this->host,$this->port) or die("Couldn't connect\n");
if($this->pubKeyFile){
$isAuth = ssh2_auth_pubkey_file($con, $this->user, $this->pubKeyFile, $this->privKeyFile);
} else {
$isAuth = ssh2_auth_password($con, $this->user, $this->pass);
};
if ($isAuth) {
$sftp = ssh2_sftp($con);
$rd = "ssh2.sftp://{$sftp}{$remoteFolder}";
if (!$dir = opendir($rd)) {
echo "\nCould not open the remote directory\n";
} else {
$files = array();
while (false != ($file = readdir($dir))) {
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
if (is_array($files)) {
foreach ($files as $remoteFile) {
echo "\ncheck file: $remoteFile vs filter: " . $this->filter."\n";
if ($this->filter !== null && strpos($remoteFile,$this->filter) === false) {
continue;
}
echo "file matched\n";
$localFile = $downloadTargetFolder . DIRECTORY_SEPARATOR . basename($remoteFile);
//$result = ftp_get($con,$localFile,$remoteFile,FTP_BINARY);
$result = true;
// Remote stream
if (!$remoteStream = #fopen($rd."/".$remoteFile, 'r')) {
echo "Unable to open the remote file $remoteFolder/$remoteFile\n";
$return = false;
} else {
// Local stream
if (!$localStream = #fopen($localFile, 'w')) {
echo "Unable to open the local file $localFile\n";
$return = false;
} else {
// Write from our remote stream to our local stream
$read = 0;
$fileSize = filesize($rd."/".$remoteFile);
while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read))) {
$read += strlen($buffer);
if (fwrite($localStream, $buffer) === FALSE) {
echo "Unable to write the local file $localFile\n";
$return = false;
break;
}
}
echo "File retrieved";
// Close
fclose($localStream);
fclose($remoteStream);
}
}
if ($result) {
$fileCount++;
}
}
}
ssh2_exec($con, 'exit');
unset($con);
}
} else {
echo "Error authenticating the user ".$this->user."\n";
}
return $fileCount;
}
}
After some research I found there was an issue with stat():
http://dougal.gunters.org/blog/2016/01/18/wordpress-php7-and-updates-via-php-ssh2/
https://bugs.php.net/bug.php?id=71376
My question
Is there a workaround to allow me to download via SFTP given my current code or is there another library someone can recommend to use instead?
My PHP version:
PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS )
Quoting PHP ssh2.sftp opendir/readdir fix,
Instead of using "ssh2.sftp://$sftp" as a stream path, convert $sftp to an integer like so: "ssh2.sftp://" . intval($sftp) . "/". Then it will work just fine.
The reason for the change is as follows:
PHP 5.6.28 (and apparently 7.0.13) introduced a security fix to URL parsing, that caused the string interpolation of the $sftp resource handle to no-longer be recognized as a valid URL. In turn, that causes opendir(), readdir(), etc. to fail when you use an $sftp resource in the path string, after an upgrade to one of those PHP versions.
As for other libraries... only other library I'm aware of is phpseclib, which has an emulator of sorts for libssh2:
https://github.com/phpseclib/libssh2-compatibility-layer
That "emulator" could certainly be improved upon tho. Like a composer.json file ought to be added, etc.
I had the same issue with php 8.0.
Try putting the filesize command before the fopens.
I am trying to create excel generated file. I want to get usernames from database and then print names according to each letter in alphabet. I am able to create sheets in alphabetical order but cant print names on each sheet.
Here is what i have so far:
<?php
require_once ('PHPExcel/Classes/PHPExcel.php');
include('inc/database_connection.php');
$conn = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
$conn->set_charset('utf8_unicode_ci');//if not by default
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
$Letter='B';
$Number=2;
for($i=321; $i<347; $i++)
{
$F = $objPHPExcel->createSheet($i); //Setting index when creating
$F->setCellValue('A1', "Username")
->setCellValue('B1', "Project")
->setCellValue('C1', "Processes");
$request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
$result= $conn->query($request);//get the result (ressource)
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$username=$row["username"];
$F->setCellValue('A'.$Number, ' '.$username.' ');
$F->getRowDimension('1')->setRowHeight(20);
$F->getColumnDimension($Letter)->setWidth(30);
++$Number;
}
} else
{
echo "0 results";
}
$F->setTitle(chr($i));
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="HeadCount.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
Is there way to print usernames for each spreedsheet? Thank you.
Problem was solved by removing if statement
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
for($i=321; $i<347; $i++)
{
$Letter='B';
$Number=2;
$F = $objPHPExcel->createSheet($i); //Setting index when creating
$objPHPExcel->setActiveSheetIndex(1);
$F->setCellValue('A1', "Username")
->setCellValue('B1', "Project")
->setCellValue('C1', "Processes");
$request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
$result= $conn->query($request);//get the result (ressource)
// output data of each row
while($row = $result->fetch_assoc())
{
$username=$row["username"];
$F->setCellValue('A'.$Number, ' '.$username.' ');
$F->getRowDimension('1')->setRowHeight(20);
$F->getColumnDimension($Letter)->setWidth(30);
++$Number;
}
$F->setTitle(chr($i));
}
I pretty much copy/pasted this from the ModX RTFM:
$results = $modx->query("SELECT * FROM `saved_jobs` WHERE `job_id` = $job_id AND `user_id` = $user");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetchAll(PDO::FETCH_ASSOC);
echo $r;
echo "<br>count " . count($r);
print_r($r);
}
But even though there are no records in the database I still get the 'else' occurring. The line echo "count " . count($r); produces the output: count 0
Does anyone know whats going on and how to fix it?
If your query is successful, you still create an object with your first statement.
take a peek [also from the docs]:
$result = $modx->query("SELECT * FROM modx_users WHERE id='blah'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return 'No result!';
}
else {
$row = $result->fetch(PDO::FETCH_ASSOC);
return 'Result:' .print_r($row,true);
}
What you want to do is find out if the object actually contains a result set:
$result = $modx->query("SELECT * FROM modx_users WHERE id='1'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return FALSE;
}
if(sizeof($result) > 0){
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo'Result:' .print_r($row,true);
}
}
so you can either test the size of the $result variable or just run the while loop & test if it has any data as well.
I am new to zend. I have developed a website using zend framework. Now, I want to set gzip compression in my website. Would you please guide me step wise to implement this.
Thanks in advance.
kamal Arora
There are two methods to gzip output in your website.
Using Webserver.If your webserver is apache you can refer here for a good documentation on how to enable mod_deflate on your server.
Using zend framework. Try the following code which is from this website.
Create a gzip compressed string in your bootstrap file.
Code:
try {
$frontController = Zend_Controller_Front::getInstance();
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
ob_start();
$frontController->dispatch();
$output = gzencode(ob_get_contents(), 9);
ob_end_clean();
header('Content-Encoding: gzip');
echo $output;
} else {
$frontController->dispatch();
}
} catch (Exeption $e) {
if (Zend_Registry::isRegistered('Zend_Log')) {
Zend_Registry::get('Zend_Log')->err($e->getMessage());
}
$message = $e->getMessage() . "\n\n" . $e->getTraceAsString();
/* trigger event */
}
GZIP does not compress images, just the raw HTML/CSS/JS/XML/JSON code from the site being sent to the user.
I made for zend framework 2 (zf2) with your tip
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = str_replace(" ", " ", str_replace("\n", " ", str_replace("\r", " ", str_replace("\t", " ", $content))));
if(#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)
{
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}
Honoring the answer of Bruno Pitteli, I think you can compress in the following way:
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'#(?://)?<![CDATA[(.*?)(?://)?]]>#s' //leave CDATA alone
);
$replace = array(
'>',
'<',
'\\1',
"//<![CDATA[n".'1'."n//]]>"
);
$content = preg_replace($search, $replace, $content);
So the full code sample now looks like:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach("finish", array($this, "compressOutput"), 100);
}
public function compressOutput($e)
{
$response = $e->getResponse();
$content = $response->getBody();
$content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//<![CDATA[n".'1'."n//]]>"), $content);
if (#strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
header('Content-Encoding: gzip');
$content = gzencode($content, 9);
}
$response->setContent($content);
}