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'> ";
}
}
}
Related
I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);
Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>
I'm trying to export a list of contacts with a specified set of fields from in Codeigniter. PHP is exiting early and I can't figure out why. It exports 4,092 contacts then exits but the count of the array being exported is 140,699. PHP gives me no errors, and on my test server the export function works fine. Here's the code:
function admin_export()
{
set_time_limit(0);
if(!$this->ion_auth->in_group(array('admin')) && !$this->input->is_cli_request())
die();
$contacts = $this->contacts_model->get_contacts();
$export_fields = unserialize($this->contacts_model->get_contact_export_fields());
if(!file_exists($this->config->item('tmp_path')))
mkdir($this->config->item('tmp_path'));
if($export_fields == false)
{
echo json_encode(false);
}
else
{
$fh = fopen($this->config->item('tmp_path').'export.csv', 'w');
fputcsv($fh, $export_fields, ',');
foreach($contacts as $i => $contact)
{
$id = $contact['id'];
foreach($contact as $k => $v)
{
if(!in_array($k, $export_fields))
{
unset($contacts[$i][$k]);
}
}
if(in_array('role', $export_fields))
{
$contacts[$i]['role'] = '';
$roles = $this->contacts_model->get_contact_roles($id);
foreach($roles as $role)
{
$contacts[$i]['role'] .= $role['role'].';';
}
$contacts[$i]['role'] = rtrim($contacts[$i]['role'], ';');
}
if(in_array('role_id', $export_fields))
{
$contacts[$i]['role_id'] = '';
$role_ids = $this->contacts_model->get_contact_roles($id);
foreach($role_ids as $role_id)
{
$contacts[$i]['role_id'] .= $role_id['id'].';';
}
$contacts[$i]['role_id'] = rtrim($contacts[$i]['role_id'], ';');
}
fputcsv($fh, $contacts[$i], ',');
}
fclose($fh);
echo json_encode(true);
}
}
What about memory? It's possible that it is maxing out the allocated memory and stopping.
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);
}
}
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