how to change upload img url with cakephp? - php

i am use this code to upload image ..this code save uploads url into database table to reuase the url again to view image was uploaded..the problem is to change url that saved into database not to change upload folder (make short ulr to save) like this
from
img/dvds/sunset.jpg
to
dvds/sunset.jpg
this change that i need make me use image() helper easy..
<?php
/**
* App Controller
*
* file: /app/app_controller.php
*/
class AppController extends Controller {
/**
* slug()
* creates a slug from a string
*/
function slug($str) {
// replace spaces with underscore, all to lowercase
$str = strtolower(str_replace(' ', '_', $str));
// create regex pattern
$pattern = "/[^a-zA-Z0-9_]/";
// replace non alphanumeric characters
$str = preg_replace($pattern, '', $str);
return $str;
}
/**
* uploads files to the server
* #params:
* $folder = the folder to upload the files e.g. 'img/files'
* $formdata = the array containing the form files
* $itemId = id of the item (optional) will create a new sub folder
* #return:
* will return an array with the success of each file upload
*/
function upload_files($folder, $formdata, $item_id = null) {
// setup dir names absolute and relative
$folder_url = WWW_ROOT.$folder;
$rel_url = $folder;
// create the folder if it does not exist
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
// if itemId is set create an item folder
if($item_id) {
// set new absolute folder
$folder_url = WWW_ROOT.$folder.'/'.$item_id;
// set new relative folder
$rel_url = $folder.'/'.$item_id;
// create directory
if(!is_dir($folder_url)) {
mkdir($folder_url);
}
}
// list of permitted file types, this is only images but documents can be added
$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png');
// loop through and deal with the files
foreach($formdata as $file) {
// replace spaces with underscores
$filename = str_replace(' ', '_', $file['name']);
// assume filetype is false
$typeOK = false;
// check filetype is ok
foreach($permitted as $type) {
if($type == $file['type']) {
$typeOK = true;
break;
}
}
// if file type ok upload the file
if($typeOK) {
// switch based on error code
switch($file['error']) {
case 0:
// check filename already exists
if(!file_exists($folder_url.'/'.$filename)) {
// create full filename
$full_url = $folder_url.'/'.$filename;
$url = $rel_url.'/'.$filename;
// upload the file
$success = move_uploaded_file($file['tmp_name'], $url);
} else {
// create unique filename and upload file
ini_set('date.timezone', 'Europe/London');
$now = date('d-m-Y-His');
$full_url = $folder_url.'/'.$now.$filename;
$url = $rel_url.'/'.$now.' - '.$filename;
$success = move_uploaded_file($file['tmp_name'], $url);
}
// if upload was successful
if($success) {
// save the url of the file(i want to change this code)
$result['urls'][] = $url;
} else {
$result['errors'][] = "Error uploaded $filename. Please try again.";
}
break;
case 3:
// an error occured
$result['errors'][] = "Error uploading $filename. Please try again.";
break;
default:
// an error occured
$result['errors'][] = "System error uploading $filename. Contact webmaster.";
break;
}
} elseif($file['error'] == 4) {
// no file was selected for upload
$result['nofiles'][] = "No file Selected";
} else {
// unacceptable file type
$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
}
}
return $result;
}
}
?>

Could you not simply change
$result['urls'][] = $url;
to
$result['urls'][] = substr($url, 4);

Related

How do I validate and "read-only" the file using CodeIgniter's File Uploading Class?

