How to count total numbers of images inside our folders and subfolders?
I put this in my view. Well, as MVC way, this may look sucks to be in view. I know how to put this into models, but don't know how to call it with controllers and views
<?php
$img = count(glob("./assets/images/*.*"));
$about = count(glob("./assets/images/aboutus/*.*"));
$blog1 = count(glob("./assets/images/blog/*.*"));
$mason = count(glob("./assets/images/blog/masonary/*.*"));
$tl = count(glob("./assets/images/blog/timeline/*.*"));
$blog2 = count(glob("./assets/images/blogdetails/*.*"));
$gallery = count(glob("./assets/images/gallery/*.*"));
$home = count(glob("./assets/images/home/*.*"));
$home2 = count(glob("./assets/images/home/slider/*.*"));
$ico = count(glob("./assets/images/ico/*.*"));
$lb = count(glob("./assets/images/lightbox/*.*"));
$keg = count(glob("./assets/images/kegiatan/*.*"));
$port1 = count(glob("./assets/images/portfolio/*.*"));
$port2 = count(glob("./assets/images/portfolio-details/*.*"));
$leader = count(glob("./assets/images/leaders/*.*"));
$srv = count(glob("./assets/images/services/*.*"));
$usr = count(glob("./assets/images/users/*.*"));
$count = $img+$about+$blog1+$mason+$tl+$blog2+$gallery+$home+$home2+$ico+$lb+$keg+$port1+$port2+$leader+$srv+$usr;
?>
Output:
<div class="col-sm-3 text-center wow bounceIn" data-wow-duration="1000ms" data-wow-delay="300ms">
<h1 class="timer bold" data-to="<?= $count;?>" data-speed="3000" data-from="0"></h1>
<h3>Total Images</h3>
</div>
Is there a way to make this simple?
Please take a look at
https://stackoverflow.com/a/10895775/7089527
You could do it like this using the [RecursiveDirectoryIterator][1]
<?php
function scan_dir($path){
$ite=new RecursiveDirectoryIterator($path);
$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
$filesize=$cur->getSize();
$bytestotal+=$filesize;
$nbfiles++;
$files[] = $filename;
}
$bytestotal=number_format($bytestotal);
return array('total_files'=>$nbfiles,
'total_size'=>$bytestotal,'files'=>$files);
}
$files = scan_dir('./');
echo "Total: {$files['total_files']} files, {$files['total_size']} >bytes\n";
//Total: 1195 files, 357,374,878 bytes
?>
[1]: http://php.net/manual/en/class.recursivedirectoryiterator.php
Hope it helps
Format to call a method in a model from a controller.
Model file:
application/models/Photo_shoot_model.php
class Photo_shoot_model extends CI_Model {
public function image_count() {
$img = count(glob("./assets/images/*.*"));
$about = count(glob("./assets/images/aboutus/*.*"));
$blog1 = count(glob("./assets/images/blog/*.*"));
$mason = count(glob("./assets/images/blog/masonary/*.*"));
$tl = count(glob("./assets/images/blog/timeline/*.*"));
$blog2 = count(glob("./assets/images/blogdetails/*.*"));
$gallery = count(glob("./assets/images/gallery/*.*"));
$home = count(glob("./assets/images/home/*.*"));
$home2 = count(glob("./assets/images/home/slider/*.*"));
$ico = count(glob("./assets/images/ico/*.*"));
$lb = count(glob("./assets/images/lightbox/*.*"));
$keg = count(glob("./assets/images/kegiatan/*.*"));
$port1 = count(glob("./assets/images/portfolio/*.*"));
$port2 = count(glob("./assets/images/portfolio-details/*.*"));
$leader = count(glob("./assets/images/leaders/*.*"));
$srv = count(glob("./assets/images/services/*.*"));
$usr = count(glob("./assets/images/users/*.*"));
$count = $img+$about+$blog1+$mason+$tl+$blog2+$gallery+$home+$home2+$ico+$lb+$keg+$port1+$port2+$leader+$srv+$usr;
return $count;
}
}
In controller:
public function index() {
// load model
$this->load->model('photo_shoot_model');
// call method
$howManyImages = $this->photo_shoot_model->image_count()
}
All about models: https://codeigniter.com/user_guide/general/models.html
But really, I'd use the RecursiveDirectoryIterator mentioned by #MayurVirkar.
Related
I am trying to save multiple images but I get the error show in the image at the bottom of the post.
I have tried doing a request of the name, but I get another error, I have a one to many relationship between property and images, I am trying to save many images of a property.
If I am receiving the image, if I make a dd before the creation I receive the image.
store method
public function store(Request $request)
{
/*--from this session you start to save the properties with all their attributes --*/
$properti = new Propertie;
$detail = new Detail;
$detail->antiquity = $request->antiquity;
$detail->furnished = $request->furnished;
$detail->floor = $request->floor;
$detail->save();
$properti->details_id = $detail->id;
$properti->name = $request->name;
$properti->price = $request->price;
$properti->description = $request->description;
$properti->departaments_id = $request->departaments;
$properti->municipalities_id = $request->municipalities;
$properti->property_type_id = $request->type_property;
$properti->offer_type_id = $request->type;
$properti->details_id = $detail->id;
$properti->lat = $request->lat;
$properti->lng = $request->lng;
$properti->address = $request->address;
if (isset($request->property_id)) {
$property_type = $request->property_id;
} else {
$property_type = null;
}
$properti->save();
$image->name = $request->name;
foreach($request->file('images') as $image ){
$name = $image->getClientOriginalName();
$image->move('image',$name);
}
$properti->images()->create(['name' => $name ]);
$piso_id = $properti->id;
$space = new Space;
$space->property_id = $piso_id;
$space->bedrooms = $request->bedrooms;
$space->bathrooms = $request->bathrooms;
$space->parking = $request->parking;
$space->area = $request->area;
$space->save();
$properti->spaces_id = $space->id;
foreach ($request->input('characteristic') as $characteristic) {
$charc = new Characteristic;
$charc->property_id = $piso_id;
$charc->characteristic = $characteristic;
$charc->save();
}
Session::flash('message', 'Se ha registrado su propiedad De forma exitosa');
return redirect()->action('PropertyController#index',compact('name'));
// return view('properties.index',compact('properties'));
}
File input
<div class="custom-file">
<input required type="file" class="form-control" name="images" placeholder="Imagenes" multiple>
</div>
Looks like this error happens only if there are no images attached. You should attach the image while looping over the request data:
foreach ($request->file('images') as $image) {
$name = $image->getClientOriginalName();
$image->move('image', $name);
// v- TO HERE -v
$properti->images()->create(['name' => $name ]);
}
// MOVE THIS: $properti->images()->create(['name' => $name ]);
as i see, you are calling a variable $name defined inside a foreach loop which mean it's not defined outside the loop, and that's what the error said.
I am trying to use a geoplugin (that code works) but I may wish to use the output in multiple locations. Because of this I've taken the code and added it to the header.php file and called the variable within my theme/inc/partials/header-contact.php. But the value is not displaying:
header-contact.php
<div class="head-contact">
<?php $details = get_field('options_company_details', 'options');
global $telephoneNumber; global $telephoneLink;?>
<span class="phone"><span class="phone-mob"><i class="fa fa-phone"></i></span><span class="tnumber"></span><?php echo $telephoneNumber;?></span>
<p class="tagline"><?php echo $details['options_tagline'];?></p>
</div>
header.php
<?php include_once(get_stylesheet_directory_uri().'/inc/geolocation.php');?>
var_dump in header-contact.php
NULL
var_dump in header.php
NULL
geolocation.php
function getUserIP() {
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP)){$ip = $client;}
elseif(filter_var($forward, FILTER_VALIDATE_IP)){$ip = $forward; }
else { $ip = $remote; } return $ip;
} $user_ip = getUserIP();
$details = get_field('options_company_details', 'options');
$telephoneNumber = $details['options_telephone'];
$getGeoArray = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$user_ip.''));
if(in_array($getGeoArray['geoplugin_city'], $lincolnshire)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $rutland)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $northamptonshire)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $norfolk)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $cambridgeshire)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $buckinghamshire)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $bedfordshire)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $hertfordshire)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $essex)){$telephoneNumber = 'NUMBER';}
elseif(in_array($getGeoArray['geoplugin_city'], $leicestershire)){$telephoneNumber = $details['options_telephone'];}
$telephoneLink = str_replace(' ', '', $telephoneNumber);
I've removed the variables used in the in_array() just to save question length.
var_dump in geolaction.php
NUMBER
I ended up using $_SESSION[] not quite sure if this is the best way to do this but it works so I am happy:
$_SESSION['phonenumber'] = $telephoneNumber;
$_SESSION['phonenumberLink'] = $telephoneLink;
echo $_SESSION['phonenumber'];
echo $_SESSION['phonenumberLink'];
This is untested but this may work if called with wp_head or init. This might make the global keyword work in the template parts.
// functions.php
// load at wp_head
add_action('wp_head', function() {
include_once(get_stylesheet_directory_uri().'/inc/geolocation.php');
});
// or
add_action('init', function() {
include_once(get_stylesheet_directory_uri().'/inc/geolocation.php');
});
Then you don't need to include it in your header file or have to use sessions.
I have a little project, where i use codeigniter, jquery and bootstrap.
I have "Startsite" where the user have to say:
Option 1: Edit project
Option 2: Create project
I think it is useful to show my Controller as first:
In the construct method i load all models, in the index i load data to all dropdowns in my "startsite", in saveProject i save my created project and the method i have a issue is editProject. Look here:
class projekt extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('html');
$this->load->helper('url');
$this->load->helper('form');
$this->load->model('projektklassen_model');
$this->load->model('kundengruppen_model');
$this->load->model('produktgruppen_model');
$this->load->model('ablehnungsgrund_model');
$this->load->model('absatzregion_model');
$this->load->model('anfragetyp_model');
$this->load->model('businessunit_model');
$this->load->model('endkundeOEM_model');
$this->load->model('lieferanten_model');
$this->load->model('prozentverteilungEOP_model');
$this->load->model('prozentverteilungSOP_model');
$this->load->model('realisierungsstatus_model');
$this->load->model('gsmbereich_model');
$this->load->model('firma_model');
$this->load->model('projekt_model');
}
public function index()
{
$data['projektklassen'] = $this->projektklassen_model->getProjektklassen();
$data['kundengruppen'] = $this->kundengruppen_model->getKundengruppen();
$data['produktgruppen'] = $this->produktgruppen_model->getProduktgruppen();
$data['ablehnungsgruende'] = $this->ablehnungsgrund_model->getAblehnungsgruende();
$data['absatzregionen'] = $this->absatzregion_model->getAbsatzregionen();
$data['anfragetypen'] = $this->anfragetyp_model->getAnfragetypen();
$data['businessunits'] = $this->businessunit_model->getBusinessunits();
$data['endkundenOEM'] = $this->endkundeOEM_model->getEndkundenOEM();
$data['lieferanten'] = $this->lieferanten_model->getLieferanten();
$data['prozentverteilungenEOP'] = $this->prozentverteilungEOP_model->getProzentverteilungenEOP();
$data['prozentverteilungenSOP'] = $this->prozentverteilungSOP_model->getProzentverteilungenSOP();
$data['realisierungsstati'] = $this->realisierungsstatus_model->getRealisierungsstatus();
$data['gsmbereiche'] = $this->gsmbereich_model->getGSMBereiche();
$data['firmen'] = $this->firma_model->getFirmen();
$data['projekte'] = $this->projekt_model->getProjekte();
$data['preFormVisible'] = true;
$this->load->view('project2', $data);
}
function saveProjekt(){
if($this->input->post('btGenerate')){
$pdm = $this->projekt_model->getPDM();
$this->projekt_model->addprojekt($pdm);
}
redirect('projekt');
}
function editProjekt(){
if($this->input->post('btladeProjekt')){
$data['proDetails'] = $this->projekt_model->editprojekt();
$data['preFormVisible'] = false;
$this->load->view('project2', $data);
}
redirect('projekt');
} }
What should happend?
The user choose on the "startsite" to edit an project. He select a project in a dropdown and click an button.
Here the form from the startsite:
<?php echo form_open('projekt/editProjekt', array('name' => 'preform')); ?>
<div class="col-sm-6 col-md-6 col-lg-6">
<label for='projekt'>Projekt</label>
<?php echo form_dropdown('projekt', $projekte, '', 'class="form-control" id="projekt"'); ?>
</div>
<div class="col-sm-6 col-md-4 col-lg-3">
<button type="submit" id="btladeProjekt" name="btladeProjekt" value="btladeProjekt" class="btn btn-primary headbutton"><i class="glyphicon glyphicon-pencil"></i> Projekt bearbeiten </button>
</div>
<?php echo form_close(); ?>
Now the controller method editProject calls a method in the model. I show you:
function editprojekt() {
$serverName = "de-sal-v-sql011";
$connectionInfo = array( "Database"=>"NB_Roll_Plan", "UID"=>"s-global_it-bit002", "PWD"=>"\$Ev1danzA\$");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$projektID = $this->input->post('projekt');
$data = array();
$tsql = "SELECT ProjektID, Projektname, KDGR, Kundenname, ProduktgruppeID, Projektklasse, MABVertrieb, GSMBereich, Ansprechpartner_kunde,ProjektanfrageNR_kunde,
Anfragedatum, Abgabedatum_angebot, PDM, übergeordnetePDM, Kommentar, Projektrisiken from Projekt WHERE ProjektID = ? ORDER BY Projektname ASC";
$var = array($projektID);
$query = sqlsrv_query($conn, $tsql, $var);
if($query != false){
while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
$data['ProjektID'] = $row['ProjektID'];
$data['Projektname'] = $row['Projektname'];
$data['KDGR'] = $row['KDGR'];
$data['Kundenname'] = $row['Kundenname'];
$data['ProduktgruppeID'] = $row['ProduktgruppeID'];
$data['Projektklasse'] = $row['Projektklasse'];
$data['MABVertrieb'] = $row['MABVertrieb'];
$data['GSMBereich'] = $row['GSMBereich'];
$data['Ansprechpartner_kunde'] = $row['Ansprechpartner_kunde'];
$data['ProjektanfrageNR_kunde'] = $row['ProjektanfrageNR_kunde'];
$data['Anfragedatum'] = $row['Anfragedatum'];
$data['Abgabedatum_angebot'] = $row['Abgabedatum_angebot'];
$data['PDM'] = $row['PDM'];
$data['übergeordnetePDM'] = $row['übergeordnetePDM'];
$data['Kommentar'] = $row['Kommentar'];
$data['Projektrisiken'] = $row['Projektrisiken'];
}
sqlsrv_free_stmt($query);
}else{
die( print_r( sqlsrv_errors(), true));
}
return $data;
}
Now i want to display the returned data in the view, but when i try this nothing happens.
<?php
if(isset($proDetails)){
echo "test";
echo "<input type='text' class='form-control' id='proname' name='proname' value='".$proDetails->ProjektID."'/>";
}else{
echo "<input type='text' class='form-control' id='proname' name='proname'>";
}
?>
What did i miss? Thx in advance
Alright I think I have understand what is you required #JamesnxD. You can load the all the drop down in a view and the edit form in another view do like this
$this->load->view('front/dropdown');
$this->load->view('front/editform',$data);
$this->load->view('front/front_footer');
some change your model function and add a param.
function editprojekt($proID) {
$projektID = $proID
}
and change your index method
public function index($proID = '') {
if($proID) {
$data['proDetails'] = $this->projekt_model->editprojekt($proID);
} else {
$data['proDetails'] = false;
}
}
Finally when you edit content you call projekt/index/12 (12 = projektID) in browser url
you know that you can use array to load helper, model and library
$this->load->helper(array('html', 'url', 'form'));
$this->load->model(array('projektklassen_model', 'kundengruppen_model', 'produktgruppen_model', 'ablehnungsgrund_model','absatzregion_model','anfragetyp_model','businessunit_model','endkundeOEM_model','lieferanten_model','prozentverteilungEOP_model','prozentverteilungSOP_model','realisierungsstatus_model','gsmbereich_model','firma_model','projekt_model'));
Assuming I try to save the following data and the Songs model's name attribute has a Phalcon\Mvc\Model\Validator\PresenceOf validator set on it
// Get an existing artist
$artist = Artists::findFirst('name = "Shinichi Osawa"');
// Create an album
$album = new Albums();
$album->name = 'The One';
$album->artist = $artist;
$songs = array();
// Create a first song
$songs[0] = new Songs();
$songs[0]->name = 'Star Guitar';
$songs[0]->duration = '5:54';
// Create a second song
$songs[1] = new Songs();
$songs[1]->name = '';
$songs[1]->duration = '4:29';
// Assign the songs array
$album->songs = $songs;
// Save the album + its songs
if (!$album->save()) {
foreach ($album->getMessages() as $message) {
$message->getModel(); // this returns null since model is new
}
}
I will get an error message saying that 'name' is required.
Question: is there a built in way of getting the related model on which the error occurred (in this case $songs[1]), or at least the alias/index of the error model (in this case songs/1)?
Didn't find a built-in solution but came up with this.
Base model
public function beforeValidation()
{
$session = $this->getService('session');
if (!$session->has('model:validation')) {
$validation = $indexes = [];
} else {
$modelName = get_called_class();
$validation = $session->get('model:validation');
if (!isset($validation[$modelName])) {
$validation[$modelName] = 0;
$indexes = $session->get('model:validation:relationIndex');
$indexes[] = $modelName;
} else {
$validation[$modelName]++;
// reset child indexes
$indexes = $session->get('model:validation:relationIndex');
$modelIndex = array_search($modelName, $indexes);
for ($i = $modelIndex + 1; $i < count($indexes); $i++) {
$modelName = $indexes[$i];
unset($validation[$modelName]);
unset($indexes[$i]);
}
$indexes = array_values($indexes);
}
}
$session->set('model:validation:relationIndex', $indexes);
$session->set('model:validation', $validation);
}
Controller
$session = $this->getDI()->get('session');
$session->remove('model:validation');
$session->remove('model:validation:relationIndex');
if (!$this->save()) {
var_dump($session->get('model:validation:relationIndex'));
var_dump($session->get('model:validation'));
}
ok so i have a php file that includes code for do a sql insert
myfile.php
include($somewhere.'/addleads.php');
addleads.php
require_once(MAIN_CLASS_PATH."common/class.Common.php");
require_once(MAIN_CLASS_PATH."modules/Leads/class.Leads.php");
$objcommon = new common();
$objLeads = new Leads();
$Errormsg = $objLeads->AddLBCleads($_REQUEST);
class.Leads.php
class Leads extends Common{
function Leads(){
$this->Common();
$this->Leadstype = "Leadstype";
$this->Leads = "Leads";
}
function AddLBCleads($objArray){
global $_REQUEST,$objSmarty,$global_config;
$objLeads = new Leads();
$objInsertArray['txtP_Ident'] = $objArray['selProperty'];
$objInsertArray['txtFirstName'] = $objArray['txtfirstname'];
$objInsertArray['txtLastName'] = $objArray['txtlastname'];
$objInsertArray['txtEmail'] = $objArray['txtEmail'];
$objInsertArray['txtPhone'] = $objArray['txtPhone'];
$objInsertArray['txtTypeId'] = $objArray['selleadtype'];
$objInsertArray['txtComments'] = $objArray['txtcomments'];
$StrEnterdate = date('Y-m-d H:i:s');
$objInsertArray['txtMoveDate'] = $StrMoveDate;
$objInsertArray['txtEntereddate'] = $StrEnterdate;
$current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
How do i get $current_id from myfile.php, when i try to access it is unavailable
Just below this line:
class Leads extends Common{
Add:
public $current_id = null; // create a public accessible variable
And instead of:
$current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
Use:
$this->current_id = $this->AddInfoToDB($objInsertArray,"txt",$this->LBCPrimary_leads);
Now you can get it like:
$objLeads = new Leads();
echo $objLeads->current_id;