本文整理汇总了PHP中ftruncate函数的典型用法代码示例。如果您正苦于以下问题:PHP ftruncate函数的具体用法?PHP ftruncate怎么用?PHP ftruncate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ftruncate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: DeleteLyrics3
function DeleteLyrics3()
{
// Initialize getID3 engine
$getID3 = new getID3();
$ThisFileInfo = $getID3->analyze($this->filename);
if (isset($ThisFileInfo['lyrics3']['tag_offset_start']) && isset($ThisFileInfo['lyrics3']['tag_offset_end'])) {
if (is_readable($this->filename) && is_writable($this->filename) && is_file($this->filename) && ($fp = fopen($this->filename, 'a+b'))) {
flock($fp, LOCK_EX);
$oldignoreuserabort = ignore_user_abort(true);
fseek($fp, $ThisFileInfo['lyrics3']['tag_offset_end'], SEEK_SET);
$DataAfterLyrics3 = '';
if ($ThisFileInfo['filesize'] > $ThisFileInfo['lyrics3']['tag_offset_end']) {
$DataAfterLyrics3 = fread($fp, $ThisFileInfo['filesize'] - $ThisFileInfo['lyrics3']['tag_offset_end']);
}
ftruncate($fp, $ThisFileInfo['lyrics3']['tag_offset_start']);
if (!empty($DataAfterLyrics3)) {
fseek($fp, $ThisFileInfo['lyrics3']['tag_offset_start'], SEEK_SET);
fwrite($fp, $DataAfterLyrics3, strlen($DataAfterLyrics3));
}
flock($fp, LOCK_UN);
fclose($fp);
ignore_user_abort($oldignoreuserabort);
return true;
} else {
$this->errors[] = 'Cannot fopen(' . $this->filename . ', "a+b")';
return false;
}
}
// no Lyrics3 present
return true;
}
示例2: writeToLog
public function writeToLog($text)
{
if (empty($text)) {
return;
}
$logFile = $this->logFile;
$logFileHistory = $this->logFileHistory;
$oldAbortStatus = ignore_user_abort(true);
if ($fp = @fopen($logFile, "ab")) {
if (@flock($fp, LOCK_EX)) {
$logSize = @filesize($logFile);
$logSize = intval($logSize);
if ($logSize > $this->maxLogSize) {
$this->logFileHistory = $this->logFile . ".old." . time();
$logFileHistory = $this->logFileHistory;
@copy($logFile, $logFileHistory);
ftruncate($fp, 0);
}
@fwrite($fp, $text);
@fflush($fp);
@flock($fp, LOCK_UN);
@fclose($fp);
}
}
ignore_user_abort($oldAbortStatus);
}
示例3: SaveSession
function SaveSession($session)
{
$name = $this->file['name'];
if (!$this->opened_file) {
if (!($this->opened_file = fopen($name, 'c+'))) {
return $this->SetPHPError('could not open the token file ' . $name, $php_error_message);
}
}
if (!flock($this->opened_file, LOCK_EX)) {
return $this->SetPHPError('could not lock the token file ' . $name . ' for writing', $php_error_message);
}
if (fseek($this->opened_file, 0)) {
return $this->SetPHPError('could not rewind the token file ' . $name . ' for writing', $php_error_message);
}
if (!ftruncate($this->opened_file, 0)) {
return $this->SetPHPError('could not truncate the token file ' . $name . ' for writing', $php_error_message);
}
if (!fwrite($this->opened_file, json_encode($session))) {
return $this->SetPHPError('could not write to the token file ' . $name, $php_error_message);
}
if (!fclose($this->opened_file)) {
return $this->SetPHPError('could not close to the token file ' . $name, $php_error_message);
}
$this->opened_file = false;
return true;
}
示例4: lock
/**
* @inheritdoc
*/
public function lock($class, $waitTime = null)
{
if (isset($this->locked[$class])) {
$this->locked[$class]['count']++;
return true;
}
$lockName = $this->getLockName($class);
$fp = fopen($lockName, 'w');
$locked = false;
if (!$waitTime) {
flock($fp, LOCK_EX);
$locked = true;
} else {
while ($waitTime > 0) {
if (flock($fp, LOCK_EX | LOCK_NB)) {
$locked = true;
break;
}
sleep(1);
$waitTime -= 1;
}
}
if (!$locked) {
fclose($fp);
return false;
}
ftruncate($fp, 0);
fwrite($fp, 'Locked at: ' . microtime(true));
$this->locked[$class] = ['res' => $fp, 'count' => 1];
return true;
}
示例5: renewCache
private function renewCache()
{
$mask = empty($this->cacheRealPath) ? 'w+b' : 'r+b';
$resource = fopen($this->cachePath, $mask);
$exchangeData = array();
if (!empty($resource)) {
$wasLocked = false;
for ($i = 1; $i <= 10; $i++) {
$lock = flock($resource, LOCK_EX | LOCK_NB);
if ($lock) {
if ($wasLocked) {
$exchangeData = json_decode(fread($resource, filesize($this->cacheRealPath)), true);
} else {
$newExchangeData = $this->getFromWeb();
if (!empty($newExchangeData)) {
ftruncate($resource, 0);
$jsonData = json_encode($newExchangeData);
fwrite($resource, $jsonData);
$exchangeData = $newExchangeData;
fflush($resource);
}
}
flock($resource, LOCK_UN);
break;
} else {
$wasLocked = true;
sleep(1);
}
}
}
fclose($resource);
return $exchangeData;
}
示例6: set
/**
* Saves data to the cache. Anything that evaluates to FALSE, NULL,
* '', 0 will not be saved.
*
* @param string $key An identifier for the data.
* @param mixed $data The data to be saved.
* @param integer $ttl Lifetime of the stored data. In seconds.
* @returns boolean TRUE on success, FALSE otherwise.
*/
public static function set($key, $data = false, $ttl = 3600)
{
if (!$key) {
self::$error = "Invalid key";
return false;
}
if (!$data) {
self::$error = "Invalid data";
return false;
}
$key = self::makeFileKey($key);
if (!is_integer($ttl)) {
$ttl = (int) $ttl;
}
$store = array('data' => $data, 'ttl' => time() + $ttl);
$status = false;
try {
$fh = fopen($key, "c");
if (flock($fh, LOCK_EX)) {
ftruncate($fh, 0);
fwrite($fh, json_encode($store));
flock($fh, LOCK_UN);
$status = true;
}
fclose($fh);
} catch (Exception $e) {
self::$error = "Exception caught: " . $e->getMessage();
return false;
}
return $status;
}
示例7: clear
/**
* Clear entries from chosen file.
*
* @param mixed $handle
*/
public function clear($handle)
{
if ($this->open($handle) && is_resource($this->_handles[$handle])) {
@ftruncate($this->_handles[$handle], 0);
}
do_action('learn_press_log_clear', $handle);
}
示例8: CreatePost
/**
* Creates a new post by pushing it to the array
* of blog posts stored in the local directory.
* @param newPost - non-null string containing the new post JSON object.
*/
function CreatePost($newPost)
{
$postFileName = $this->postFilename;
$fileExists = file_exists($postFileName);
$postFile = $this->createBlogPostFileHandle($postFileName, $fileExists);
$fileSize = filesize($postFileName);
// Store some useful variables for blog post parsing.
$contents;
$blogPosts = [];
// Check if file size is larger than 0 or not empty.
if ($fileSize > 0) {
// Read the existing blog post file and store in a string.
$contents = fread($postFile, $fileSize);
// TODO(Jess): Delete later - for debugging.
// print($contents);
// Parse the contents JSON string into an array.
$blogPosts = json_decode($contents, true) ?: [];
// print($blogPosts);
// Clear the blog post file.
ftruncate($postFile, 0);
// Update the pointer back to the beginning of the file.
fseek($postFile, 0);
}
// Push the new blog post to the array of blog posts.
array_push($blogPosts, $newPost);
// Encode and store back into a JSON string.
$postJSONString = json_encode($blogPosts);
// Update the post file to the new JSON string.
fwrite($postFile, $postJSONString);
fclose($postFile);
// TODO(Jess): Delete later - for debugging.
print $postJSONString;
}
示例9: write_cache_file
function write_cache_file($file, $content)
{
// Open
$handle = @fopen($file, 'r+b');
// @ - file may not exist
if (!$handle) {
$handle = fopen($file, 'wb');
if (!$handle) {
return false;
}
}
// Lock
flock($handle, LOCK_EX);
ftruncate($handle, 0);
// Write
if (fwrite($handle, $content) === false) {
// Unlock and close
flock($handle, LOCK_UN);
fclose($handle);
return false;
}
// Unlock and close
flock($handle, LOCK_UN);
fclose($handle);
return true;
}
示例10: unban_callback
protected static function unban_callback($handle, $parameters)
{
$size = $parameters['initial_file_size'];
if (0 === $size) {
return true;
}
$contents = fread($handle, $size);
if (empty($contents)) {
return;
}
$now = time();
$ban_lines = explode("\n", $contents);
$new_bans = array();
// Unban expired bans
foreach ($ban_lines as $ban_line) {
if (empty($ban_line)) {
continue;
}
list($ip, $expires) = explode(' ', $ban_line);
if (!empty($parameters['ip']) && $parameters['ip'] === $ip) {
continue;
}
if (!empty($expires) && (int) $expires > $now) {
$new_bans[] = $ban_line;
}
}
$new_ban_lines = implode("\n", $new_bans);
if (!empty($new_ban_lines)) {
$new_ban_lines .= "\n";
}
// Replace .htaccess contents
ftruncate($handle, 0);
rewind($handle);
return fwrite($handle, $new_ban_lines);
}
示例11: getSequence
function getSequence($name, $folder = '/tmp', $default = 0)
{
// Build a filename from the folder and sequence name
$filename = realpath($folder) . '/' . $name . '.seq';
// Open the file
$fp = fopen($filename, "a+");
// Lock the file so no other processes can use it
if (flock($fp, LOCK_EX)) {
// Fetch the current number from the file
$num = trim(stream_get_contents($fp));
// Check that what we read from the file was a number
if (!ctype_digit($num)) {
// If its not a number, lets reset to the default value
$newnum = $default;
} else {
// If its a number, increment it
$newnum = $num + 1;
}
// Delete the contents of the file
ftruncate($fp, 0);
rewind($fp);
// Write the new number to the file
fwrite($fp, "{$newnum}\n");
// Release the lock
flock($fp, LOCK_UN);
} else {
echo "Couldn't get the lock!";
}
// Close the file
fclose($fp);
// Return the incremented number
return $newnum;
}
示例12: hg_file_write
/**
* 写文件
*
* @return intager 写入数据的字节数
*/
function hg_file_write($filename, $content, $mode = 'rb+')
{
$length = strlen($content);
@touch($filename);
if (!is_writeable($filename)) {
@chmod($filename, 0666);
}
if (($fp = fopen($filename, $mode)) === false) {
trigger_error('hg_file_write() failed to open stream: Permission denied', E_USER_WARNING);
return false;
}
flock($fp, LOCK_EX | LOCK_NB);
$bytes = 0;
if (($bytes = @fwrite($fp, $content)) === false) {
$errormsg = sprintf('file_write() Failed to write %d bytes to %s', $length, $filename);
trigger_error($errormsg, E_USER_WARNING);
return false;
}
if ($mode == 'rb+') {
@ftruncate($fp, $length);
}
@fclose($fp);
// 检查是否写入了所有的数据
if ($bytes != $length) {
$errormsg = sprintf('file_write() Only %d of %d bytes written, possibly out of free disk space.', $bytes, $length);
trigger_error($errormsg, E_USER_WARNING);
return false;
}
// 返回长度
return $bytes;
}
示例13: create
/**
* Creates or overwrites a new JPA archive
*
* @param $archive The full path to the JPA archive
*
* @return bool True on success
*/
public function create($archive)
{
$this->dataFileName = $archive;
// Try to kill the archive if it exists
$fp = @fopen($this->dataFileName, "wb");
if (!($fp === false)) {
@ftruncate($fp, 0);
@fclose($fp);
} else {
if (file_exists($this->dataFileName)) {
@unlink($this->dataFileName);
}
@touch($this->dataFileName);
}
if (!is_writable($archive)) {
$this->error = 'Can\'t open ' . $archive . ' for writing';
return false;
}
// Write the initial instance of the archive header
$this->writeArchiveHeader();
if (!empty($error)) {
return false;
}
return true;
}
示例14: RemoveID3v1
function RemoveID3v1()
{
if ($ThisFileInfo['filesize'] >= pow(2, 31)) {
$this->errors[] = 'Unable to write ID3v1 because file is larger than 2GB';
return false;
}
// File MUST be writeable - CHMOD(646) at least
if (is_writeable($this->filename)) {
if ($fp_source = @fopen($this->filename, 'r+b')) {
fseek($fp_source, -128, SEEK_END);
if (fread($fp_source, 3) == 'TAG') {
ftruncate($fp_source, filesize($this->filename) - 128);
} else {
// no ID3v1 tag to begin with - do nothing
}
fclose($fp_source);
return true;
} else {
$this->errors[] = 'Could not open ' . $this->filename . ' mode "r+b"';
}
} else {
$this->errors[] = $this->filename . ' is not writeable';
}
return false;
}
示例15: write_config_file
function write_config_file($filename, $comments) {
global $config_template;
$tokens = array('{USER}',
'{PASSWORD}',
'{HOST}',
'{PORT}',
'{DBNAME}',
'{TABLE_PREFIX}',
'{HEADER_IMG}',
'{HEADER_LOGO}',
'{GENERATED_COMMENTS}',
'{CONTENT_DIR}',
'{MAIL_USE_SMTP}',
'{GET_FILE}'
);
if ($_POST['step1']['old_path'] != '') {
$values = array(urldecode($_POST['step1']['db_login']),
addslashes(urldecode($_POST['step1']['db_password'])),
$_POST['step1']['db_host'],
$_POST['step1']['db_port'],
$_POST['step1']['db_name'],
$_POST['step1']['tb_prefix'],
addslashes(urldecode($_POST['step1']['header_img'])),
addslashes(urldecode($_POST['step1']['header_logo'])),
$comments,
addslashes(urldecode($_POST['step5']['content_dir'])),
$_POST['step1']['smtp'],
$_POST['step1']['get_file']
);
} else {
$values = array(urldecode($_POST['step2']['db_login']),
addslashes(urldecode($_POST['step2']['db_password'])),
$_POST['step2']['db_host'],
$_POST['step2']['db_port'],
$_POST['step2']['db_name'],
$_POST['step2']['tb_prefix'],
'', //header image
'', //header logo
$comments,
addslashes(urldecode($_POST['step4']['content_dir'])),
$_POST['step3']['smtp'],
$_POST['step4']['get_file']
);
}
$config_template = str_replace($tokens, $values, $config_template);
if (!$handle = @fopen($filename, 'wb')) {
return false;
}
@ftruncate($handle,0);
if (!@fwrite($handle, $config_template, strlen($config_template))) {
return false;
}
@fclose($handle);
return true;
}