/**
  * Save an uploaded file to a new location.
  *
  * @param   mixed    name of $_FILE input or array of upload data
  * @param   string   new filename
  * @param   string   new directory
  * @param   integer  chmod mask
  * @return  string   full path to new file
  */
 public static function save($file, $filename = NULL, $directory = NULL, $chmod = 0755)
 {
     // Load file data from FILES if not passed as array
     $file = is_array($file) ? $file : $_FILES[$file];
     if ($filename === NULL) {
         // Use the default filename, with a timestamp pre-pended
         $filename = time() . $file['name'];
     }
     // Remove spaces from the filename
     $filename = preg_replace('/\\s+/', '_', $filename);
     if ($directory === NULL) {
         // Use the pre-configured upload directory
         $directory = WWW_ROOT . 'files/';
     }
     // Make sure the directory ends with a slash
     $directory = rtrim($directory, '/') . '/';
     if (!is_dir($directory)) {
         // Create the upload directory
         mkdir($directory, 0777, TRUE);
     }
     //if ( ! is_writable($directory))
     //throw new exception;
     if (is_uploaded_file($file['tmp_name']) and move_uploaded_file($file['tmp_name'], $filename = $directory . $filename)) {
         if ($chmod !== FALSE) {
             // Set permissions on filename
             chmod($filename, $chmod);
         }
         //$all_file_name = array(FILE_INFO => $filename);
         // Return new file path
         return $filename;
     }
     return FALSE;
 }
 /**
  * Upload component
  *
  * @requires component package file,
  *
  * @return bool;
  */
 public function upload()
 {
     $archive = new ZipArchive();
     $data_dir = ossn_get_userdata('tmp/components');
     if (!is_dir($data_dir)) {
         mkdir($data_dir, 0755, true);
     }
     $zip = $_FILES['com_file'];
     $newfile = "{$data_dir}/{$zip['name']}";
     if (move_uploaded_file($zip['tmp_name'], $newfile)) {
         if ($archive->open($newfile) === TRUE) {
             $archive->extractTo($data_dir);
             //make community components works on installer #394
             $validate = $archive->statIndex(0);
             $validate = str_replace('/', '', $validate['name']);
             $archive->close();
             if (is_dir("{$data_dir}/{$validate}") && is_file("{$data_dir}/{$validate}/ossn_com.php") && is_file("{$data_dir}/{$validate}/ossn_com.xml")) {
                 $archive->open($newfile);
                 $archive->extractTo(ossn_route()->com);
                 $archive->close();
                 $this->newCom($validate);
                 OssnFile::DeleteDir($data_dir);
                 return true;
             }
         }
     }
     return false;
 }
Exemplo n.º 3
1
 public static function getUrlUploadMultiImages($obj, $user_id)
 {
     $url_arr = array();
     $min_size = 1024 * 1000 * 700;
     $max_size = 1024 * 1000 * 1000 * 3.5;
     foreach ($obj["tmp_name"] as $key => $tmp_name) {
         $ext_arr = array('png', 'jpg', 'jpeg', 'bmp');
         $name = StringHelper::filterString($obj['name'][$key]);
         $storeFolder = Yii::getPathOfAlias('webroot') . '/images/' . date('Y-m-d', time()) . '/' . $user_id . '/';
         $pathUrl = 'images/' . date('Y-m-d', time()) . '/' . $user_id . '/' . time() . $name;
         if (!file_exists($storeFolder)) {
             mkdir($storeFolder, 0777, true);
         }
         $tempFile = $obj['tmp_name'][$key];
         $targetFile = $storeFolder . time() . $name;
         $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
         $size = $obj['name']['size'];
         if (in_array($ext, $ext_arr)) {
             if ($size >= $min_size && $size <= $max_size) {
                 if (move_uploaded_file($tempFile, $targetFile)) {
                     array_push($url_arr, $pathUrl);
                 } else {
                     return NULL;
                 }
             } else {
                 return NULL;
             }
         } else {
             return NULL;
         }
     }
     return $url_arr;
 }
Exemplo n.º 4
1
 function addnew()
 {
     if ($_POST) {
         $image = $_FILES['logo'];
         $image_name = $image['name'];
         $image_tmp = $image['tmp_name'];
         $image_size = $image['size'];
         $error = $image['error'];
         $file_ext = explode('.', $image_name);
         $file_ext = strtolower(end($file_ext));
         $allowed_ext = array('jpg', 'jpeg', 'bmp', 'png', 'gif');
         $file_on_server = '';
         if (in_array($file_ext, $allowed_ext)) {
             if ($error === 0) {
                 if ($image_size < 3145728) {
                     $file_on_server = uniqid() . '.' . $file_ext;
                     $destination = './brand_img/' . $file_on_server;
                     move_uploaded_file($image_tmp, $destination);
                 }
             }
         }
         $values = array('name' => $this->input->post('name'), 'description' => $this->input->post('desc'), 'logo' => $file_on_server, 'is_active' => 1);
         if ($this->brand->create($values)) {
             $this->session->set_flashdata('message', 'New Brand added successfully');
         } else {
             $this->session->set_flashdata('errormessage', 'Oops! Something went wrong!!');
         }
         redirect(base_url() . 'brands/');
     }
     $this->load->helper('form');
     $this->load->view('includes/header', array('title' => 'Add Brand'));
     $this->load->view('brand/new_brand');
     $this->load->view('includes/footer');
 }