I'm trying to upload an Excel file using CodeIgniter. What I want to do is to just read the file without moving/uploading it in my upload path which is required in the configuration.
Yup, I can use the native PHP's $_FILES superglobal variable. But, I like to use the library because it gives me extra security to my app.
So.. how can I upload a file using CI's File Uploading class without being uploaded to my server?
$config['upload_path'] = './public/uploads/';
$config['allowed_types'] = 'xlsx|xls';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile'))
{
$this->output->set_output(array('result' => FALSE, 'message' => $this->upload->display_errors()))->_display();
exit(1);
}
else
{
$data = $this->upload->data();
// Let the model do his work!
$this->load->model('Userlist_Model');
$result = $this->Userlist_Model->extract_list($data);
$this->output->set_output($result)->_display();
}
Here's my solution: Just extend the Upload.php (CI_Upload) by creating MY_Upload inside the libraries folder. Copying the do_upload() method then remove the part where the upload starts:
MY_Upload.php
class MY_Upload extends CI_Upload
{
public function validate_file($field = 'userfile')
{
// Is $_FILES[$field] set? If not, no reason to continue.
if (isset($_FILES[$field]))
{
$_file = $_FILES[$field];
}
// Does the field name contain array notation?
elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1)
{
$_file = $_FILES;
for ($i = 0; $i < $c; $i++)
{
// We can't track numeric iterations, only full field names are accepted
if (($field = trim($matches[0][$i], '[]')) === '' OR ! isset($_file[$field]))
{
$_file = NULL;
break;
}
$_file = $_file[$field];
}
}
if ( ! isset($_file))
{
$this->set_error('upload_no_file_selected', 'debug');
return FALSE;
}
// Is the upload path valid?
if ( ! $this->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
// Was the file able to be uploaded? If not, determine the reason why.
if ( ! is_uploaded_file($_file['tmp_name']))
{
$error = isset($_file['error']) ? $_file['error'] : 4;
switch ($error)
{
case UPLOAD_ERR_INI_SIZE:
$this->set_error('upload_file_exceeds_limit', 'info');
break;
case UPLOAD_ERR_FORM_SIZE:
$this->set_error('upload_file_exceeds_form_limit', 'info');
break;
case UPLOAD_ERR_PARTIAL:
$this->set_error('upload_file_partial', 'debug');
break;
case UPLOAD_ERR_NO_FILE:
$this->set_error('upload_no_file_selected', 'debug');
break;
case UPLOAD_ERR_NO_TMP_DIR:
$this->set_error('upload_no_temp_directory', 'error');
break;
case UPLOAD_ERR_CANT_WRITE:
$this->set_error('upload_unable_to_write_file', 'error');
break;
case UPLOAD_ERR_EXTENSION:
$this->set_error('upload_stopped_by_extension', 'debug');
break;
default:
$this->set_error('upload_no_file_selected', 'debug');
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$this->file_temp = $_file['tmp_name'];
$this->file_size = $_file['size'];
// Skip MIME type detection?
if ($this->detect_mime !== FALSE)
{
$this->_file_mime_type($_file);
}
$this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type);
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
$this->file_name = $this->_prep_filename($_file['name']);
$this->file_ext = $this->get_extension($this->file_name);
$this->client_name = $this->file_name;
// Is the file type allowed to be uploaded?
if ( ! $this->is_allowed_filetype())
{
$this->set_error('upload_invalid_filetype', 'debug');
return FALSE;
}
// if we're overriding, let's now make sure the new name and type is allowed
if ($this->_file_name_override !== '')
{
$this->file_name = $this->_prep_filename($this->_file_name_override);
// If no extension was provided in the file_name config item, use the uploaded one
if (strpos($this->_file_name_override, '.') === FALSE)
{
$this->file_name .= $this->file_ext;
}
else
{
// An extension was provided, let's have it!
$this->file_ext = $this->get_extension($this->_file_name_override);
}
if ( ! $this->is_allowed_filetype(TRUE))
{
$this->set_error('upload_invalid_filetype', 'debug');
return FALSE;
}
}
// Convert the file size to kilobytes
if ($this->file_size > 0)
{
$this->file_size = round($this->file_size/1024, 2);
}
// Is the file size within the allowed maximum?
if ( ! $this->is_allowed_filesize())
{
$this->set_error('upload_invalid_filesize', 'info');
return FALSE;
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basedir restriction.
if ( ! $this->is_allowed_dimensions())
{
$this->set_error('upload_invalid_dimensions', 'info');
return FALSE;
}
// Sanitize the file name for security
$this->file_name = $this->_CI->security->sanitize_filename($this->file_name);
// Truncate the file name if it's too long
if ($this->max_filename > 0)
{
$this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
}
// Remove white spaces in the name
if ($this->remove_spaces === TRUE)
{
$this->file_name = preg_replace('/\s+/', '_', $this->file_name);
}
if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext)))
{
// file_ext was previously lower-cased by a get_extension() call
$this->file_name = substr($this->file_name, 0, -$ext_length).$this->file_ext;
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$this->orig_name = $this->file_name;
if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name)))
{
return FALSE;
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($this->xss_clean && $this->do_xss_clean() === FALSE)
{
$this->set_error('upload_unable_to_write_file', 'error');
return FALSE;
}
/*
* Set the finalized image dimensions
* This sets the image width/height (assuming the
* file was an image). We use this information
* in the "data" function.
*/
$this->set_image_properties($this->upload_path.$this->file_name);
// Return true if the file passed the validation
return TRUE;
}
}

