I am new to slim php framework, I want to upload an image and put the file name in the database via POST, can some one kindly give me some example code.
Here's the router:
$app->post('/', 'uploadFile');
this will point to the function below:
function uploadFile () {
if (!isset($_FILES['uploads'])) {
echo "No files uploaded!!";
return;
}
$imgs = array();
$files = $_FILES['uploads'];
$cnt = count($files['name']);
for($i = 0 ; $i < $cnt ; $i++) {
if ($files['error'][$i] === 0) {
$name = uniqid('img-'.date('Ymd').'-');
if (move_uploaded_file($files['tmp_name'][$i], 'uploads/' . $name) === true) {
$imgs[] = array('url' => '/uploads/' . $name, 'name' => $files['name'][$i]);
}
}
}
$imageCount = count($imgs);
if ($imageCount == 0) {
echo 'No files uploaded!! <p>Try again';
return;
}
$plural = ($imageCount == 1) ? '' : 's';
foreach($imgs as $img) {
printf('%s <img src="%s" width="50" height="50" /><br/>', $img['name'], $img['url']);
}
}
If anyone have better answer, please be welcome to alter mine.
The creator of Slim has made a library to handle file uploading through Slim: https://github.com/brandonsavage/Upload
Related
I need to check if the excel file is currently open using PHPSpreadsheet.
I thought of a solution by handling this line $writer->save(file_name) into if else condition but still doesn't work.
if($writer->save(file_name){
//file is open
}else{
//file is not open
}
What else can I do to solve my problem?
I need to check if the excel file is currently open using PHPSpreadsheet.
Checking if a file is open isn't really useful, since the open/closed state could change at any time, or the failure could be caused by other filesystem problems.
What you need to do is handle the failure during file operations as:
try {
$writer->save(file_name);
}
catch (Exception $e) {
echo 'Unable to save file. Please close any other applications(s) that are using it: [", $e->getMessage(), "]\n";
}
Answered by #terry-carmen will be Incorrect in following situation:
It will still show "Resource Unavailable" error If file is exists but being used by some application and $writer->save() will try to unlink() the file.
To Overcome this situations I edited the save() function as following:
(Located at: "\vendor\phpoffice\phpspreadsheet\src\PhpSpreadsheet\Writer\Xlsx.php")
public function save($pFilename)
{
if ($this->spreadSheet !== null) {
// garbage collect
$this->spreadSheet->garbageCollect();
// If $pFilename is php://output or php://stdout, make it a temporary file...
$originalFilename = $pFilename;
if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
$pFilename = #tempnam(File::sysGetTempDir(), 'phpxltmp');
if ($pFilename == '') {
$pFilename = $originalFilename;
}
}
$saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
// Create string lookup table
$this->stringTable = [];
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
}
// Create styles dictionaries
$this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet));
$this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet));
$this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet));
$this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet));
$this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet));
$this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet));
// Create drawing dictionary
$this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet));
$zip = new ZipArchive();
if (file_exists($pFilename)) {
// Added by muhammad.begawala#gmail.com
// '#' will stop displaying "Resource Unavailable" error because of file is open some where.
// 'unlink($pFilename) !== true' will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if (#unlink($pFilename) !== true) {
throw new WriterException('Could not delete file: ' . $pFilename . ' Please close all applications that are using it.');
}
}
// Try opening the ZIP file
if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) {
if ($zip->open($pFilename, ZipArchive::CREATE) !== true) {
throw new WriterException('Could not open ' . $pFilename . ' for writing.');
}
}
// Add [Content_Types].xml to ZIP file
$zip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts));
//if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
if ($this->spreadSheet->hasMacros()) {
$macrosCode = $this->spreadSheet->getMacrosCode();
if ($macrosCode !== null) {
// we have the code ?
$zip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin
if ($this->spreadSheet->hasMacrosCertificate()) {
//signed macros ?
// Yes : add the certificate file and the related rels file
$zip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate());
$zip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet));
}
}
}
//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
if ($this->spreadSheet->hasRibbon()) {
$tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
$zip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data'));
if ($this->spreadSheet->hasRibbonBinObjects()) {
$tmpRootPath = dirname($tmpRibbonTarget) . '/';
$ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
foreach ($ribbonBinObjects as $aPath => $aContent) {
$zip->addFromString($tmpRootPath . $aPath, $aContent);
}
//the rels for files
$zip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet));
}
}
// Add relationships to ZIP file
$zip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet));
$zip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet));
// Add document properties to ZIP file
$zip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet));
$zip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet));
$customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet);
if ($customPropertiesPart !== null) {
$zip->addFromString('docProps/custom.xml', $customPropertiesPart);
}
// Add theme to ZIP file
$zip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet));
// Add string table to ZIP file
$zip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable));
// Add styles to ZIP file
$zip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet));
// Add workbook to ZIP file
$zip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas));
$chartCount = 0;
// Add worksheets
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
$zip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts));
if ($this->includeCharts) {
$charts = $this->spreadSheet->getSheet($i)->getChartCollection();
if (count($charts) > 0) {
foreach ($charts as $chart) {
$zip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas));
++$chartCount;
}
}
}
}
$chartRef1 = 0;
// Add worksheet relationships (drawings, ...)
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
// Add relationships
$zip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts));
// Add unparsedLoadedData
$sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
$unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) {
$zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
}
}
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) {
$zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
}
}
$drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
$drawingCount = count($drawings);
if ($this->includeCharts) {
$chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
}
// Add drawing and image relationship parts
if (($drawingCount > 0) || ($chartCount > 0)) {
// Drawing relationships
$zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
// Drawings
$zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
} elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) {
// Drawings
$zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
}
// Add comment relationship parts
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
// VML Comments
$zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
// Comments
$zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
}
// Add unparsed relationship parts
if (isset($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'])) {
foreach ($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'] as $vmlDrawing) {
$zip->addFromString($vmlDrawing['filePath'], $vmlDrawing['content']);
}
}
// Add header/footer relationship parts
if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
// VML Drawings
$zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
// VML Drawing relationships
$zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
// Media
foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
$zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
}
}
}
// Add media
for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
$imageContents = null;
$imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
if (strpos($imagePath, 'zip://') !== false) {
$imagePath = substr($imagePath, 6);
$imagePathSplitted = explode('#', $imagePath);
$imageZip = new ZipArchive();
$imageZip->open($imagePathSplitted[0]);
$imageContents = $imageZip->getFromName($imagePathSplitted[1]);
$imageZip->close();
unset($imageZip);
} else {
$imageContents = file_get_contents($imagePath);
}
$zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
} elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
ob_start();
call_user_func(
$this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
$this->getDrawingHashTable()->getByIndex($i)->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
$zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
}
}
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
// Close file
if ( #$zip->close() === false ) { // updated by muhammad.begawala#gmail.com
throw new WriterException("Could not close zip file $pFilename.");
}
// If a temporary file was used, copy it to the correct file stream
if ($originalFilename != $pFilename) {
if (copy($pFilename, $originalFilename) === false) {
throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename.");
}
#unlink($pFilename);
}
return true;
// Return True to make sure that file is created successfully with no ExceptionsAdded by muhammad.begawala#gmail.com
} else {
throw new WriterException('PhpSpreadsheet object unassigned.');
}
}
Major Changes:
1) Handling "Resource Unavailable" error by unlink() as Exception using try catch so that It doesn't show error when file is being used by some applications when we tries to delete it using unlink.
if (file_exists($pFilename)) {
// Added by muhammad.begawala#gmail.com
// '#' will stop displaying "Resource Unavailable" error because of file is open some where.
// 'unlink($pFilename) !== true' will check if file is deleted successfully.
// Throwing exception so that we can handle error easily instead of displaying to users.
if (#unlink($pFilename) !== true) {
throw new WriterException('Could not delete file: ' . $pFilename . ' Please close all applications that are using it.');
}
}
2) $writer->save('hello world.xlsx') will return TRUE if file is successfully created else throw Exception.
Usage:
try {
$writer->save('hello world.xlsx');
echo 'File Created';
}
catch (Exception $e) {
echo $e->getMessage(); // Will print Exception thrown by save()
}
I read similar query on google, there I read about checking whether file is writable and then setting permissions using chmod() function, but I tried that too, it didnt work. I want to store the image path in database, and move the image to the uploads folder. The path of the image would be as :
C:/xampp/htdocs/konnect1/uploads/Hydrangeas1.jpg
On using chmod(), I get Warning as "Message: chmod(): No such file or directory".
please help as what should I change now.
Controller page->admin_c.php
Posting the function, where image upload code is written.
public function create_event1()
{
if($this->input->post('counter') || !$this->input->post('counter'))
{
$count = $this->input->post('counter');
$c = $count;
//echo $c;
if($this->input->is_ajax_request())
{
$vardata = $this->input->post('vardata');
echo $vardata;
}
$g = $_POST['results'];
$configUpload['upload_path'] = '/konnect1/uploads/'; #the folder placed in the root of project
$configUpload['allowed_types'] = 'gif|jpg|png|bmp|jpeg'; #allowed types description
$configUpload['max_size'] = '0'; #max size
$configUpload['max_width'] = '0'; #max width
$configUpload['max_height'] = '0'; #max height
$configUpload['encrypt_name'] = false; #encrypt name of the uploaded file
$this->load->library('upload', $configUpload);
$this->upload->initialize($configUpload); #init the upload class
if( chmod($configUpload['upload_path'], 0755) )
{
// more code
chmod($configUpload['upload_path'], 0777);
}
else
echo "Couldn't do it.";
if ( ! is_writable($this->upload->do_upload('picture')))
{
$uploadedDetails = $this->upload->display_errors('upload_not_writable');
echo $uploadedDetails;
}
else if(!$this->upload->do_upload('picture'))
{
$uploadedDetails = $this->upload->display_errors();
}
else
{
$uploadedDetails = $this->upload->data();
//print_r($uploadedDetails);die;
$etype = $this->input->post('etype');
$ecategory = $this->input->post('ecategory');
$ename = $this->input->post('ename');
$edat_time = $this->input->post('edat_time');
$evenue = $this->input->post('evenue');
$sch_name0 = $this->input->post("sch_name0");
$speaker_name0 = $this->input->post("speaker_name0");
$sch_stime0 = $this->input->post("sch_stime0");
$sch_etime0 = $this->input->post("sch_etime0");
$sch_venue0 = $this->input->post("sch_venue0");
$sch_name = $this->input->post("sch_name");
$speaker_name = $this->input->post("speaker_name");
$sch_stime = $this->input->post("sch_stime");
$sch_etime = $this->input->post("sch_etime");
$sch_venue = $this->input->post("sch_venue");
$agenda_desc = $this->input->post("agenda_desc");
if ((!empty($etype)) || (!empty($uploadedDetails)) || (!empty($ecategory)) || (!empty($ename)) || (!empty($edat_time)) || (!empty($evenue)) || (!empty($sch_name0)) || (!empty($speaker_name0)) || (!empty($sch_stime0)) || (!empty($sch_etime0)) || (!empty($sch_venue0)) || (!empty($sch_name)) || (!empty($speaker_name)) || (!empty($sch_stime)) || (!empty($sch_etime)) || (!empty($sch_venue)) || (!empty($agenda_desc)))
{
$res1 = $this->admin_m->insert($uploadedDetails);
if($res1 == true)
{
$res2 = $this->admin_m->insert1($c);
$lastid = $this->db->insert_id();
$data['h'] = $this->admin_m->select($lastid);
//return the data in view
$this->load->view('admin/event', $data);
}
else
echo "error";
}
}
}
}
Model Page->admin_m.php
<?php
class Admin_m extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
public function insert($image_data = array())
{
//$data1 = explode('/',$imge_data);
//$data2 = in_array("konnect1", $data1);
$data = array(
'ename' => $this->input->post('ename'),
'eimg' => $this->input->post('eimg'),
'edat_time' => $this->input->post('edat_time'),
'evenue' => $this->input->post('evenue'),
'sch_name' => $this->input->post('sch_name0'),
'speaker_name' => $this->input->post('speaker_name0'),
'sch_stime' => $this->input->post('sch_stime0'),
'sch_etime' => $this->input->post('sch_etime0'),
'sch_venue' => $this->input->post('sch_venue0'),
'etype' => $this->input->post('etype'),
'ecategory' => $this->input->post('ecategory'),
'agenda_desc' => $this->input->post('agenda_desc'),
'eimg' => $image_data['full_path']
);
$result = $this->db->insert('event',$data);
if($result == true)
return true;
else
echo "Error in first row";
}
public function insert1($c)
{
for($i=0; $i<=$c; $i++)
{
$sql = array(
'sch_name' => $this->input->post('sch_name')[$i],
'speaker_name' => $this->input->post('speaker_name')[$i],
'sch_stime' => $this->input->post('sch_stime')[$i],
'sch_etime' => $this->input->post('sch_etime')[$i],
'sch_venue' => $this->input->post('sch_venue')[$i]
);
//$sql = "INSERT INTO event(sch_name,speaker_name,sch_stime,sch_etime,sch_venue) VALUES(($this->input->post('sch_name')[$i]),($this->input->post('speaker_name')[$i]),($this->input->post('sch_stime')[$i]),($this->input->post('sch_etime')[$i]),($this->input->post('sch_venue')[$i]))";
$res = $this->db->insert('event',$sql);
}
if ($res == true)
return true;
else
echo "Error from first row";
}
public function select($lastid)
{
//data is retrive from this query
$query = $this->db->get('event');
return $query;
}
}
?>
for reference, attached model code also.
According to the error message, it seems PHP is unable to find the directory.
Please use PHP function is_dir() to first validate if PHP can recognize the path as a folder.
Once it returns true, you can proceed to use it.
Also in your upload path, you have started with / which would mean that your project is placed in root of OS and I don't think that location would be correct.
From the terminal cd to your project directory and run command pwd and get the current working directory and then use the proper upload path after taking into consideration the location of the project.
My codes multiple image upload and update mysql db but one problem if id=1 It's working multiple image uploading and update.else It's not working and white page.
tables 2
musteri_soru and musteri_cevap
is updating musteri_cevap in colon resim
controller code:
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
if($_FILES){
$dizin= "../upload/form_cevap/";
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++){
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
Models code :
function duzenle($no,$data)
{
$this->db->update($this->tablo,$data, array('no' => $no));
}
function cevapDuzenle($n,$dat)
{
$data = array('resim' => $dat);
$this->db->update($this->ctablo,$data, array('soru_no' => $n));
}
My Tables
enter link description here
To be honest, I'm not quite sure how your upload was working as the $_FILES array shouldn't be nesting the uploads in the way you've shown above.
I'm not saying this will definitely work but it should do:
function duzenle($no)
{
//I would possible look at using the Form_validation Library here
if (empty($_POST)) {
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no, $arr1);
if (!empty($_FILES)) {
$dizin = "../upload/form_cevap/";
foreach ($_FILES as $name => $file) {
//If there is an error there isn't any reason to try and upload this file
if ($file['error'] !== 0) {
continue;
}
$name = $file['name'];
$isim = md5(uniqid(rand()));
move_uploaded_file($file['tmp_name'], "./$dizin/$isim$name");
$arr['resim'] = $dizin . $isim . $name;
//Not sure what's going on here so I haven't changed it
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach ($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else {
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik' => $veri->baslik,
'veri' => $veri,
'cevap' => $veri2
);
$this->bc->addCrumb($veri->baslik, 'form_duzenle/duzenle/' . $veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle', $data);
}
}
Hope this helps!
Check your for loop,
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++)
for loop condition should be $i < $dosya_sayi as array index always starts from 0.
So correct for loop is
for($i=0;$i<$dosya_sayi;$i++)
I solved the problem.Duzenle codes on change the bottom code.
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
$cevaplar = $this->form_duzenle_model->cevapListe($no)->result_array();
if($_FILES){
$dizin= "../upload/form_cevap/";
foreach($cevaplar AS $cevap){
$i = $cevap['no'];
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
$this->form_duzenle_model->cevapDuzenle($i,$arr['resim']);
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
Trying to prevent a file from being duplicated in a users directory. This is what I have come up with,
$data = $connection->getMedia($fileid);
/**
* The test begins
*/
$dir = 'media/download/'.$username;
$files1 = scandir($dir);
foreach ($files1 as $i => $file) {
if (md5($file) == md5($data)) {
//statement
echo "Duplicate entry detected.";
}
else {
file_put_contents($finalPath, $data);
}
This, however, gives me an endless loop and I cant see what it is doing. So, can anyone give me a better idea.?
EDIT: the full code:
foreach ($accounts as $username => $password) {
$connection= new Connection($username,$password);
$fileList= $connection->getFiles();
echo '<br><p>Last available files for '.$username.': <br>';
if (!file_exists('media/download/'.$username)) {
mkdir('media/download/'.$username, 0777, true);
}
for ($i=0;$i<7;$i++)
{
$fileID= $fileList[$i]->id;
$data = $connection->getMedia($fileID);
if (!strlen($data) < 1 ) {
$recipient = $fileList[$i]->recipient;
$finalPath = 'media/download/'.$username.'/to'.$recipient.'_id'.$fildID.rand(0,200).'.jpg';
file_put_contents($finalPath, $data);
echo " <img src='".$finalPath."' height='100' width='100'> ";
}
}
}
I'm trying to rename each file before uploading to Amazon S3.
I am trying to use this exact method of which was answered by #Silvertiger: PHP - upload and overwrite a file (or upload and rename it)?
If exists, rename to a random name although somehow it doesn't work.
Here is the upload post Parameter from the Amazon S3 Class:
public static function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600,
$maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
{
// Create policy object
$policy = new stdClass;
$policy->expiration = gmdate('Y-m-d\TH:i:s\Z', (time() + $lifetime));
$policy->conditions = array();
$obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj);
$obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj);
$obj = new stdClass; // 200 for non-redirect uploads
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$obj->success_action_status = (string)$successRedirect;
else // URL
$obj->success_action_redirect = $successRedirect;
array_push($policy->conditions, $obj);
if ($acl !== self::ACL_PUBLIC_READ)
array_push($policy->conditions, array('eq', '$acl', $acl));
array_push($policy->conditions, array('starts-with', '$key', $uriPrefix));
if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', ''));
foreach (array_keys($headers) as $headerKey)
array_push($policy->conditions, array('starts-with', '$'.$headerKey, ''));
foreach ($amzHeaders as $headerKey => $headerVal)
{
$obj = new stdClass;
$obj->{$headerKey} = (string)$headerVal;
array_push($policy->conditions, $obj);
}
array_push($policy->conditions, array('content-length-range', 0, $maxFileSize));
$policy = base64_encode(str_replace('\/', '/', json_encode($policy)));
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';
$params->acl = $acl;
$params->policy = $policy; unset($policy);
$params->signature = self::__getHash($params->policy);
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$params->success_action_status = (string)$successRedirect;
else
$params->success_action_redirect = $successRedirect;
foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
return $params;
}
Here is #Silvertiger's method:
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
This is my upload form:
<form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
foreach ($params as $p => $v)
echo " <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
And this is the Input info:
public static function inputFile($file, $md5sum = true)
{
if (!file_exists($file) || !is_file($file) || !is_readable($file))
{
self::__triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
return false;
}
return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
(is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
}
You can do your renaming at this point in your code:
move_uploaded_file($tmp, $filelocation);
The $filelocation can be changed to whatever you want and the uploaded file will be renamed to that path.
Edit: The S3::getHttpUploadPostParams method always uses the file name from the upload to create the S3 resource. To change that you have to copy the method but change this line:
$params->key = $uriPrefix.'${filename}';
The '${filename} must be changed to a path of your choosing.
Replace this:
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.'${filename}';
with this:
function rand_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = self::$__accessKey;
$params->key = $uriPrefix.rand_string(5).'${filename}';
You can easily put this code.. 100 percent working.
<?php
$file=$_FILES['file']['name'];
$path ="upload/".$file;
$ext=pathinfo($path,PATHINFO_EXTENSION);
$name=pathinfo($path,PATHINFO_FILENAME);
if(file_exists($path))
{
echo "File alredy exists .So name is changed automatically & moved";
$path1="upload/";
$new_name=$path1.$name.rand(1,500).".".$ext;
move_uploaded_file($_FILES['file']['tmp_name'],$new_name);
}
else
{
echo"uploaded Sucessfully without any change";
move_uploaded_file($_FILES['file']['tmp_name'],$path);
}
?>