I am trying to find a way to transfer files from server-to-server. The source server can be any platform, and we may not even really know anything about it except that it supports FTP.
A number of posts I have found on SO recommend using scp, sftp, rsync, or wget for this purpose. Given that this PHP script needs to work every time, and the only thing we know for sure is that the source server supports FTP, how can this be achieved?
I found a couple FTP examples on SO, but they weren't explained very well.
We need to be able to download all files and folders, keeping the same directory structure as well.
I have found a PHP class that makes recursive FTP uploads and downloads easy. It can be found here
The code they used is below (The code at the top is example code for downloads, uploads, and error checking):
<?php // example
set_time_limit(0);
require 'ftp.php';
$ftp = new ftp();
$ftp->conn('host', 'username', 'password');
$ftp->get('download/demo', '/demo'); // download live "/demo" folder to local "download/demo"
$ftp->put('/demo/test', 'upload/vjtest'); // upload local "upload/vjtest" to live "/demo/test"
$arr = $ftp->getLogData();
if ($arr['error'] != "")
echo '<h2>Error:</h2>' . implode('<br />', $arr['error']);
if ($arr['ok'] != "")
echo '<h2>Success:</h2>' . implode('<br />', $arr['ok']);
class ftp {
private $conn, $login_result, $logData, $ftpUser, $ftpPass, $ftpHost, $retry, $ftpPasv, $ftpMode, $verbose, $logPath, $createMask;
// --------------------------------------------------------------------
/**
* Construct method
*
* #param array keys[passive_mode(true|false)|transfer_mode(FTP_ASCII|FTP_BINARY)|reattempts(int)|log_path|verbose(true|false)|create_mask(default:0777)]
* #return void
*/
function __construct()
{
$this->retry = (isset($o['reattempts'])) ? $o['reattempts'] : 3;
$this->ftpPasv = (isset($o['passive_mode'])) ? $o['passive_mode'] : true;
$this->ftpMode = (isset($o['transfer_mode'])) ? $o['transfer_mode'] : FTP_BINARY;
$this->verbose = (isset($o['verbose'])) ? $o['verbose'] : false;
$this->logPath = (isset($o['log_path'])) ? $o['log_path'] : dirname(__FILE__).'\log';
$this->createMask = (isset($o['create_mask'])) ? $o['create_mask'] : 0777;
}
// --------------------------------------------------------------------
/**
* Connection method
*
* #param string hostname
* #param string username
* #param string password
* #return void
*/
public function conn($hostname, $username, $password)
{
$this->ftpUser = $username;
$this->ftpPass = $password;
$this->ftpHost = $hostname;
$this->initConn();
}
// --------------------------------------------------------------------
/**
* Init connection method - connect to ftp server and set passive mode
*
* #return bool
*/
function initConn()
{
$this->conn = ftp_connect($this->ftpHost);
$this->login_result = ftp_login($this->conn, $this->ftpUser, $this->ftpPass);
if($this->conn && $this->login_result)
{
ftp_pasv($this->conn, $this->ftpPasv);
return true;
}
return false;
}
// --------------------------------------------------------------------
/**
* Put method - upload files(folders) to ftp server
*
* #param string path to destionation file/folder on ftp
* #param string path to source file/folder on local disk
* #param int only for identify reattempt, dont use this param
* #return bool
*/
public function put($destinationFile, $sourceFile, $retry = 0)
{
if(file_exists($sourceFile))
{
if(!$this->isDir($sourceFile, true))
{
$this->createSubDirs($destinationFile);
if(!ftp_put($this->conn, $destinationFile, $sourceFile, $this->ftpMode))
{
$retry++;
if($retry > $this->retry)
{
$this->logData('Error when uploading file: '.$sourceFile.' => '.$destinationFile, 'error');
return false;
}
if($this->verbose) echo 'Retry: '.$retry."\n";
$this->reconnect();
$this->put($destinationFile, $sourceFile, $retry);
}
else
{
$this->logData('Upload:'.$sourceFile.' => '.$destinationFile, 'ok');
return true;
}
}
else
{
$this->recursive($destinationFile, $sourceFile, 'put');
}
}
}
// --------------------------------------------------------------------
/**
* Get method - download files(folders) from ftp server
*
* #param string path to destionation file/folder on local disk
* #param string path to source file/folder on ftp server
* #param int only for identify reattempt, dont use this param
* #return bool
*/
public function get($destinationFile, $sourceFile, $retry = 0)
{
if(!$this->isDir($sourceFile, false))
{
if($this->verbose)echo $sourceFile.' => '.$destinationFile."\n";
$this->createSubDirs($destinationFile, false, true);
if(!ftp_get($this->conn, $destinationFile, $sourceFile, $this->ftpMode))
{
$retry++;
if($retry > $this->retry)
{
$this->logData('Error when downloading file: '.$sourceFile.' => '.$destinationFile, 'error');
return false;
}
if($this->verbose) echo 'Retry: '.$retry."\n";
$this->reconnect();
$this->get($destinationFile, $sourceFile, $retry);
}
else
{
$this->logData('Download:'.$sourceFile.' => '.$destinationFile, 'ok');
return true;
}
}
else
{
$this->recursive($destinationFile, $sourceFile, 'get');
}
}
// --------------------------------------------------------------------
/**
* Make dir method - make folder on ftp server or local disk
*
* #param string path to destionation folder on ftp or local disk
* #param bool true for local, false for ftp
* #return bool
*/
public function makeDir($dir, $local = false)
{
if($local)
{
if(!file_exists($dir) && !is_dir($dir))return mkdir($dir, $this->createMask); else return true;
}
else
{
ftp_mkdir($this->conn,$dir);
return ftp_chmod($this->conn, $this->createMask, $dir);
}
}
// --------------------------------------------------------------------
/**
* Cd up method - change working dir up
*
* #param bool true for local, false for ftp
* #return bool
*/
public function cdUp($local)
{
return $local ? chdir('..') : ftp_cdup($this->conn);
}
// --------------------------------------------------------------------
/**
* List contents of dir method - list all files in specified directory
*
* #param string path to destionation folder on ftp or local disk
* #param bool true for local, false for ftp
* #return bool
*/
public function listFiles($file, $local = false)
{
if(!$this->isDir($file, $local))return false;
if($local)
{
return scandir($file);
}
else
{
if(!preg_match('/\//', $file))
{
return ftp_nlist($this->conn, $file);
}else
{
$dirs = explode('/', $file);
foreach($dirs as $dir)
{
$this->changeDir($dir, $local);
}
$last = count($dirs)-1;
$this->cdUp($local);
$list = ftp_nlist($this->conn, $dirs[$last]);
$i = 0;
foreach($dirs as $dir)
{
if($i < $last) $this->cdUp($local);
$i++;
}
return $list;
}
}
}
// --------------------------------------------------------------------
/**
* Returns current working directory
*
* #param bool true for local, false for ftp
* #return bool
*/
public function pwd($local = false)
{
return $local ? getcwd() : ftp_pwd($this->conn);
}
// --------------------------------------------------------------------
/**
* Change current working directory
*
* #param string dir name
* #param bool true for local, false for ftp
* #return bool
*/
public function changeDir($dir, $local = false)
{
return $local ? chdir($dir) : #ftp_chdir($this->conn, $dir);
}
// --------------------------------------------------------------------
/**
* Create subdirectories
*
* #param string path
* #param bool
* #param bool true for local, false for ftp
* #param bool change current working directory back
* #return void
*/
function createSubDirs($file, $last = false, $local = false, $chDirBack = true)
{
if(preg_match('/\//',$file))
{
$origin = $this->pwd($local);
if(!$last) $file = substr($file, 0, strrpos($file,'/'));
$dirs = explode('/',$file);
foreach($dirs as $dir)
{
if(!$this->isDir($dir, $local))
{
$this->makeDir($dir, $local);
$this->changeDir($dir, $local);
}
else
{
$this->changeDir($dir, $local);
}
}
if($chDirBack) $this->changeDir($origin, $local);
}
}
// --------------------------------------------------------------------
/**
* Recursion
*
* #param string destionation file/folder
* #param string source file/folder
* #param string put or get
* #return void
*/
function recursive($destinationFile, $sourceFile, $mode)
{
$local = ($mode == 'put') ? true : false;
$list = $this->listFiles($sourceFile, $local);
if($this->verbose) echo "\n".'Folder: '.$sourceFile."\n";
$this->logData(($mode=='get')?('Download:'):('Upload:').$sourceFile.' => '.$destinationFile, 'ok');
if($this->verbose) print_r($list);
$x=0;
$z=0;
if(count($list)==2)// blank folder
{
if($mode == 'get')
$this->makeDir($destinationFile, true);
if($mode == 'put')
$this->makeDir($destinationFile);
}
foreach($list as $file)
{
if($file == '.' || $file == '..')continue;
$destFile = $destinationFile.'/'.$file;
$srcFile = $sourceFile.'/'.$file;
if($this->isDir($srcFile,$local))
{
$this->recursive($destFile, $srcFile, $mode);
}
else
{
if($local)
{
$this->put($destFile, $srcFile);
}
else
{
$this->get($destFile, $srcFile);
}
}
}
}
// --------------------------------------------------------------------
/**
* Check if is dir
*
* #param string path to folder
* #return bool
*/
public function isDir($dir, $local)
{
if($local) return is_dir($dir);
if($this->changeDir($dir))return $this->cdUp(0);
return false;
}
// --------------------------------------------------------------------
/**
* Save log data to array
*
* #param string data
* #param string type(error|ok)
* #return void
*/
function logData($data, $type)
{
$this->logData[$type][] = $data;
}
// --------------------------------------------------------------------
/**
* Get log data array
*
* #return array
*/
public function getLogData()
{
return $this->logData;
}
// --------------------------------------------------------------------
/**
* Save log data to file
*
* #return void
*/
public function logDataToFiles()
{
if(!$this->logPath) return false;
$this->makeDir($this->logPath, true);
$log = $this->getLogData();
$sep = "\n".date('y-m-d H:i:s').' ';
if($log['error'] != "")
{
$logc = date('y-m-d H:i:s').' '.join($sep,$log['error'])."\n";
$this->addToFile($this->logPath.'/'.$this->ftpUser.'-error.log',$logc);
}
if($log['ok'] != "")
{
$logc = date('y-m-d H:i:s').' '.join($sep,$log['ok'])."\n";
$this->addToFile($this->logPath.'/'.$this->ftpUser.'-ok.log',$logc);
}
}
// --------------------------------------------------------------------
/**
* Reconnect method
*
* #return void
*/
public function reconnect()
{
$this->closeConn();
$this->initConn();
}
// --------------------------------------------------------------------
/**
* Close connection method
*
* #return void
*/
public function closeConn()
{
return ftp_close($this->conn);
}
// --------------------------------------------------------------------
/**
* Write to file
*
* #param string path to file
* #param string text
* #param string fopen mode
* #return void
*/
function addToFile($file, $ins, $mode = 'a')
{
$fp = fopen($file, $mode);
fwrite($fp,$ins);
fclose($fp);
}
// --------------------------------------------------------------------
/**
* Destruct method - close connection and save log data to file
*
* #return void
*/
function __destruct()
{
$this->closeConn();
$this->logDataToFiles();
}
}
// END ftp class
/* End of file ftp.php */
/* Location: ftp.php */
This should be a comment, but its a bit long. Copying a file over FTP using PHP might be as simple as
file_put_contents($fname
, file_get_contents('FTP://ftp.example com/path/afile'));
But what do you know about where your PHP code is running? It may not have the capability to
resolve DNS names
make client connections to other/remote services
create a listening data channel (for non-passive data channel)
And we can't answer these questions for you. Hence your first step is to get a proof of concept up and running using similar code to that above before you start worrying about lots of files, directories and synchronisation.
Why the requirement to implement this in PHP?
Related
I would like to find a way to use image magick in the following class to convert the source to jpg (the code come from phpWord library):
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* #see https://github.com/PHPOffice/PHPWord
* #copyright 2010-2018 PHPWord contributors
* #license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\Exception\InvalidImageException;
use PhpOffice\PhpWord\Exception\UnsupportedImageTypeException;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\Shared\ZipArchive;
use PhpOffice\PhpWord\Style\Image as ImageStyle;
/**
* Image element
*/
class Image extends AbstractElement
{
/**
* Image source type constants
*/
const SOURCE_LOCAL = 'local'; // Local images
const SOURCE_GD = 'gd'; // Generated using GD
const SOURCE_ARCHIVE = 'archive'; // Image in archives zip://$archive#$image
const SOURCE_STRING = 'string'; // Image from string
/**
* Image source
*
* #var string
*/
private $source;
/**
* Source type: local|gd|archive
*
* #var string
*/
private $sourceType;
/**
* Image style
*
* #var ImageStyle
*/
private $style;
/**
* Is watermark
*
* #var bool
*/
private $watermark;
/**
* Name of image
*
* #var string
*/
private $name;
/**
* Image type
*
* #var string
*/
private $imageType;
/**
* Image create function
*
* #var string
*/
private $imageCreateFunc;
/**
* Image function
*
* #var string
*/
private $imageFunc;
/**
* Image extension
*
* #var string
*/
private $imageExtension;
/**
* Is memory image
*
* #var bool
*/
private $memoryImage;
/**
* Image target file name
*
* #var string
*/
private $target;
/**
* Image media index
*
* #var int
*/
private $mediaIndex;
/**
* Has media relation flag; true for Link, Image, and Object
*
* #var bool
*/
protected $mediaRelation = true;
/**
* Create new image element
*
* #param string $source
* #param mixed $style
* #param bool $watermark
* #param string $name
*
* #throws \PhpOffice\PhpWord\Exception\InvalidImageException
* #throws \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException
*/
public function __construct($source, $style = null, $watermark = false, $name = null)
{
$this->source = $source;
$this->style = $this->setNewStyle(new ImageStyle(), $style, true);
$this->setIsWatermark($watermark);
$this->setName($name);
$this->checkImage();
}
/**
* Get Image style
*
* #return ImageStyle
*/
public function getStyle()
{
return $this->style;
}
/**
* Get image source
*
* #return string
*/
public function getSource()
{
return $this->source;
}
/**
* Get image source type
*
* #return string
*/
public function getSourceType()
{
return $this->sourceType;
}
/**
* Sets the image name
*
* #param string $value
*/
public function setName($value)
{
$this->name = $value;
}
/**
* Get image name
*
* #return null|string
*/
public function getName()
{
return $this->name;
}
/**
* Get image media ID
*
* #return string
*/
public function getMediaId()
{
return md5($this->source);
}
/**
* Get is watermark
*
* #return bool
*/
public function isWatermark()
{
return $this->watermark;
}
/**
* Set is watermark
*
* #param bool $value
*/
public function setIsWatermark($value)
{
$this->watermark = $value;
}
/**
* Get image type
*
* #return string
*/
public function getImageType()
{
return $this->imageType;
}
/**
* Get image create function
*
* #return string
*/
public function getImageCreateFunction()
{
return $this->imageCreateFunc;
}
/**
* Get image function
*
* #return string
*/
public function getImageFunction()
{
return $this->imageFunc;
}
/**
* Get image extension
*
* #return string
*/
public function getImageExtension()
{
return $this->imageExtension;
}
/**
* Get is memory image
*
* #return bool
*/
public function isMemImage()
{
return $this->memoryImage;
}
/**
* Get target file name
*
* #return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Set target file name.
*
* #param string $value
*/
public function setTarget($value)
{
$this->target = $value;
}
/**
* Get media index
*
* #return int
*/
public function getMediaIndex()
{
return $this->mediaIndex;
}
/**
* Set media index.
*
* #param int $value
*/
public function setMediaIndex($value)
{
$this->mediaIndex = $value;
}
/**
* Get image string data
*
* #param bool $base64
* #return string|null
* #since 0.11.0
*/
public function getImageStringData($base64 = false)
{
$source = $this->source;
$actualSource = null;
$imageBinary = null;
$imageData = null;
$isTemp = false;
// Get actual source from archive image or other source
// Return null if not found
if ($this->sourceType == self::SOURCE_ARCHIVE) {
$source = substr($source, 6);
list($zipFilename, $imageFilename) = explode('#', $source);
$zip = new ZipArchive();
if ($zip->open($zipFilename) !== false) {
if ($zip->locateName($imageFilename) !== false) {
$isTemp = true;
$zip->extractTo(Settings::getTempDir(), $imageFilename);
$actualSource = Settings::getTempDir() . DIRECTORY_SEPARATOR . $imageFilename;
}
}
$zip->close();
} else {
$actualSource = $source;
}
// Can't find any case where $actualSource = null hasn't captured by
// preceding exceptions. Please uncomment when you find the case and
// put the case into Element\ImageTest.
// if ($actualSource === null) {
// return null;
// }
// Read image binary data and convert to hex/base64 string
if ($this->sourceType == self::SOURCE_GD) {
$imageResource = call_user_func($this->imageCreateFunc, $actualSource);
if ($this->imageType === 'image/png') {
// PNG images need to preserve alpha channel information
imagesavealpha($imageResource, true);
}
ob_start();
call_user_func($this->imageFunc, $imageResource);
$imageBinary = ob_get_contents();
ob_end_clean();
} elseif ($this->sourceType == self::SOURCE_STRING) {
$imageBinary = $this->source;
} else {
$fileHandle = fopen($actualSource, 'rb', false);
if ($fileHandle !== false) {
$imageBinary = fread($fileHandle, filesize($actualSource));
fclose($fileHandle);
}
}
if ($imageBinary !== null) {
if ($base64) {
$imageData = chunk_split(base64_encode($imageBinary));
} else {
$imageData = chunk_split(bin2hex($imageBinary));
}
}
// Delete temporary file if necessary
if ($isTemp === true) {
#unlink($actualSource);
}
return $imageData;
}
/**
* Check memory image, supported type, image functions, and proportional width/height.
*
* #throws \PhpOffice\PhpWord\Exception\InvalidImageException
* #throws \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException
*/
private function checkImage()
{
$this->setSourceType();
// Check image data
if ($this->sourceType == self::SOURCE_ARCHIVE) {
$imageData = $this->getArchiveImageSize($this->source);
} elseif ($this->sourceType == self::SOURCE_STRING) {
$imageData = $this->getStringImageSize($this->source);
} else {
$imageData = #getimagesize($this->source);
}
if (!is_array($imageData)) {
throw new InvalidImageException(sprintf('Invalid image: %s', $this->source));
}
list($actualWidth, $actualHeight, $imageType) = $imageData;
// Check image type support
$supportedTypes = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG);
if ($this->sourceType != self::SOURCE_GD && $this->sourceType != self::SOURCE_STRING) {
$supportedTypes = array_merge($supportedTypes, array(IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM));
}
if (!in_array($imageType, $supportedTypes)) {
throw new UnsupportedImageTypeException();
}
// Define image functions
$this->imageType = image_type_to_mime_type($imageType);
$this->setFunctions();
$this->setProportionalSize($actualWidth, $actualHeight);
}
/**
* Set source type.
*/
private function setSourceType()
{
if (stripos(strrev($this->source), strrev('.php')) === 0) {
$this->memoryImage = true;
$this->sourceType = self::SOURCE_GD;
} elseif (strpos($this->source, 'zip://') !== false) {
$this->memoryImage = false;
$this->sourceType = self::SOURCE_ARCHIVE;
} elseif (filter_var($this->source, FILTER_VALIDATE_URL) !== false) {
$this->memoryImage = true;
if (strpos($this->source, 'https') === 0) {
$fileContent = file_get_contents($this->source);
$this->source = $fileContent;
$this->sourceType = self::SOURCE_STRING;
} else {
$this->sourceType = self::SOURCE_GD;
}
} elseif ((strpos($this->source, chr(0)) === false) && #file_exists($this->source)) {
$this->memoryImage = false;
$this->sourceType = self::SOURCE_LOCAL;
} else {
$this->memoryImage = true;
$this->sourceType = self::SOURCE_STRING;
}
}
/**
* Get image size from archive
*
* #since 0.12.0 Throws CreateTemporaryFileException.
*
* #param string $source
*
* #throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException
*
* #return array|null
*/
private function getArchiveImageSize($source)
{
$imageData = null;
$source = substr($source, 6);
list($zipFilename, $imageFilename) = explode('#', $source);
$tempFilename = tempnam(Settings::getTempDir(), 'PHPWordImage');
if (false === $tempFilename) {
throw new CreateTemporaryFileException(); // #codeCoverageIgnore
}
$zip = new ZipArchive();
if ($zip->open($zipFilename) !== false) {
if ($zip->locateName($imageFilename) !== false) {
$imageContent = $zip->getFromName($imageFilename);
if ($imageContent !== false) {
file_put_contents($tempFilename, $imageContent);
$imageData = getimagesize($tempFilename);
unlink($tempFilename);
}
}
$zip->close();
}
return $imageData;
}
/**
* get image size from string
*
* #param string $source
*
* #codeCoverageIgnore this method is just a replacement for getimagesizefromstring which exists only as of PHP 5.4
*/
private function getStringImageSize($source)
{
$result = false;
if (!function_exists('getimagesizefromstring')) {
$uri = 'data://application/octet-stream;base64,' . base64_encode($source);
$result = #getimagesize($uri);
} else {
$result = #getimagesizefromstring($source);
}
return $result;
}
/**
* Set image functions and extensions.
*/
private function setFunctions()
{
switch ($this->imageType) {
case 'image/png':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefrompng';
$this->imageFunc = 'imagepng';
$this->imageExtension = 'png';
break;
case 'image/gif':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefromgif';
$this->imageFunc = 'imagegif';
$this->imageExtension = 'gif';
break;
case 'image/jpeg':
case 'image/jpg':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefromjpeg';
$this->imageFunc = 'imagejpeg';
$this->imageExtension = 'jpg';
break;
case 'image/bmp':
case 'image/x-ms-bmp':
$this->imageType = 'image/bmp';
$this->imageExtension = 'bmp';
break;
case 'image/tiff':
$this->imageExtension = 'tif';
break;
}
}
/**
* Set proportional width/height if one dimension not available.
*
* #param int $actualWidth
* #param int $actualHeight
*/
private function setProportionalSize($actualWidth, $actualHeight)
{
$styleWidth = $this->style->getWidth();
$styleHeight = $this->style->getHeight();
if (!($styleWidth && $styleHeight)) {
if ($styleWidth == null && $styleHeight == null) {
$this->style->setWidth($actualWidth);
$this->style->setHeight($actualHeight);
} elseif ($styleWidth) {
$this->style->setHeight($actualHeight * ($styleWidth / $actualWidth));
} else {
$this->style->setWidth($actualWidth * ($styleHeight / $actualHeight));
}
}
}
/**
* Get is watermark
*
* #deprecated 0.10.0
*
* #codeCoverageIgnore
*/
public function getIsWatermark()
{
return $this->isWatermark();
}
/**
* Get is memory image
*
* #deprecated 0.10.0
*
* #codeCoverageIgnore
*/
public function getIsMemImage()
{
return $this->isMemImage();
}
}
As you can see from the private function checkImage(), the image source must be jpg, gif on png. Sometimes the format of the image is different. So I want to convert it first to jpg.
But I dont know where to implement the following:
$image =$source;
$img = new Imagick($image);
$img->setImageFormat('jpeg');
I tried to put it within the class as follow but I don't think thats how a class works:
public function __construct($source, $style = null, $watermark = false, $name = null)
{
$image =$source;
$img = new Imagick($image);
$img->setImageFormat('jpeg');
$this->source = $img;
$this->style = $this->setNewStyle(new ImageStyle(), $style, true);
$this->setIsWatermark($watermark);
$this->setName($name);
$this->checkImage();
}
I got the error:
Fatal error: Uncaught Error: Class "PhpOffice\PhpWord\Element\Imagick" not found in /var/www/websource/libraries/vendor/phpoffice/phpword/src/PhpWord/Element/Image.php:145 Stack trace: #0
FYI imagick is installed and work properly when i want to convert an img.
Thank you
It is necessary to expand the method of "sendContent", namely, add a method to delete (deleteDirAfterSend) the directory after downloading the file.
Class: Symfony\Component\HttpFoundation\BinaryFileResponse;
Modify Method: sendContent();
How to implement this correctly?
protected $deleteDir = null;
/**
* Sends the file.
*
* {#inheritdoc}
*/
public function sendContent()
{
if (!$this->isSuccessful()) {
return parent::sendContent();
}
if (0 === $this->maxlen) {
return $this;
}
$out = fopen('php://output', 'wb');
$file = fopen($this->file->getPathname(), 'rb');
stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
fclose($out);
fclose($file);
if ($this->deleteFileAfterSend && file_exists($this->file->getPathname())) {
unlink($this->file->getPathname());
}
if ($this->deleteDirAfterSend && file_exists($this->deleteDir)) {
rmdir($this->deleteDir);
}
return $this;
}
/**
* If this is set to true, the file will be unlinked after the request is send
* Note: If the X-Sendfile header is used, the deleteDirAfterSend setting will not be used.
*
* #param bool $shouldDelete
*
* #param null $dir
* #return $this
*/
public function deleteDirAfterSend($shouldDelete = true, $dir = null)
{
$this->deleteDirAfterSend = $shouldDelete;
$this->deleteDir = $dir;
return $this;
}
I am trying to write a class that will allow me to write data to a file and then read it. In some cases, I also lock the file for write, then unlock it once the writing is done.
The problem that I am having is when trying to get the content of the file using my getCache() method the file becomes empty. It seems that when the getCache() method is called the content of the file are deleted for some reason.
Here is my class
<?php
namespace ICWS;
use \ICWS\showVar;
use \DirectoryIterator;
/**
* CacheHandler
*
* #package ICWS
*/
class CacheHandler {
/* Max time second allowed to keep a session File */
private $maxTimeAllowed = 300;
private $filename = '';
private $handle;
public function __construct( $filename ){
$this->filename = $filename;
// 5% chance to collect garbage when the class is initialized.
if(rand(1, 100) <= 5){
$this->collectGarbage();
}
}
/**
* Add/Update the cached array in the session
*
* #param string $key
* #param bigint $id
* #param array $field
* #return void
*/
public function updateCache($key, $id, array $field)
{
$currentVal = (object) $field;
$this->openFile();
$this->lockFile();
$storage = $this->readFile();
//create a new if the $id does not exists in the cache
if( isset($storage[$key]) && array_key_exists($id, $storage[$key]) ){
$currentVal = (object) $storage[$key][$id];
foreach($field as $k => $v){
$currentVal->$k = $v; //update existing key or add a new one
}
}
$storage[$key][$id] = $currentVal;
new showVar($storage);
$this->updateFile($storage);
$this->unlockFile();
$this->closeFile();
}
/**
* gets the current cache/session for a giving $key
*
* #param string $key
* #return object or boolean
*/
public function getCache($key)
{
$value = false;
$this->openFile();
$storage = $this->readFile();
if(isset($storage[$key])){
$value = $storage[$key];
}
$this->closeFile();
return $value;
}
/**
* removes the $id from the cache/session
*
* #param string $key
* #param bigint $id
* #return boolean
*/
public function removeCache($key, $id)
{
$this->openFile();
$this->lockFile();
$storage = $this->readFile();
if( !isset($storage[$key][$id])){
$this->unlockFile();
$this->closeFile();
return false;
}
unset($storage[$key][$id]);
$this->updateFile($storage);
$this->unlockFile();
$this->closeFile();
return true;
}
/**
* unset a session
*
* #param argument $keys
* #return void
*/
public function truncateCache()
{
if(file_exists($this->filename)){
unlink($this->filename);
}
}
/**
* Open a file in a giving mode
*
* #params string $mode
* #return void
*/
private function openFile( $mode = "w+"){
$this->handle = fopen($this->filename, $mode);
if(!$this->handle){
throw new exception('The File could not be opened!');
}
}
/**
* Close the file
* #return void
*/
private function closeFile(){
fclose($this->handle);
$this->handle = null;
}
/**
* Update the file with array data
* #param array $data the array in that has the data
* #return void
*/
private function updateFile(array $data = array() ){
$raw = serialize($data);
fwrite($this->handle, $raw);
}
/**
* Read the data from the opned file
*
* #params string $mode
* #return array of the data found in the file
*/
private function readFile() {
$length = filesize($this->filename);
if($length > 0){
rewind($this->handle);
$raw = fread($this->handle, filesize($this->filename));
return unserialize($raw);
}
return array();
}
/**
* Lock the file
*
* #return void
*/
private function lockFile( $maxAttempts = 100, $lockType = LOCK_EX) {
$i = 0;
while($i <= $maxAttempts){
// acquire an exclusive lock
if( flock($this->handle, LOCK_EX) ){
break;
}
++$i;
}
}
/**
* Unlock the file
*
* #return void
*/
private function unlockFile() {
fflush($this->handle);
flock($this->handle, LOCK_UN);
}
/**
* Remove add cache files
*
* #return void
*/
private function collectGarbage(){
$mydir = dirname($this->filename);
$dir = new DirectoryIterator( $mydir );
$time = strtotime("now");
foreach ($dir as $file) {
if ( !$file->isDot()
&& $file->isFile()
&& ($time - $file->getATime()) > $this->maxTimeAllowed
&& isset($file->getFilename) && $file->getFilename != 'index.html'
) {
unlink($file->getPathName());
}
}
}
}
This is how I call my class
<?php
require 'autoloader.php';
try {
$cache = new \ICWS\CacheHandler('cache/12300000');
$field = array('name' => 'Mike A', 'Address' => '123 S Main', 'phone' => '2152456245', 'ext' => 123);
$cache->updateCache('NewKey', '123456', $field);
echo '<pre>';
print_r($cache->getCache('NewKey'));
echo '</pre>';
} catch (exception $e){
echo $e->getMessage();
}
?>
When commenting the line print_r($cache->getCache('NewKey')); The file 12300000 will have the data below as expected
a:1:{s:6:"NewKey";a:1:{i:123456;O:8:"stdClass":4:{s:4:"name";s:6:"Mike A";s:7:"Address";s:10:"123 S Main";s:5:"phone";s:10:"2152456245";s:3:"ext";i:123;}}}
However, when the method print_r($cache->getCache('NewKey')); is called the file becomes empty.
What am I doing wrong here? Why is my print_r($cache->getCache('NewKey')); method is emptying out the file?
openFile($mode = "w+")
The documentation for fopen() says:
'w+' Open for reading and writing; 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.
So it resets the file, deleting everything in it.
Probably you want mode a+:
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek()() only affects the reading position, writes are always appended.
When i open https://127.0.0.1/mutillidae/ then my webpage show this error
I also change the permission of LoggerAppenderFile.php but it still error.
The php file code is
<?php
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* #package log4php
* #subpackage appenders
*/
/**
* FileAppender appends log events to a file.
*
* Parameters are ({#link $fileName} but option name is <b>file</b>),
* {#link $append}.
*
* #version $Revision: 806678 $
* #package log4php
* #subpackage appenders
*/
class LoggerAppenderFile extends LoggerAppender {
/**
* #var boolean if {#link $file} exists, appends events.
*/
private $append = true;
/**
* #var string the file name used to append events
*/
protected $fileName;
/**
* #var mixed file resource
*/
protected $fp = false;
public function __construct($name = '') {
parent::__construct($name);
$this->requiresLayout = true;
}
public function __destruct() {
$this->close();
}
public function activateOptions() {
$fileName = $this->getFile();
if(!is_file($fileName)) {
$dir = dirname($fileName);
if(!is_dir($dir)) {
mkdir($dir, 0777, true);
}
}
$this->fp = fopen($fileName, ($this->getAppend()? 'a':'w'));
if($this->fp) {
if(flock($this->fp, LOCK_EX)) {
if($this->getAppend()) {
fseek($this->fp, 0, SEEK_END);
}
fwrite($this->fp, $this->layout->getHeader());
flock($this->fp, LOCK_UN);
$this->closed = false;
} else {
// TODO: should we take some action in this case?
$this->closed = true;
}
} else {
$this->closed = true;
}
}
public function close() {
if($this->closed != true) {
if($this->fp and $this->layout !== null) {
if(flock($this->fp, LOCK_EX)) {
fwrite($this->fp, $this->layout->getFooter());
flock($this->fp, LOCK_UN);
}
fclose($this->fp);
}
$this->closed = true;
}
}
public function append(LoggerLoggingEvent $event) {
if($this->fp and $this->layout !== null) {
if(flock($this->fp, LOCK_EX)) {
fwrite($this->fp, $this->layout->format($event));
flock($this->fp, LOCK_UN);
} else {
$this->closed = true;
}
}
}
/**
* Sets and opens the file where the log output will go.
*
* This is an overloaded method. It can be called with:
* - setFile(string $fileName) to set filename.
* - setFile(string $fileName, boolean $append) to set filename and append.
*/
public function setFile() {
$numargs = func_num_args();
$args = func_get_args();
if($numargs == 1 and is_string($args[0])) {
$this->setFileName($args[0]);
} else if ($numargs >=2 and is_string($args[0]) and is_bool($args[1])) {
$this->setFile($args[0]);
$this->setAppend($args[1]);
}
}
/**
* #return string
*/
public function getFile() {
return $this->getFileName();
}
/**
* #return boolean
*/
public function getAppend() {
return $this->append;
}
public function setAppend($flag) {
$this->append = LoggerOptionConverter::toBoolean($flag, true);
}
public function setFileName($fileName) {
$this->fileName = $fileName;
}
/**
* #return string
*/
public function getFileName() {
return $this->fileName;
}
}
How can i solve this problem ?
I found a solution in http://fanli7.net/a/bianchengyuyan/PHP/20130723/398120.html here but i failed. If this problem is unsolvable then it can occur a big problem for my lab testing ?
OK. I find the solution. Actually you setup a old version of mutillidae. So it was buggy program. Then i find a new version. Here is the download link enter link description here. After you setup it,it will be awesome.
I really need to be able to extract the metadata from a .ttf true type font file.
I'm building a central database of all the fonts all our designers use (they're forever swapping fonts via email to take over design elements, etc). I want to get all the fonts, some have silly names like 00001.ttf, so file name is no help, but I know the fonts have metadata, I need some way to extract that in PHP.
Then I can create a loop to look through the directories I've specified, get this data (and any other data I can get at the same time, and add it to a database.
I just really need help with the reading of this metadata part.
I came across this link. It will do what you want (I've tested it and posted results). Just pass the class the path of the TTF file you want to parse the data out of. then use $fontinfo[1].' '.$fontinfo[2] for the name.
In case you don't want to register, here is the class
Resulting Data
Array
(
[1] => Almonte Snow
[2] => Regular
[3] => RayLarabie: Almonte Snow: 2000
[4] => Almonte Snow
[5] => Version 2.000 2004
[6] => AlmonteSnow
[8] => Ray Larabie
[9] => Ray Larabie
[10] => Larabie Fonts is able to offer unique free fonts through the generous support of visitors to the site. Making fonts is my full-time job and every donation, in any amount, enables me to continue running the site and creating new fonts. If you would like to support Larabie Fonts visit www.larabiefonts.com for details.
[11] => http://www.larabiefonts.com
[12] => http://www.typodermic.com
)
Usage
<?php
include 'ttfInfo.class.php';
$fontinfo = getFontInfo('c:\windows\fonts\_LDS_almosnow.ttf');
echo '<pre>';
print_r($fontinfo);
echo '</pre>';
?>
ttfInfo.class.php
<?php
/**
* ttfInfo class
* Retrieve data stored in a TTF files 'name' table
*
* #original author Unknown
* found at http://www.phpclasses.org/browse/package/2144.html
*
* #ported for used on http://www.nufont.com
* #author Jason Arencibia
* #version 0.2
* #copyright (c) 2006 GrayTap Media
* #website http://www.graytap.com
* #license GPL 2.0
* #access public
*
* #todo: Make it Retrieve additional information from other tables
*
*/
class ttfInfo {
/**
* variable $_dirRestriction
* Restrict the resource pointer to this directory and above.
* Change to 1 for to allow the class to look outside of it current directory
* #protected
* #var int
*/
protected $_dirRestriction = 1;
/**
* variable $_dirRestriction
* Restrict the resource pointer to this directory and above.
* Change to 1 for nested directories
* #protected
* #var int
*/
protected $_recursive = 0;
/**
* variable $fontsdir
* This is to declare this variable as protected
* don't edit this!!!
* #protected
*/
protected $fontsdir;
/**
* variable $filename
* This is to declare this varable as protected
* don't edit this!!!
* #protected
*/
protected $filename;
/**
* function setFontFile()
* set the filename
* #public
* #param string $data the new value
* #return object reference to this
*/
public function setFontFile($data)
{
if ($this->_dirRestriction && preg_match('[\.\/|\.\.\/]', $data))
{
$this->exitClass('Error: Directory restriction is enforced!');
}
$this->filename = $data;
return $this;
} // public function setFontFile
/**
* function setFontsDir()
* set the Font Directory
* #public
* #param string $data the new value
* #return object referrence to this
*/
public function setFontsDir($data)
{
if ($this->_dirRestriction && preg_match('[\.\/|\.\.\/]', $data))
{
$this->exitClass('Error: Directory restriction is enforced!');
}
$this->fontsdir = $data;
return $this;
} // public function setFontsDir
/**
* function readFontsDir()
* #public
* #return information contained in the TTF 'name' table of all fonts in a directory.
*/
public function readFontsDir()
{
if (empty($this->fontsdir)) { $this->exitClass('Error: Fonts Directory has not been set with setFontsDir().'); }
if (empty($this->backupDir)){ $this->backupDir = $this->fontsdir; }
$this->array = array();
$d = dir($this->fontsdir);
while (false !== ($e = $d->read()))
{
if($e != '.' && $e != '..')
{
$e = $this->fontsdir . $e;
if($this->_recursive && is_dir($e))
{
$this->setFontsDir($e);
$this->array = array_merge($this->array, readFontsDir());
}
else if ($this->is_ttf($e) === true)
{
$this->setFontFile($e);
$this->array[$e] = $this->getFontInfo();
}
}
}
if (!empty($this->backupDir)){ $this->fontsdir = $this->backupDir; }
$d->close();
return $this;
} // public function readFontsDir
/**
* function setProtectedVar()
* #public
* #param string $var the new variable
* #param string $data the new value
* #return object reference to this
* DISABLED, NO REAL USE YET
public function setProtectedVar($var, $data)
{
if ($var == 'filename')
{
$this->setFontFile($data);
} else {
//if (isset($var) && !empty($data))
$this->$var = $data;
}
return $this;
}
*/
/**
* function getFontInfo()
* #public
* #return information contained in the TTF 'name' table.
*/
public function getFontInfo()
{
$fd = fopen ($this->filename, "r");
$this->text = fread ($fd, filesize($this->filename));
fclose ($fd);
$number_of_tables = hexdec($this->dec2ord($this->text[4]).$this->dec2ord($this->text[5]));
for ($i=0;$i<$number_of_tables;$i++)
{
$tag = $this->text[12+$i*16].$this->text[12+$i*16+1].$this->text[12+$i*16+2].$this->text[12+$i*16+3];
if ($tag == 'name')
{
$this->ntOffset = hexdec(
$this->dec2ord($this->text[12+$i*16+8]).$this->dec2ord($this->text[12+$i*16+8+1]).
$this->dec2ord($this->text[12+$i*16+8+2]).$this->dec2ord($this->text[12+$i*16+8+3]));
$offset_storage_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+4]).$this->dec2ord($this->text[$this->ntOffset+5]));
$number_name_records_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+2]).$this->dec2ord($this->text[$this->ntOffset+3]));
}
}
$storage_dec = $offset_storage_dec + $this->ntOffset;
$storage_hex = strtoupper(dechex($storage_dec));
for ($j=0;$j<$number_name_records_dec;$j++)
{
$platform_id_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+0]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+1]));
$name_id_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+6]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+7]));
$string_length_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+8]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+9]));
$string_offset_dec = hexdec($this->dec2ord($this->text[$this->ntOffset+6+$j*12+10]).$this->dec2ord($this->text[$this->ntOffset+6+$j*12+11]));
if (!empty($name_id_dec) and empty($font_tags[$name_id_dec]))
{
for($l=0;$l<$string_length_dec;$l++)
{
if (ord($this->text[$storage_dec+$string_offset_dec+$l]) == '0') { continue; }
else { $font_tags[$name_id_dec] .= ($this->text[$storage_dec+$string_offset_dec+$l]); }
}
}
}
return $font_tags;
} // public function getFontInfo
/**
* function getCopyright()
* #public
* #return 'Copyright notice' contained in the TTF 'name' table at index 0
*/
public function getCopyright()
{
$this->info = $this->getFontInfo();
return $this->info[0];
} // public function getCopyright
/**
* function getFontFamily()
* #public
* #return 'Font Family name' contained in the TTF 'name' table at index 1
*/
public function getFontFamily()
{
$this->info = $this->getFontInfo();
return $this->info[1];
} // public function getFontFamily
/**
* function getFontSubFamily()
* #public
* #return 'Font Subfamily name' contained in the TTF 'name' table at index 2
*/
public function getFontSubFamily()
{
$this->info = $this->getFontInfo();
return $this->info[2];
} // public function getFontSubFamily
/**
* function getFontId()
* #public
* #return 'Unique font identifier' contained in the TTF 'name' table at index 3
*/
public function getFontId()
{
$this->info = $this->getFontInfo();
return $this->info[3];
} // public function getFontId
/**
* function getFullFontName()
* #public
* #return 'Full font name' contained in the TTF 'name' table at index 4
*/
public function getFullFontName()
{
$this->info = $this->getFontInfo();
return $this->info[4];
} // public function getFullFontName
/**
* function dec2ord()
* Used to lessen redundant calls to multiple functions.
* #protected
* #return object
*/
protected function dec2ord($dec)
{
return $this->dec2hex(ord($dec));
} // protected function dec2ord
/**
* function dec2hex()
* private function to perform Hexadecimal to decimal with proper padding.
* #protected
* #return object
*/
protected function dec2hex($dec)
{
return str_repeat('0', 2-strlen(($hex=strtoupper(dechex($dec))))) . $hex;
} // protected function dec2hex
/**
* function dec2hex()
* private function to perform Hexadecimal to decimal with proper padding.
* #protected
* #return object
*/
protected function exitClass($message)
{
echo $message;
exit;
} // protected function dec2hex
/**
* function dec2hex()
* private helper function to test in the file in question is a ttf.
* #protected
* #return object
*/
protected function is_ttf($file)
{
$ext = explode('.', $file);
$ext = $ext[count($ext)-1];
return preg_match("/ttf$/i",$ext) ? true : false;
} // protected function is_ttf
} // class ttfInfo
function getFontInfo($resource)
{
$ttfInfo = new ttfInfo;
$ttfInfo->setFontFile($resource);
return $ttfInfo->getFontInfo();
}
?>
Update 2021
Here is an updated version of the class with some fixes
https://github.com/HusamAamer/TTFInfo.git
Very similar to the previously posted answer... I've been using this class for a long time now.
class fontAttributes extends baseClass
{
// --- ATTRIBUTES ---
/**
* #access private
* #var string
*/
private $_fileName = NULL ; // Name of the truetype font file
/**
* #access private
* #var string
*/
private $_copyright = NULL ; // Copyright
/**
* #access private
* #var string
*/
private $_fontFamily = NULL ; // Font Family
/**
* #access private
* #var string
*/
private $_fontSubFamily = NULL ; // Font SubFamily
/**
* #access private
* #var string
*/
private $_fontIdentifier = NULL ; // Font Unique Identifier
/**
* #access private
* #var string
*/
private $_fontName = NULL ; // Font Name
/**
* #access private
* #var string
*/
private $_fontVersion = NULL ; // Font Version
/**
* #access private
* #var string
*/
private $_postscriptName = NULL ; // Postscript Name
/**
* #access private
* #var string
*/
private $_trademark = NULL ; // Trademark
// --- OPERATIONS ---
private function _returnValue($inString)
{
if (ord($inString) == 0) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($inString,"UTF-8","UTF-16");
} else {
return str_replace(chr(00),'',$inString);
}
} else {
return $inString;
}
} // function _returnValue()
/**
* #access public
* #return integer
*/
public function getCopyright()
{
return $this->_returnValue($this->_copyright);
} // function getCopyright()
/**
* #access public
* #return integer
*/
public function getFontFamily()
{
return $this->_returnValue($this->_fontFamily);
} // function getFontFamily()
/**
* #access public
* #return integer
*/
public function getFontSubFamily()
{
return $this->_returnValue($this->_fontSubFamily);
} // function getFontSubFamily()
/**
* #access public
* #return integer
*/
public function getFontIdentifier()
{
return $this->_returnValue($this->_fontIdentifier);
} // function getFontIdentifier()
/**
* #access public
* #return integer
*/
public function getFontName()
{
return $this->_returnValue($this->_fontName);
} // function getFontName()
/**
* #access public
* #return integer
*/
public function getFontVersion()
{
return $this->_returnValue($this->_fontVersion);
} // function getFontVersion()
/**
* #access public
* #return integer
*/
public function getPostscriptName()
{
return $this->_returnValue($this->_postscriptName);
} // function getPostscriptName()
/**
* #access public
* #return integer
*/
public function getTrademark()
{
return $this->_returnValue($this->_trademark);
} // function getTrademark()
/**
* Convert a big-endian word or longword value to an integer
*
* #access private
* #return integer
*/
private function _UConvert($bytesValue,$byteCount)
{
$retVal = 0;
$bytesLength = strlen($bytesValue);
for ($i=0; $i < $bytesLength; $i++) {
$tmpVal = ord($bytesValue{$i});
$t = pow(256,($byteCount-$i-1));
$retVal += $tmpVal*$t;
}
return $retVal;
} // function UConvert()
/**
* Convert a big-endian word value to an integer
*
* #access private
* #return integer
*/
private function _USHORT($stringValue) {
return $this->_UConvert($stringValue,2);
}
/**
* Convert a big-endian word value to an integer
*
* #access private
* #return integer
*/
private function _ULONG($stringValue) {
return $this->_UConvert($stringValue,4);
}
/**
* Read the Font Attributes
*
* #access private
* #return integer
*/
private function readFontAttributes() {
$fontHandle = fopen($this->_fileName, "rb");
// Read the file header
$TT_OFFSET_TABLE = fread($fontHandle, 12);
$uMajorVersion = $this->_USHORT(substr($TT_OFFSET_TABLE,0,2));
$uMinorVersion = $this->_USHORT(substr($TT_OFFSET_TABLE,2,2));
$uNumOfTables = $this->_USHORT(substr($TT_OFFSET_TABLE,4,2));
// $uSearchRange = $this->_USHORT(substr($TT_OFFSET_TABLE,6,2));
// $uEntrySelector = $this->_USHORT(substr($TT_OFFSET_TABLE,8,2));
// $uRangeShift = $this->_USHORT(substr($TT_OFFSET_TABLE,10,2));
// Check is this is a true type font and the version is 1.0
if ($uMajorVersion != 1 || $uMinorVersion != 0) {
fclose($fontHandle);
throw new Exception($this->_fileName.' is not a Truetype font file') ;
}
// Look for details of the name table
$nameTableFound = false;
for ($t=0; $t < $uNumOfTables; $t++) {
$TT_TABLE_DIRECTORY = fread($fontHandle, 16);
$szTag = substr($TT_TABLE_DIRECTORY,0,4);
if (strtolower($szTag) == 'name') {
// $uCheckSum = $this->_ULONG(substr($TT_TABLE_DIRECTORY,4,4));
$uOffset = $this->_ULONG(substr($TT_TABLE_DIRECTORY,8,4));
// $uLength = $this->_ULONG(substr($TT_TABLE_DIRECTORY,12,4));
$nameTableFound = true;
break;
}
}
if (!$nameTableFound) {
fclose($fontHandle);
throw new Exception('Can\'t find name table in '.$this->_fileName) ;
}
// Set offset to the start of the name table
fseek($fontHandle,$uOffset,SEEK_SET);
$TT_NAME_TABLE_HEADER = fread($fontHandle, 6);
// $uFSelector = $this->_USHORT(substr($TT_NAME_TABLE_HEADER,0,2));
$uNRCount = $this->_USHORT(substr($TT_NAME_TABLE_HEADER,2,2));
$uStorageOffset = $this->_USHORT(substr($TT_NAME_TABLE_HEADER,4,2));
$attributeCount = 0;
for ($a=0; $a < $uNRCount; $a++) {
$TT_NAME_RECORD = fread($fontHandle, 12);
$uNameID = $this->_USHORT(substr($TT_NAME_RECORD,6,2));
if ($uNameID <= 7) {
// $uPlatformID = $this->_USHORT(substr($TT_NAME_RECORD,0,2));
$uEncodingID = $this->_USHORT(substr($TT_NAME_RECORD,2,2));
// $uLanguageID = $this->_USHORT(substr($TT_NAME_RECORD,4,2));
$uStringLength = $this->_USHORT(substr($TT_NAME_RECORD,8,2));
$uStringOffset = $this->_USHORT(substr($TT_NAME_RECORD,10,2));
if ($uStringLength > 0) {
$nPos = ftell($fontHandle);
fseek($fontHandle,$uOffset + $uStringOffset + $uStorageOffset,SEEK_SET);
$testValue = fread($fontHandle, $uStringLength);
if (trim($testValue) > '') {
switch ($uNameID) {
case 0 : if ($this->_copyright == NULL) {
$this->_copyright = $testValue;
$attributeCount++;
}
break;
case 1 : if ($this->_fontFamily == NULL) {
$this->_fontFamily = $testValue;
$attributeCount++;
}
break;
case 2 : if ($this->_fontSubFamily == NULL) {
$this->_fontSubFamily = $testValue;
$attributeCount++;
}
break;
case 3 : if ($this->_fontIdentifier == NULL) {
$this->_fontIdentifier = $testValue;
$attributeCount++;
}
break;
case 4 : if ($this->_fontName == NULL) {
$this->_fontName = $testValue;
$attributeCount++;
}
break;
case 5 : if ($this->_fontVersion == NULL) {
$this->_fontVersion = $testValue;
$attributeCount++;
}
break;
case 6 : if ($this->_postscriptName == NULL) {
$this->_postscriptName = $testValue;
$attributeCount++;
}
break;
case 7 : if ($this->_trademark == NULL) {
$this->_trademark = $testValue;
$attributeCount++;
}
break;
}
}
fseek($fontHandle,$nPos,SEEK_SET);
}
}
if ($attributeCount > 7) {
break;
}
}
fclose($fontHandle);
return true;
}
/**
* #access constructor
* #return void
*/
function __construct($fileName='') {
if ($fileName == '') {
throw new Exception('Font File has not been specified') ;
}
$this->_fileName = $fileName;
if (!file_exists($this->_fileName)) {
throw new Exception($this->_fileName.' does not exist') ;
} elseif (!is_readable($this->_fileName)) {
throw new Exception($this->_fileName.' is not a readable file') ;
}
return $this->readFontAttributes();
} // function constructor()
} /* end of class fontAttributes */
Why reinvent the wheel when the fine people at DOMPDF project has already done the work for you? Take a look at php-font-lib # https://github.com/PhenX/php-font-lib. This has all the features that you have asked for and supports other font formats as well. Look at the demo UI # http://pxd.me/php-font-lib/www/font_explorer.html to get an idea about what kind of information you can get from this library.