Uploading files in Fine-Uploader, fail to combine/merge chunks after successful upload

So I've been trying to get Chunked uploading working for a project I've been working on, I'm pretty new to things, in fact for all intensive purposes you can consider me a complete noob who is teaching himself, I'm using the Manual Upload Template from the website, and the Traditional Server Side Example files to gain an understanding of how the code works and trying to piece them together into a fully functional example for me to build from. I've been able to get most things working.
I've managed to get it uploading regular files into the files folder successfully if I upload a file without chunking it goes into my files directory, however if I use chunking it works to chunk up the file and upload it into a folder in my Chunks directory, but i cant seem to figure out how to get it to put the chunks back together and place it in the Files directory
My Firefox console gives me this response and stops after finishing uploading a file in chunks regardless of if I have my chunking success endpoint included in my code or not which makes me think it's got something to do with my chunking success endpoint not being set up correctly or something along those lines.
[Fine Uploader 5.11.8] All chunks have been uploaded for 0 - finalizing....fine-uploader.js:162:21
[Fine Uploader 5.11.8] Received response status 200 with body: {"success":true,"uuid":"79e7db33-9609-49cd-bcb1-2606bea6abd7","uploadName":null}fine-uploader.js:162:21
[Fine Uploader 5.11.8] Finalize successful for 0
I've spent about 2 days researching this with no avail, I don't seem to be getting errors, but as I said I'm pretty much a Noob when it comes to understanding this on my own. Any help is Greatly Appreciated.
Here Is my Uploader Code Body
<body>
<!-- Fine Uploader DOM Element
====================================================================== -->
<div id="fine-uploader-manual-trigger"></div>
<!-- Your code to create an instance of Fine Uploader and bind to the DOM/template
====================================================================== -->
<script>
var manualUploader = new qq.FineUploader({
debug: true,
element: document.getElementById('fine-uploader-manual-trigger'),
template: 'qq-template-manual-trigger',
request: {
endpoint: 'endpoint.php'
},
chunking: {
enabled: true
},
success: {
endpoint: "endpoint.php?done"
},
resume: {
enabled: true
},
thumbnails: {
placeholders: {
waitingPath: 'images/waiting-generic.png',
notAvailablePath: 'images/not_available-generic.png'
}
},
autoUpload: false,
showMessage: function(message) { //show message if any error occur during upload process
alert(message);
}
});
qq(document.getElementById("trigger-upload")).attach("click", function() {
manualUploader.uploadStoredFiles();
});
</script>
</body>
</html>
Here Is my Endpoint.php File
require_once "handler.php";
$uploader = new UploadHandler();
// Specify the list of valid extensions, ex. array("jpeg", "xml", "bmp")
$uploader->allowedExtensions = array(); // all files types allowed by default
// Specify max file size in bytes.
$uploader->sizeLimit = null;
// Specify the input name set in the javascript.
$uploader->inputName = "qqfile"; // matches Fine Uploader's default inputName value by default
// If you want to use the chunking/resume feature, specify the folder to temporarily save parts.
$uploader->chunksFolder = "chunks";
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
header("Content-Type: text/plain");
// Assumes you have a chunking.success.endpoint set to point here with a query parameter of "done".
// For example: /myserver/handlers/endpoint.php?done
if (isset($_GET["done"])) {
$result = $uploader->combineChunks("files");
}
// Handles upload requests
else {
// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
$result = $uploader->handleUpload("files");
// To return a name used for uploaded file you can use the following line.
$result["uploadName"] = $uploader->getUploadName();
}
echo json_encode($result);
}
// for delete file requests
else if ($method == "DELETE") {
$result = $uploader->handleDelete("files");
echo json_encode($result);
}
else {
header("HTTP/1.0 405 Method Not Allowed");
}
?>
Here is my handler.php file, I'm just using the default traditional server side example.
class UploadHandler {
public $allowedExtensions = array();
public $sizeLimit = null;
public $inputName = 'qqfile';
public $chunksFolder = 'chunks';
public $chunksCleanupProbability = 0.001; // Once in 1000 requests on avg
public $chunksExpireIn = 604800; // One week
protected $uploadName;
/**
* Get the original filename
*/
public function getName(){
if (isset($_REQUEST['qqfilename']))
return $_REQUEST['qqfilename'];
if (isset($_FILES[$this->inputName]))
return $_FILES[$this->inputName]['name'];
}
public function getInitialFiles() {
$initialFiles = array();
for ($i = 0; $i < 5000; $i++) {
array_push($initialFiles, array("name" => "name" + $i, uuid => "uuid" + $i, thumbnailUrl => ""));
}
return $initialFiles;
}
/**
* Get the name of the uploaded file
*/
public function getUploadName(){
return $this->uploadName;
}
public function combineChunks($uploadDirectory, $name = null) {
$uuid = $_POST['qquuid'];
if ($name === null){
$name = $this->getName();
}
$targetFolder = $this->chunksFolder.DIRECTORY_SEPARATOR.$uuid;
$totalParts = isset($_REQUEST['qqtotalparts']) ? (int)$_REQUEST['qqtotalparts'] : 1;
$targetPath = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
$this->uploadName = $name;
if (!file_exists($targetPath)){
mkdir(dirname($targetPath), 0777, true);
}
$target = fopen($targetPath, 'wb');
for ($i=0; $i<$totalParts; $i++){
$chunk = fopen($targetFolder.DIRECTORY_SEPARATOR.$i, "rb");
stream_copy_to_stream($chunk, $target);
fclose($chunk);
}
// Success
fclose($target);
for ($i=0; $i<$totalParts; $i++){
unlink($targetFolder.DIRECTORY_SEPARATOR.$i);
}
rmdir($targetFolder);
if (!is_null($this->sizeLimit) && filesize($targetPath) > $this->sizeLimit) {
unlink($targetPath);
http_response_code(413);
return array("success" => false, "uuid" => $uuid, "preventRetry" => true);
}
return array("success" => true, "uuid" => $uuid);
}
/**
* Process the upload.
* #param string $uploadDirectory Target directory.
* #param string $name Overwrites the name of the file.
*/
public function handleUpload($uploadDirectory, $name = null){
if (is_writable($this->chunksFolder) &&
1 == mt_rand(1, 1/$this->chunksCleanupProbability)){
// Run garbage collection
$this->cleanupChunks();
}
// Check that the max upload size specified in class configuration does not
// exceed size allowed by server config
if ($this->toBytes(ini_get('post_max_size')) < $this->sizeLimit ||
$this->toBytes(ini_get('upload_max_filesize')) < $this->sizeLimit){
$neededRequestSize = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
return array('error'=>"Server error. Increase post_max_size and upload_max_filesize to ".$neededRequestSize);
}
if ($this->isInaccessible($uploadDirectory)){
return array('error' => "Server error. Uploads directory isn't writable");
}
$type = $_SERVER['CONTENT_TYPE'];
if (isset($_SERVER['HTTP_CONTENT_TYPE'])) {
$type = $_SERVER['HTTP_CONTENT_TYPE'];
}
if(!isset($type)) {
return array('error' => "No files were uploaded.");
} else if (strpos(strtolower($type), 'multipart/') !== 0){
return array('error' => "Server error. Not a multipart request. Please set forceMultipart to default value (true).");
}
// Get size and name
$file = $_FILES[$this->inputName];
$size = $file['size'];
if (isset($_REQUEST['qqtotalfilesize'])) {
$size = $_REQUEST['qqtotalfilesize'];
}
if ($name === null){
$name = $this->getName();
}
// check file error
if($file['error']) {
return array('error' => 'Upload Error #'.$file['error']);
}
// Validate name
if ($name === null || $name === ''){
return array('error' => 'File name empty.');
}
// Validate file size
if ($size == 0){
return array('error' => 'File is empty.');
}
if (!is_null($this->sizeLimit) && $size > $this->sizeLimit) {
return array('error' => 'File is too large.', 'preventRetry' => true);
}
// Validate file extension
$pathinfo = pathinfo($name);
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
if($this->allowedExtensions && !in_array(strtolower($ext), array_map("strtolower", $this->allowedExtensions))){
$these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
}
// Save a chunk
$totalParts = isset($_REQUEST['qqtotalparts']) ? (int)$_REQUEST['qqtotalparts'] : 1;
$uuid = $_REQUEST['qquuid'];
if ($totalParts > 1){
# chunked upload
$chunksFolder = $this->chunksFolder;
$partIndex = (int)$_REQUEST['qqpartindex'];
if (!is_writable($chunksFolder) && !is_executable($uploadDirectory)){
return array('error' => "Server error. Chunks directory isn't writable or executable.");
}
$targetFolder = $this->chunksFolder.DIRECTORY_SEPARATOR.$uuid;
if (!file_exists($targetFolder)){
mkdir($targetFolder, 0777, true);
}
$target = $targetFolder.'/'.$partIndex;
$success = move_uploaded_file($_FILES[$this->inputName]['tmp_name'], $target);
return array("success" => true, "uuid" => $uuid);
}
else {
# non-chunked upload
$target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
if ($target){
$this->uploadName = basename($target);
if (!is_dir(dirname($target))){
mkdir(dirname($target), 0777, true);
}
if (move_uploaded_file($file['tmp_name'], $target)){
return array('success'=> true, "uuid" => $uuid);
}
}
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
}
/**
* Process a delete.
* #param string $uploadDirectory Target directory.
* #params string $name Overwrites the name of the file.
*
*/
public function handleDelete($uploadDirectory, $name=null)
{
if ($this->isInaccessible($uploadDirectory)) {
return array('error' => "Server error. Uploads directory isn't writable" . ((!$this->isWindows()) ? " or executable." : "."));
}
$targetFolder = $uploadDirectory;
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$tokens = explode('/', $url);
$uuid = $tokens[sizeof($tokens)-1];
$target = join(DIRECTORY_SEPARATOR, array($targetFolder, $uuid));
if (is_dir($target)){
$this->removeDir($target);
return array("success" => true, "uuid" => $uuid);
} else {
return array("success" => false,
"error" => "File not found! Unable to delete.".$url,
"path" => $uuid
);
}
}
/**
* Returns a path to use with this upload. Check that the name does not exist,
* and appends a suffix otherwise.
* #param string $uploadDirectory Target directory
* #param string $filename The name of the file to use.
*/
protected function getUniqueTargetPath($uploadDirectory, $filename)
{
// Allow only one process at the time to get a unique file name, otherwise
// if multiple people would upload a file with the same name at the same time
// only the latest would be saved.
if (function_exists('sem_acquire')){
$lock = sem_get(ftok(__FILE__, 'u'));
sem_acquire($lock);
}
$pathinfo = pathinfo($filename);
$base = $pathinfo['filename'];
$ext = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';
$ext = $ext == '' ? $ext : '.' . $ext;
$unique = $base;
$suffix = 0;
// Get unique file name for the file, by appending random suffix.
while (file_exists($uploadDirectory . DIRECTORY_SEPARATOR . $unique . $ext)){
$suffix += rand(1, 999);
$unique = $base.'-'.$suffix;
}
$result = $uploadDirectory . DIRECTORY_SEPARATOR . $unique . $ext;
// Create an empty target file
if (!touch($result)){
// Failed
$result = false;
}
if (function_exists('sem_acquire')){
sem_release($lock);
}
return $result;
}
/**
* Deletes all file parts in the chunks folder for files uploaded
* more than chunksExpireIn seconds ago
*/
protected function cleanupChunks(){
foreach (scandir($this->chunksFolder) as $item){
if ($item == "." || $item == "..")
continue;
$path = $this->chunksFolder.DIRECTORY_SEPARATOR.$item;
if (!is_dir($path))
continue;
if (time() - filemtime($path) > $this->chunksExpireIn){
$this->removeDir($path);
}
}
}
/**
* Removes a directory and all files contained inside
* #param string $dir
*/
protected function removeDir($dir){
foreach (scandir($dir) as $item){
if ($item == "." || $item == "..")
continue;
if (is_dir($item)){
$this->removeDir($item);
} else {
unlink(join(DIRECTORY_SEPARATOR, array($dir, $item)));
}
}
rmdir($dir);
}
/**
* Converts a given size with units to bytes.
* #param string $str
*/
protected function toBytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
return $val;
}
/**
* Determines whether a directory can be accessed.
*
* is_executable() is not reliable on Windows prior PHP 5.0.0
* (http://www.php.net/manual/en/function.is-executable.php)
* The following tests if the current OS is Windows and if so, merely
* checks if the folder is writable;
* otherwise, it checks additionally for executable status (like before).
*
* #param string $directory The target directory to test access
*/
protected function isInaccessible($directory) {
$isWin = $this->isWindows();
$folderInaccessible = ($isWin) ? !is_writable($directory) : ( !is_writable($directory) && !is_executable($directory) );
return $folderInaccessible;
}
/**
* Determines is the OS is Windows or not
*
* #return boolean
*/
protected function isWindows() {
$isWin = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
return $isWin;
}
}
Thanks for the help in making sure my code was correct, Kicked myself in the face for this one! As I was thinking for the longest time a incorrectly setup Apache Environment has been the root of all my problems.
I did not have .htaccess setup which seemed to fix all of my problems.
Here are the steps I followed to resolve my problem.
First Step
Open apache.conf file as
sudo vim /etc/apache2/apache2.conf
Second Step
remove comment sign (#) if you find it before this line ( line number 187 approx.)
AccessFileName .htaccess
Third Step
Then find the line where there is
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
replace "None" with "All"
AllowOverride All
Step Four
Activate ModRewrite:
sudo a2enmod rewrite
sudo service apache2 restart
Everything should be Good from here.

Delete an image in PHP (WordPress)

I have this code which uploads an image from admin and it works well.
add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
}
function validate_setting($theme_options) {
$keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {
// if a files was upload
if ($image['size']) {
// if it is an image
if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false);
$options = get_option('theme_options'); echo "<img src='{$options['logo']}' />";
// save the file, and store an array, containing its location in $file
$file = wp_handle_upload( $image, $override ); $theme_options[$keys[$i]] = $file['url']; } else {
// Not an image.
$options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$logo];
// Die and let the user know that they made a mistake.
wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.'); } } // Else, the user didn't upload a file.
// Retain the image that's already on file.
else { $options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$keys[$i]]; } $i++; }
return $theme_options;
}
and now I want the function to delete the current image.
function delete_file($theme_options) {
if (array_key_exists('delete_file', $_FILES)) {
$image = $_FILES['delete_file'];
if (file_exists($image)) {
unlink($image);
echo 'File '.$image.' has been deleted';
} else {
echo 'Could not delete '.$image.', file does not exist';
}
}
}
I added the button in admin but is doing.. nothing.
I'm building a TemplateOptions in WordPress and now I'm trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field "delete" to work.
I found out that you don't need to insert the record in the DB as you only have a single image and whose name and path are also constant . So you simply need to unlink the image from the directory and it will be deleted, nothing else.
say your logo.png is in your themes's img folder then you should unlink it like this. default is your theme name
$path = ABSPATH.'wp-content/themes/default/img/logo.png';
if(file_exists($path))
{
unlink( $path );
}
Note: Remember that you have to pass the absolute path to the unlink() and not the url having http , because it will give you an error , you can't use http with unlink.