Exemplo n.º 5
1
 function save($overwrite = true)
 {
     global $messageStack;
     if (!$overwrite and file_exists($this->destination . $this->filename)) {
         $messageStack->add_session(TEXT_IMAGE_OVERWRITE_WARNING . $this->filename, 'caution');
         return true;
     } else {
         if (substr($this->destination, -1) != '/') {
             $this->destination .= '/';
         }
         if (move_uploaded_file($this->file['tmp_name'], $this->destination . $this->filename)) {
             chmod($this->destination . $this->filename, $this->permissions);
             if ($this->message_location == 'direct') {
                 $messageStack->add(sprintf(SUCCESS_FILE_SAVED_SUCCESSFULLY, $this->filename), 'success');
             } else {
                 $messageStack->add_session(sprintf(SUCCESS_FILE_SAVED_SUCCESSFULLY, $this->filename), 'success');
             }
             return true;
         } else {
             if ($this->message_location == 'direct') {
                 $messageStack->add(ERROR_FILE_NOT_SAVED, 'error');
             } else {
                 $messageStack->add_session(ERROR_FILE_NOT_SAVED, 'error');
             }
             return false;
         }
     }
 }
Exemplo n.º 6
0
function UploadImage($bukti_name)
{
    //direktori gambar
    $vdir_upload = "bukti/";
    $vfile_upload = $vdir_upload . $bukti_name;
    //Simpan gambar dalam ukuran sebenarnya
    move_uploaded_file($_FILES["bukti"]["tmp_name"], $vfile_upload);
    //identitas file asli
    $im_src = imagecreatefromjpeg($vfile_upload);
    $src_width = imageSX($im_src);
    $src_height = imageSY($im_src);
    //Simpan dalam versi small 110 pixel
    //Set ukuran gambar hasil perubahan
    $dst_width = 50;
    $dst_height = $dst_width / $src_width * $src_height;
    //proses perubahan ukuran
    $im = imagecreatetruecolor($dst_width, $dst_height);
    imagecopyresampled($im, $im_src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
    //Simpan gambar
    imagejpeg($im, $vdir_upload . "small_" . $bukti_name);
    //Simpan dalam versi medium 360 pixel
    //Set ukuran gambar hasil perubahan
    $dst_width2 = 270;
    $dst_height2 = $dst_width2 / $src_width * $src_height;
    //proses perubahan ukuran
    $im2 = imagecreatetruecolor($dst_width2, $dst_height2);
    imagecopyresampled($im2, $im_src, 0, 0, 0, 0, $dst_width2, $dst_height2, $src_width, $src_height);
    //Simpan gambar
    imagejpeg($im2, $vdir_upload . "medium_" . $bukti_name);
    //Hapus gambar di memori komputer
    imagedestroy($im_src);
    imagedestroy($im);
    imagedestroy($im2);
}
Exemplo n.º 7
0
 /**
  * POST: /file-tiny-mce/upload-file
  */
 public function uploadFilePost()
 {
     $path = $_REQUEST['Path'];
     $uploadFile = $_SERVER['DOCUMENT_ROOT'] . Config::$SUB_FOLDER . '/' . $path . basename($_FILES['File']['name']);
     move_uploaded_file($_FILES['File']['tmp_name'], $uploadFile);
     parent::redirectToUrlFromAction('file-tiny-mce', 'index', $path == '' ? '' : substr($path, 0, -1));
 }
Exemplo n.º 8
0
 public function yukle($dosya)
 {
     $this->dosya = $dosya;
     if (isset($this->dosya['name']) && empty($this->dosya['name'])) {
         return $this->mesaj('Lütfen Yüklenecek Resmi Seçiniz.');
     } else {
         if ($this->dosya['size'] > $this->limit * 1024) {
             return $this->mesaj('Resim Yükleme Limitini Aştınız.! MAX: ' . $this->limit . 'KB Yükleyebilirsiniz.');
         } else {
             if ($this->dosya['type'] == "image/gif" || $this->dosya['type'] == "image/pjpeg" || $this->dosya['type'] == "image/jpeg" || $this->dosya['type'] == "image/png") {
                 $yeni = time() . substr(md5(mt_rand(9, 999)), 8, 4);
                 $file = $this->dosya['name'];
                 $dosya_yolu = $this->buyuk . "/" . basename($yeni . substr($file, strrpos($file, ".")));
                 if (@move_uploaded_file($this->dosya['tmp_name'], $dosya_yolu)) {
                     $resim = $yeni . substr($file, strrpos($file, "."));
                     @chmod("./" . $dosya_yolu . $resim, 0644);
                     $this->createthumb($this->buyuk . $resim, $this->kucuk . $resim, $this->boyut, $this->boyut);
                     return $this->mesaj($this->succes, $resim, 1);
                 }
             } else {
                 return $this->mesaj('Yanlış Bir Format Yüklemeye Çalıştınız. Format : JPG - GIF - PNG');
             }
         }
     }
 }
Exemplo n.º 9
0
 private function setFile($file)
 {
     $errorCode = $file['error'];
     if ($errorCode === UPLOAD_ERR_OK) {
         $type = exif_imagetype($file['tmp_name']);
         if ($type) {
             $extension = image_type_to_extension($type);
             $src = 'img/' . date('YmdHis') . '.original' . $extension;
             if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {
                 if (file_exists($src)) {
                     unlink($src);
                 }
                 $result = move_uploaded_file($file['tmp_name'], $src);
                 if ($result) {
                     $this->src = $src;
                     $this->type = $type;
                     $this->extension = $extension;
                     $this->setDst();
                 } else {
                     $this->msg = 'Failed to save file';
                 }
             } else {
                 $this->msg = 'Please upload image with the following types: JPG, PNG, GIF';
             }
         } else {
             $this->msg = 'Please upload image file';
         }
     } else {
         $this->msg = $this->codeToMessage($errorCode);
     }
 }
Exemplo n.º 10
0
function upload_pro()
{
    global $con;
    if (isset($_POST['upload'])) {
        $title = secure_code($_POST['title']);
        $name = secure_code($_POST['name']);
        $price = $_POST['price'];
        $keywords = $_POST['keywords'];
        $cat = secure_code($_POST['cat']);
        $imag_name = $_FILES['img']['name'];
        $imag_temp = $_FILES['img']['tmp_name'];
        $store_images = 'product_images/';
        $discription = secure_code($_POST['des']);
        if ($title == '' || $name == '' || $price == '' || $keywords == '' || $cat == '' || $imag_name == '' || $discription == '') {
            echo "<div class='alert alert-danger'><strong>Error</strong>:   Please fill out the fields!</div>";
        } else {
            move_uploaded_file($imag_temp, $store_images . $imag_name);
            $upload_query = mysqli_query($con, "INSERT INTO products (title,name,price,keywords,category,image,discription) VALUES ('{$title}','{$name}','{$price}','{$keywords}','{$cat}','{$imag_name}','{$discription}')");
            if ($upload_query) {
                echo "<div class='alert alert-success'><strong>Congratulation</strong>  Product Successfully uploaded!</div>";
            } else {
                echo "<div class='alert alert-danger'>Sorry product not uplaod!</div>";
            }
        }
    }
}
Exemplo n.º 11
0
 public function executeUpload(sfWebRequest $request)
 {
     $language = LanguageTable::getInstance()->find($request->getParameter('id'));
     /* @var $language Language */
     if (!$language) {
         return $this->notFound();
     }
     if ($request->getPostParameter('csrf_token') == UtilCSRF::gen('language_upload', $language->getId())) {
         $this->ajax()->setAlertTarget('#upload', 'append');
         $file = $request->getFiles('file');
         if ($file && $file['tmp_name']) {
             $parser = new sfMessageSource_XLIFF();
             if ($parser->loadData($file['tmp_name'])) {
                 $dir = dirname($language->i18nFileWidget());
                 if (!file_exists($dir)) {
                     mkdir($dir);
                 }
                 move_uploaded_file($file['tmp_name'], $language->i18nFileWidget());
                 $language->i18nCacheWidgetClear();
                 return $this->ajax()->alert('Language file updated.', '', null, null, false, 'success')->render(true);
             }
             return $this->ajax()->alert('File invalid.', '', null, null, false, 'error')->render(true);
         }
         return $this->ajax()->alert('Upload failed.', '', null, null, false, 'error')->render(true);
     }
     return $this->notFound();
 }
 function insertarExcel($array)
 {
     $uploadOk = 1;
     $time = time();
     $fecha = date("Y-m-d", $time);
     $target_dir = "../documents/";
     $target_file = $target_dir . basename($_FILES["archivoExcel"]["name"]);
     move_uploaded_file($array["archivoExcel"]["tmp_name"], $target_file);
     set_include_path(get_include_path() . PATH_SEPARATOR . '../complements/PHPExcel-1.8/Classes/');
     $inputFileType = 'Excel2007';
     include 'PHPExcel/IOFactory.php';
     $inputFileName = $target_file;
     $objReader = PHPExcel_IOFactory::createReader($inputFileType);
     $objReader->setReadDataOnly(true);
     $objPHPExcel = $objReader->load($inputFileName);
     $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
     require_once "../db/conexiones.php";
     $consulta = new Conexion();
     foreach ($sheetData as $datos) {
         $nombreSinAcentos = sanear_string($datos['B']);
         $nombre = strtoupper(trim($nombreSinAcentos));
         $datosEmpleado = $consulta->Conectar("postgres", "SELECT * FROM userinfo WHERE UPPER(name)='" . $nombre . "'");
         if ($datosEmpleado) {
             $sqlInsert = $this->invoco->Conectar("postgres", "INSERT INTO horario_personal (user_id, banda_id, fecha) VALUES (" . $datosEmpleado[0]['userid'] . "," . $datos['C'] . ", '" . $fecha . "')");
         }
     }
     return "Se insertaron los datos Exitosamente!";
 }
Exemplo n.º 13
0
 private function createnewpicture()
 {
     $local = $this->path_two . $this->file['name'];
     move_uploaded_file($this->file['tmp_name'], $local);
     $filename = $this->file['tmp_name'] . "/" . $this->file['name'];
     $this->location = $this->path . "/" . $this->file['name'];
     switch ($this->file['type']) {
         case 'image/jpeg':
             $src = imagecreatefromjpeg($local);
             break;
         case 'image/png':
             $src = imagecreatefrompng($local);
             break;
         case 'image/gif':
             $src = imagecreatefromgif($local);
             break;
         default:
             break;
     }
     $sx = imagesx($src);
     $sy = imagesy($src);
     $new_image = imagecreatetruecolor($this->newwidth, $this->newheight);
     if (imagecopyresized($new_image, $src, 0, 0, 0, 0, $this->newwidth, $this->newheight, $sx, $sy)) {
         if (ImageJpeg($new_image, $this->location) || Imagegif($new_image, $this->location) || Imagepng($new_image, $this->location)) {
             //imagejpeg($this->location);
             return true;
         }
     } else {
         return false;
     }
 }
Exemplo n.º 14
0
function upload_originales($fichier, $destination, $ext)
{
    $sortie = array();
    // récupération du nom d'origine
    $nom_origine = $fichier['name'];
    // récupération de l'extension du fichier mise en minuscule et sans le .
    $extension_origine = substr(strtolower(strrchr($nom_origine, '.')), 1);
    // si l'extension ne se trouve pas (!) dans le tableau contenant les extensions autorisées
    if (!in_array($extension_origine, $ext)) {
        // envoi d'une erreur et arrêt de la fonction
        return "Erreur : Extension non autorisée";
    }
    // si l'extension est valide mais de type jpeg
    if ($extension_origine === "jpeg") {
        $extension_origine = "jpg";
    }
    // création du nom final  (appel de la fonction chaine_hasard, pour la chaine de caractère aléatoire)
    $nom_final = chaine_hasard(25);
    // on a besoin du nom final dans le tableau $sortie si la fonction réussit
    $sortie['poids'] = filesize($fichier['tmp_name']);
    $sortie['largeur'] = getimagesize($fichier['tmp_name'])[0];
    $sortie['hauteur'] = getimagesize($fichier['tmp_name'])[1];
    $sortie['nom'] = $nom_final;
    $sortie['extension'] = $extension_origine;
    // on déplace l'image du dossier temporaire vers le dossier 'originales'  avec le nom de fichier complet
    if (@move_uploaded_file($fichier['tmp_name'], $destination . $nom_final . "." . $extension_origine)) {
        return $sortie;
        // si erreur
    } else {
        return "Erreur lors de l'upload d'image";
    }
}
Exemplo n.º 15
0
 /**
  * Handles an uploaded file, stores it to the correct folder, adds an entry
  * to the database and returns a TBGFile object
  * 
  * @param string $thefile The request parameter the file was sent as
  * 
  * @return TBGFile The TBGFile object
  */
 public function handleUpload($key, $file_name = null, $file_dir = null)
 {
     $apc_exists = self::CanGetUploadStatus();
     if ($apc_exists && !array_key_exists($this->getParameter('APC_UPLOAD_PROGRESS'), $_SESSION['__upload_status'])) {
         $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')] = array('id' => $this->getParameter('APC_UPLOAD_PROGRESS'), 'finished' => false, 'percent' => 0, 'total' => 0, 'complete' => 0);
     }
     try {
         $thefile = $this->getUploadedFile($key);
         if ($thefile !== null) {
             if ($thefile['error'] == UPLOAD_ERR_OK) {
                 Logging::log('No upload errors');
                 if (is_uploaded_file($thefile['tmp_name'])) {
                     Logging::log('Uploaded file is uploaded');
                     $files_dir = $file_dir === null ? Caspar::getUploadPath() : $file_dir;
                     $new_filename = $file_name === null ? Caspar::getUser()->getID() . '_' . NOW . '_' . basename($thefile['name']) : $file_name;
                     Logging::log('Moving uploaded file to ' . $new_filename);
                     if (!move_uploaded_file($thefile['tmp_name'], $files_dir . $new_filename)) {
                         Logging::log('Moving uploaded file failed!');
                         throw new \Exception(Caspar::getI18n()->__('An error occured when saving the file'));
                     } else {
                         Logging::log('Upload complete and ok');
                         return true;
                     }
                 } else {
                     Logging::log('Uploaded file was not uploaded correctly');
                     throw new \Exception(Caspar::getI18n()->__('The file was not uploaded correctly'));
                 }
             } else {
                 Logging::log('Upload error: ' . $thefile['error']);
                 switch ($thefile['error']) {
                     case UPLOAD_ERR_INI_SIZE:
                     case UPLOAD_ERR_FORM_SIZE:
                         throw new \Exception(Caspar::getI18n()->__('You cannot upload files bigger than %max_size% MB', array('%max_size%' => Settings::getUploadsMaxSize())));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         throw new \Exception(Caspar::getI18n()->__('The upload was interrupted, please try again'));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         throw new \Exception(Caspar::getI18n()->__('No file was uploaded'));
                         break;
                     default:
                         throw new \Exception(Caspar::getI18n()->__('An unhandled error occured') . ': ' . $thefile['error']);
                         break;
                 }
             }
             Logging::log('Uploaded file could not be uploaded');
             throw new \Exception(Caspar::getI18n()->__('The file could not be uploaded'));
         }
         Logging::log('Could not find uploaded file' . $key);
         throw new \Exception(Caspar::getI18n()->__('Could not find the uploaded file. Please make sure that it is not too big.'));
     } catch (Exception $e) {
         Logging::log('Upload exception: ' . $e->getMessage());
         if ($apc_exists) {
             $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')]['error'] = $e->getMessage();
             $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')]['finished'] = true;
             $_SESSION['__upload_status'][$this->getParameter('APC_UPLOAD_PROGRESS')]['percent'] = 100;
         }
         throw $e;
     }
 }
Exemplo n.º 16
0
 /**
  * Save an uploaded file to a new location. If no filename is provided,
  * the original filename will be used, with a unique prefix added.
  *
  * This method should be used after validating the $_FILES array:
  *
  *     if ($array->check())
  *     {
  *         // Upload is valid, save it
  *         Upload::save($array['file']);
  *     }
  *
  * @param   array   $file       uploaded file data
  * @param   string  $filename   new filename
  * @param   string  $directory  new directory
  * @param   integer $chmod      chmod mask
  * @return  string  on success, full path to new file
  * @return  FALSE   on failure
  */
 public static function save(array $file, $filename = NULL, $directory = NULL, $chmod = 0644)
 {
     if (!isset($file['tmp_name']) or !is_uploaded_file($file['tmp_name'])) {
         // Ignore corrupted uploads
         return FALSE;
     }
     if ($filename === NULL) {
         // Use the default filename, with a timestamp pre-pended
         $filename = uniqid() . $file['name'];
     }
     // Remove spaces from the filename
     $filename = preg_replace('/\\s+/u', '_', $filename);
     if ($directory === NULL) {
         // Use the pre-configured upload directory
         $directory = Upload::$default_directory;
     }
     if (!is_dir($directory) or !is_writable(realpath($directory))) {
         throw new Exception('Directory :dir must be writable', [':dir' => Debug::path($directory)]);
     }
     // Make the filename into a complete path
     $filename = realpath($directory) . DIRECTORY_SEPARATOR . $filename;
     if (move_uploaded_file($file['tmp_name'], $filename)) {
         if ($chmod !== FALSE) {
             // Set permissions on filename
             chmod($filename, $chmod);
         }
         // Return new file path
         return $filename;
     }
     return FALSE;
 }
Exemplo n.º 17
0
 public function importExcelAction()
 {
     $request = $this->getRequest();
     $upfile = $request->files->get("filedata");
     $tmpPath = $upfile->getPathname();
     $filename = $upfile->getClientOriginalName();
     $fixedType = explode(".", strtolower($filename));
     $fixedType = $fixedType[count($fixedType) - 1];
     $newfile = $_SERVER['DOCUMENT_ROOT'] . "/upload/staff_" . rand(10000, 99999) . "." . $fixedType;
     $field_name = array();
     $field_value = array();
     $msg = "";
     $success = true;
     $recordcount = 0;
     $totalpage = 1;
     $page_record = 100;
     if (move_uploaded_file($tmpPath, $newfile)) {
         $re = $this->getExcelContent($newfile);
         $data = $re["data"];
         $recordcount = $re["recordcount"];
         $totalpage = ceil($recordcount / $page_record);
     } else {
         $this->get("logger")->err("上传文件错误!");
         $msg = "文件上传错误!";
         $success = false;
     }
     $result = array("success" => $success, "msg" => $msg, "DataSource" => $data, "filepath" => $newfile, "recordcount" => $recordcount, "totalpage" => $totalpage);
     $response = new Response("<script>parent.staff_import_callback(" . json_encode($result) . ")</script>");
     $response->headers->set('Content-Type', 'text/html');
     return $response;
 }
Exemplo n.º 18
0
 function _upLoadFiles($files)
 {
     $this->directorio = getcwd() . $this->carpeta;
     if (!is_array($files) || $files == "" || $files == null) {
         echo "No existe archivo que subir";
     } else {
         $nombre = basename($files['userfile']['name']);
         $tipoArchivo = basename($files['userfile']['type']);
         $tamano = basename($files['userfile']['size']);
         $messajes = false;
         if (!array_key_exists(array_search($tipoArchivo, $this->allowed), $this->allowed)) {
             echo "<p>La extensi&oacute;n " . $tipoArchivo . " o el tama&ntilde;o " . $tamano . " de los archivos no es correcta.";
         } else {
             if (!is_dir($this->directorio)) {
                 mkdir($this->directorio, 777, true);
             }
             chmod($this->carpeta, 777);
             $up = move_uploaded_file($files['userfile']['tmp_name'], $this->carpeta . $nombre);
             if ($up) {
                 $messajes = $nombre;
             }
             $files = null;
             return $messajes;
         }
     }
 }
Exemplo n.º 19
0
 /**
  * Parses the file
  *
  * @param array $file
  * @param bool $delete Delete file after parsing or not
  * @return string $file
  */
 function parseFile($file, $onlyHeader = false)
 {
     if ($onlyHeader) {
         $path = ASCMS_TEMP_PATH . "/";
         $newpath = $path . basename($file) . "." . time() . ".import";
         move_uploaded_file($file, $newpath);
         $file = $newpath;
         $data = $this->dataClass->parse($file, true, true, 1);
     } else {
         $data = $this->dataClass->parse($file, true, true);
     }
     if (!empty($data)) {
         if (isset($data['fieldnames'])) {
             // Set the fieldnames
             $this->fieldNames = $data['fieldnames'];
         } else {
             // Take the first data line as fieldnames
             foreach ($data['data'][0] as $value) {
                 $this->fieldNames[] = $value;
             }
         }
         if (isset($data['data'])) {
             $this->importedData = $data['data'];
         }
     }
     if (!$onlyHeader) {
         unlink($file);
     }
     return $file;
 }
Exemplo n.º 20
0
 public function co_star_edit()
 {
     if ($_POST['submit'] and $_POST['index'] != "") {
         $Stars = M('Co_stars');
         $index = $_POST['index'];
         $star = $Stars->where('photo_index=' . $index)->find();
         if ($_POST['title'] != "") {
             $data['photo_title'] = $_POST['title'];
         }
         $tmp_name = $_FILES['upfile']['tmp_name'];
         $file = $_FILES["upfile"];
         //上傳文件名稱
         //C('__PUBLIC__')爲 /Quanquan/Public
         move_uploaded_file($tmp_name, 'Public/WebResources/co_star/' . $file['name']);
         //將上傳文件移動到指定目錄待解壓
         if ($file['name']) {
             unlink($star['photo_url']);
             $data['photo_url'] = C('__PUBLIC__') . '/WebResources/co_star/' . $file['name'];
         }
         if ($Stars->where('photo_index=' . $index)->save($data)) {
             echo '修改成功';
         } else {
             echo $star['photo_url'];
         }
     } else {
         echo '未輸入數據';
     }
     $this->display();
 }
Exemplo n.º 21
0
 private static function upload_file($tmp, $file, $error)
 {
     if ($error == 0) {
         move_uploaded_file($tmp, $file);
         return self::file($file);
     } else {
         if ($error == 1 || $error == 2) {
             return self::error('The file you are attempting to upload is too large');
         } else {
             if ($error == 3) {
                 return self::error('The file you are attempting to upload is incomplete');
             } else {
                 if ($error == 4) {
                     if (self::$optional) {
                         return false;
                     } else {
                         return self::error('No file was uploaded');
                     }
                 } else {
                     return self::error('Unknown error');
                 }
             }
         }
     }
 }
Exemplo n.º 22
0
function simple_upload_csv_products_file()
{
    $upload_feedback = '';
    if (isset($_FILES['product_csv']) && $_FILES['product_csv']['size'] > 0) {
        $arr_file_type = wp_check_filetype(basename($_FILES['product_csv']['name']));
        $uploaded_file_type = $arr_file_type['ext'];
        $allowed_file_type = 'csv';
        if ($uploaded_file_type == $allowed_file_type) {
            $wp_uploads_dir = wp_upload_dir();
            $filepath = $wp_uploads_dir['basedir'] . '/simple-products.csv';
            if (move_uploaded_file($_FILES['product_csv']['tmp_name'], $filepath)) {
                simple_import_product_from_csv();
            } else {
                $upload_feedback = '<div class="al-box warning">' . __('There was a problem with your upload.', 'al-ecommerce-product-catalog') . '</div>';
            }
        } else {
            $upload_feedback = '<div class="al-box warning">' . __('Please upload only CSV files.', 'al-ecommerce-product-catalog') . '</div>';
        }
        echo $upload_feedback;
    } else {
        $url = sample_import_file_url();
        echo '<form method="POST" enctype="multipart/form-data"><input type="file" accept=".csv" name="product_csv" id="product_csv" /><input type="submit" class="button" value="' . __('Import Products', 'al-ecommerce-product-catalog') . '" /></form>';
        echo '<div class="al-box info"><p>' . __("The CSV fields should be in following order: Image URL, Product Name, Product Price, Product Categories, Short Description, Long Description.", "al-ecommerce-product-catalog") . '</p><p>' . __("The first row should contain the field names. Semicolon should be used as the CSV separator.", "al-ecommerce-product-catalog") . '</p><a href="' . $url . '" class="button-primary">' . __('Download CSV Template', 'al-ecommerce-product-catalog') . '</a></div>';
    }
}
Exemplo n.º 23
0
 public function upload()
 {
     if (is_dir($this->upload_file_dir) === false) {
         mkdir($this->upload_file_dir, 0777, true);
     }
     if (is_writable($this->upload_file_dir) === false) {
         if (!chmod($this->upload_file_dir, 0777)) {
             throw new PhxException("Could not write file into this directory: " . $this->upload_dir);
         }
     }
     for ($i = 0; $i < $this->file_count; $i++) {
         if (!$this->tmp_name[$i]) {
             continue;
         }
         if (is_null($this->ext_allowed)) {
             if (!@move_uploaded_file($this->tmp_name[$i], $this->upload_file_dir . $this->name[$i])) {
                 throw new UploadException($this->error[$i]);
             }
         } else {
             if (is_array($this->ext_allowed)) {
                 if (in_array($this->extension[$i], $this->ext_allowed)) {
                     if (!@move_uploaded_file($this->tmp_name[$i], $this->upload_file_dir . $this->name[$i])) {
                         throw new UploadException($this->error[$i]);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 24
0
function saveImage($mimeType, $tempName)
{
    global $dir;
    switch ($mimeType) {
        case "image/png":
            $type = "png";
            break;
        case "image/jpeg":
            $type = "jpg";
            break;
        case "image/jpg":
            $type = "jpg";
            break;
        case "image/gif":
            $type = "gif";
            break;
        case "video/mp4":
            $type = "mp4";
            break;
        case "video/webm":
            $type = "webm";
            break;
        default:
            die("error,e-418");
    }
    $hash = generateNewHash($type);
    if (move_uploaded_file($tempName, $dir . "/{$hash}.{$type}")) {
        die("success," . (RAW_IMAGE_LINK ? $dir . "/i/{$hash}.{$type}" : ($type == "png" ? "" : "") . "{$hash}" . "." . "{$type}"));
    }
    die("error,e-503");
}
Exemplo n.º 25
0
 /**
  * add method
  *
  * @return void
  */
 public function add()
 {
     // debug($_FILES);
     // debug($this->request->data);
     // exit;
     $file_path = "img/";
     $file_path = $file_path . basename($_FILES['UploadedFile']['name']);
     if (move_uploaded_file($_FILES['UploadedFile']['tmp_name'], $file_path)) {
         echo "success";
     } else {
         echo "fail";
     }
     $response = array();
     if ($this->request->is('post')) {
         $this->Company->create();
         $this->request->data['image_path'] = $file_path;
         $this->request->data['image_name'] = $_FILES['UploadedFile']['name'];
         if ($this->Company->save($this->request->data)) {
             //$this->Session->setFlash(__('The company has been saved.'));
             $response['success'] = true;
             return $this->_sendJson($response);
         } else {
             //$this->Session->setFlash(__('The company could not be saved. Please, try again.'));
         }
         exit;
     }
 }
Exemplo n.º 26
0
 function import_csv_to_sqlite()
 {
     $db = new MYDB();
     $csvfile_path = 'CSV/';
     $csv_file = $csvfile_path . basename($_FILES['csvdoc']['name']);
     echo '<pre>';
     if (move_uploaded_file($_FILES['csvdoc']['tmp_name'], $csv_file)) {
         $csvfile = fopen($csv_file, 'r');
         $theData = fgets($csvfile);
         $i = 0;
         $res = null;
         while (!feof($csvfile)) {
             $csvfile_data[] = fgets($csvfile, 1000);
             $csv_array = explode(",", $csvfile_data[$i]);
             $insert_csv = array();
             if (!empty($csv_array[0])) {
                 $olddate = str_replace('"', ' ', $csv_array[4]);
                 $Work_Date = strtotime(str_replace('/', '-', $olddate));
                 $names = explode(" ", $csv_array[0]);
                 $csv_FN['First_Name'] = str_replace('"', ' ', $names[0]);
                 $csv_MN['Middle_Name'] = str_replace('"', ' ', $names[1]);
                 $csv_FaN['Family_Name'] = str_replace('"', ' ', $names[2]);
                 $csv_PR['Payroll_Reference'] = $csv_array[1];
                 $csv_THW['Total_Hours_Worked'] = $csv_array[2];
                 $csv_TP['Total_Pay'] = $csv_array[3];
                 $csv_WD['Work_Date'] = $Work_Date;
                 $que = "INSERT INTO record (First_Name,Family_Name,Middle_Name,Payroll_Reference,Total_Hours_Worked,Total_Pay,Work_Date ) VALUES\n\t\t\t\t\t\t\t\t\t             ('" . $csv_FN['First_Name'] . "',\n\t\t\t\t\t\t\t\t\t              '" . $csv_FaN['Family_Name'] . "',\n\t\t\t\t\t\t\t\t\t              '" . $csv_MN['Middle_Name'] . "',\n\t\t\t\t\t\t\t\t\t              " . $csv_PR['Payroll_Reference'] . ",\n\t\t\t\t\t\t\t\t\t              " . $csv_THW['Total_Hours_Worked'] . ",\n\t\t\t\t\t\t\t\t\t              " . $csv_TP['Total_Pay'] . ",\n\t\t\t\t\t\t\t\t\t              " . $csv_WD['Work_Date'] . "\n\t\t\t\t\t\t\t\t\t              )";
                 $res = $db->exec($que);
                 $i++;
             }
         }
         fclose($csvfile);
         $db->close();
     }
 }
Exemplo n.º 27
0
 function saveAs($filename, $directory, $field, $overwrite, $mode = 0766)
 {
     if ($this->isPosted) {
         if ($this->HTTP_POST_FILES[$field]['size'] < $this->maxupload_size && $this->HTTP_POST_FILES[$field]['size'] > 0) {
             $noerrors = true;
             $tempName = $this->HTTP_POST_FILES[$field]['tmp_name'];
             $all = $directory . $filename;
             if (file_exists($all)) {
                 if ($overwrite) {
                     @unlink($all) || ($noerrors = false);
                     $this->errors = upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé.");
                     @move_uploaded_file($tempName, $all) || ($noerrors = false);
                     $this->errors .= upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé.");
                     @chmod($all, $mode);
                 }
             } else {
                 @move_uploaded_file($tempName, $all) || ($noerrors = false);
                 $this->errors = upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé.");
                 @chmod($all, $mode);
             }
             return $noerrors;
         } elseif ($this->HTTP_POST_FILES[$field]['size'] > $this->maxupload_size) {
             $this->errors = upload_translate("La taille de ce fichier excède la taille maximum autorisée") . " => " . number_format($this->maxupload_size / 1024, 2) . " Kbs";
             return false;
         } elseif ($this->HTTP_POST_FILES[$field]['size'] == 0) {
             $this->errors = upload_translate("Erreur de téléchargement du fichier - fichier non sauvegardé.");
             return false;
         }
     }
 }
/**
 * Comprueba si se ha cargado alguna imagen en el formulario guardándola en caso afirmativo en el servidor
 * y devolviendo la ruta de donde está almacenada y en caso negativo, devuelve una ruta con la imagen establecida
 * por defecto (la llamada imagen X).
 *
 * @param object $imagen -> Objeto de tipo $_FILES, que se espera ser una imagen
 * @param string $codigo -> Código del producto de la imagen en cuestión
 * @param bool $crear_producto -> false: si no es un nuevo producto - true: En caso de ser un producto nuevo
 */
function cargarImagen($imagen, $codigo, $crear_producto = false)
{
    // Si la imagen no se ha subido y...
    if ($imagen["imagen"]["name"] == "") {
        if ($crear_producto) {
            // ... en caso de ser un producto nuevo, le añado una ruta por defecto a la imagen X.
            $img = "../imagenes/image_placeholder.png";
        } else {
            return false;
        }
    } else {
        if (preg_match("/\\w+[.](jpg|png)\$/", $imagen['imagen']['name'])) {
            $temporal = $imagen['imagen']['tmp_name'];
            // Todas mis imágenes de muebles quiero que empiecen por '_ID', seguido de su código, un '-' y el nombre de la imagen.
            $img = "../imagenes/_ID" . $codigo . "-" . $imagen['imagen']['name'];
            if (move_uploaded_file($temporal, $img)) {
                // En caso de que se haya subido la imagen correctamente:
                echo Html::p("Y la imagen nueva se ha guardado con éxito en {$img}.");
            } else {
                // Sino se ha subido la imagen correctamente al servidor
                $img = "../imagenes/image_placeholder.png";
                echo Html::p("Pero la imagen NO se ha cargado con éxito, por lo que se utilizará la imagen X por defecto en {$img}.", "error");
            }
        } else {
            // En caso de no ser un archivo de extensión .jpg o .png
            $img = "../imagenes/image_placeholder.png";
            echo Html::p("Pero la imagen NO es de formato .jpg o .png, por lo que se utilizará una imagen vacía por defecto.", "error");
            echo Html::p("Asegúrate de modificar la imagen de este producto a una válida.", "error");
        }
    }
    return $img;
}
Exemplo n.º 29
0
 /**
  * Save the file to the specified path
  * @return boolean TRUE on success
  */
 function save($path)
 {
     if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
         return false;
     }
     return true;
 }
 function new_pic()
 {
     $inpId = $this->input->post('inpId');
     $inpVal = $this->input->post('inpValue');
     $cid = $this->session->userdata['profile_data'][0]['custID'];
     $filepath = $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
     $name = $this->session->userdata['profile_data'][0]['custID'] . '_' . $_FILES['profile_pic']['name'];
     $size = $_FILES['profile_pic']['size'];
     $photo_type = $_FILES['profile_pic']['type'];
     $tmp = $_FILES['profile_pic']['tmp_name'];
     $upload_image = $filepath . basename($_FILES['profile_pic']['name']);
     $thumbnail = $filepath . 'small_' . $name;
     $actual = $filepath . $name;
     $newwidth = "200";
     $newheight = "200";
     if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $upload_image)) {
         exec('convert ' . $upload_image . ' -resize ' . $newwidth . 'x' . $newheight . '^ ' . $thumbnail);
         rename($upload_image, $actual);
         /*   unlink("uploads/".$this->session->userdata['profile_data'][0]['photo']);
               unlink("uploads/small_".$this->session->userdata['profile_data'][0]['photo']);
               $data=array(
               'photo' => $name
               );
              $this->session->set_userdata("profile_data[0]['photo']",$name); */
         echo "uploaded" . $_SERVER['DOCUMENT_ROOT'];
     } else {
         echo "not_uploaded";
     }
     $sql_11 = "UPDATE `personaldata` SET `PerdataProfPict`='{$name}' WHERE  `custID`='{$cid}'";
     $this->db->query($sql_11);
     $sql_22 = "UPDATE `personalphoto` SET `photo`='{$name}' WHERE `custID`='{$cid}'";
     $this->db->query($sql_22);
     $this->update_joomla('avatar', $name);
     echo $this->db->affected_rows();
 }