how to check and delete if file uploaded before with codeigniter

i build function to upload zip files but when user upload file two times it didnt delete the first uploaded file but added increment number to the file name (( file.zip,file1.zip,file2.zip,,,etc )
so i want to tell the function when the user uploaded the same file name delete the first file and upload this second file or replace it ... anyone help me how to do that...
/**
* change book source file
*
* #param integer $book_id
*/
public function upload_book_zip($book_id) {
$vars = array();
$vars['upload_path'] = PUBPATH . 'global/modules/bookstore/files/books_source_file/';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
$book = $this->d_book->find_by_id($book_id);
if (isset($_POST['submit'])) {
$file_name = $this->upload($vars);
if ($file_name === NULL) { // error happens while uploading file
$vars['upload_errors'] = $this->upload->display_errors("<p class='notification n-error'>", "</p>");
} else {
$this->d_book->update_one_field($book_id, 'bo_path_zip', $file_name);
$this->session->set_flashdata('success_msg', lang('file_uploaded'));
redirect('bookstore/admin_d_book/');
}
} else {
$vars['upload_errors'] = NULL;
}
if ($book->bo_path_zip) { // load cover image
$vars['file_path'] = base_url() . 'global/modules/bookstore/files/books_source_file/' . $book->bo_path_zip;
} else {
$vars['file_path'] = NULL;
}
$vars['controller_name'] = 'admin_d_book';
$this->view('bookstore/admin/change_zip_file', $vars);
}
/**
*
* #param array $config the configuration array
* #return string
*
*/
private function upload($config) {
$this->load->library('upload', $config);
if (!$this->upload->do_upload("file")) {
return $uploadData['file_name'] = NULL;
} else {
$uploadData = $this->upload->data();
log_message('debug', 'file has been uploaded ok - file name is ' . $uploadData['file_name']);
return $uploadData['file_name'];
}
}
you can do that by adding
$vars['overwrite'] = TRUE;
better check File upload library
Set overwrite to true in the config array you pass
$vars = array();
$vars['upload_path'] = 'filepath here';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
// add this line
$vars['overwrite'] = true;
// the old file will now get overwritten
$file_name = $this->upload($vars)
A better method is to check the md5 or sha1 checksum of the file.
If two users uploads two different files with the same name to the server, the file on server will be overwritten and it is impossible to distingush the file by just name.
Also, it can be done easily in PHP.

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories