I'm trying upload image but getting error, image is successfully uploading to folder /server/uploads/ but in console im getting error:
Notice: Undefined index: CKEditorFuncNum in
C:\xampp\A_websites\site.ru\public\dashboard\vendors\editor\uploader\upload.php
on line 55
window.parent.CKEDITOR.tools.callFunction(,
'http://site.ru/server/uploads/Screenshot_18.png', 'Screenshot_18.png
successfully uploaded: \n- Size: 8.85 KB');
How I can fix it?
Config.js
config.extraPlugins = 'uploadwidget,uploadimage,filebrowser';
config.filebrowserUploadUrl = '/dashboard/vendors/editor/uploader/upload.php'
;
Upload.php:
<?php
$upload_dir = array(
'img'=> '/server/uploads/',
);
$imgset = array(
// 'maxsize' => 2000,
// 'maxwidth' => 900,
// 'maxheight' => 800,
'minwidth' => 10,
'minheight' => 10,
'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'),
);
// If 0, will OVERWRITE the existing file
define('RENAME_F', 1);
$re = '';
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name']))); //get filename without extension
// get protocol and host name to send the absolute image path to CKEditor
$site = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'].'/';
$sepext = explode('.', strtolower($_FILES['upload']['name']));
$type = end($sepext); // gets extension
$upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
$upload_dir = trim($upload_dir, '/') .'/';
//checkings for image or audio
if(in_array($type, $imgset['type'])){
// list($width, $height) = getimagesize($_FILES['upload']['tmp_name']); // image width and height
if(isset($width) && isset($height)) {
if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
}
}
else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';
//set filename; if file exists, and RENAME_F is 1, set "img_name_I"
// $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
function setFName($p, $fn, $ex, $i){
if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
else return $fn .$ex;
}
$f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
$uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name; // full file path
// If no errors, upload the image, else, output the errors
if($re == '') {
// print_r($_FILES);exit;
if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
$CKEditorFuncNum = $_GET['CKEditorFuncNum'];
$url = $site. $upload_dir . $f_name;
$msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
$re = in_array($type, $imgset['type']) ? "window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')" //for img
: 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent(); dialog.hide();';
}
else $re = 'alert("Unable to upload the file")';
}
else $re = 'alert("'. $re .'")';
}
#header('Content-type: text/html; charset=utf-8');
echo '<script>'. $re .';</script>';
Please add config.filebrowserUploadMethod = "form"; in config.js which resides inside ckeditor file
config.filebrowserUploadUrl = '/dashboard/vendors/editor/uploader/upload.php'
Just add CKEditorFuncNum parameter on above config.
config.filebrowserUploadUrl = '/dashboard/vendors/editor/uploader/upload.php?CKEditorFuncNum=1'
Related
On my codeigniter pagination links I am using bootstrap 3 +
When I am on the very first link it hides the << which goes back to start when I click on it.
1 2 >>
Question How can I make the codeigniter pagination all ways display << >> I have tried Always show Previous & Next links using CodeIgniter Pagination Class but is for CI2
$config['base_url'] = base_url('forum/?fid=' . $this->input->get('fid') . $url);
$config['total_rows'] = $this->thread_model->total_threads($this->input->get('fid'));
$config['per_page'] = $this->config->item('config_limit_admin');
$config['page_query_string'] = TRUE;
$config["full_tag_open"] = '<ul class="pagination">';
$config["full_tag_close"] = '</ul>';
$config["first_link"] = "«";
$config["first_tag_open"] = "<li>";
$config["first_tag_close"] = "</li>";
$config["last_link"] = "»";
$config["last_tag_open"] = "<li>";
$config["last_tag_close"] = "</li>";
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '<li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '<li>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
I have just override the create_links() of core library in slightly different way to achieve this. So All you have to do is create a file name My_Pagination.php inapplication/libraries and put this code there (Code copied from create_link() method from core library Pagination.php)
My_Pagination.php file (Codeigniter 3.1.0)
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Pagination extends CI_Pagination {
public function create_links() {
if ($this->total_rows == 0 OR $this->per_page == 0) {
return '';
}
// Calculate the total number of pages
$num_pages = (int) ceil($this->total_rows / $this->per_page);
if ($num_pages === 1) {
return '';
}
// Check the user defined number of links.
$this->num_links = (int) $this->num_links;
if ($this->num_links < 0) {
show_error('Your number of links must be a non-negative number.');
}
// Keep any existing query string items.
// Note: Has nothing to do with any other query string option.
if ($this->reuse_query_string === TRUE) {
$get = $this->CI->input->get();
// Unset the controll, method, old-school routing options
unset($get['c'], $get['m'], $get[$this->query_string_segment]);
} else {
$get = array();
}
// Put together our base and first URLs.
// Note: DO NOT append to the properties as that would break successive calls
$base_url = trim($this->base_url);
$first_url = $this->first_url;
$query_string = '';
$query_string_sep = (strpos($base_url, '?') === FALSE) ? '?' : '&';
// Are we using query strings?
if ($this->page_query_string === TRUE) {
// If a custom first_url hasn't been specified, we'll create one from
// the base_url, but without the page item.
if ($first_url === '') {
$first_url = $base_url;
// If we saved any GET items earlier, make sure they're appended.
if (!empty($get)) {
$first_url .= $query_string_sep . http_build_query($get);
}
}
// Add the page segment to the end of the query string, where the
// page number will be appended.
$base_url .= $query_string_sep . http_build_query(array_merge($get, array($this->query_string_segment => '')));
} else {
// Standard segment mode.
// Generate our saved query string to append later after the page number.
if (!empty($get)) {
$query_string = $query_string_sep . http_build_query($get);
$this->suffix .= $query_string;
}
// Does the base_url have the query string in it?
// If we're supposed to save it, remove it so we can append it later.
if ($this->reuse_query_string === TRUE && ($base_query_pos = strpos($base_url, '?')) !== FALSE) {
$base_url = substr($base_url, 0, $base_query_pos);
}
if ($first_url === '') {
$first_url = $base_url . $query_string;
}
$base_url = rtrim($base_url, '/') . '/';
}
// Determine the current page number.
$base_page = ($this->use_page_numbers) ? 1 : 0;
// Are we using query strings?
if ($this->page_query_string === TRUE) {
$this->cur_page = $this->CI->input->get($this->query_string_segment);
} elseif (empty($this->cur_page)) {
// Default to the last segment number if one hasn't been defined.
if ($this->uri_segment === 0) {
$this->uri_segment = count($this->CI->uri->segment_array());
}
$this->cur_page = $this->CI->uri->segment($this->uri_segment);
// Remove any specified prefix/suffix from the segment.
if ($this->prefix !== '' OR $this->suffix !== '') {
$this->cur_page = str_replace(array($this->prefix, $this->suffix), '', $this->cur_page);
}
} else {
$this->cur_page = (string) $this->cur_page;
}
// If something isn't quite right, back to the default base page.
if (!ctype_digit($this->cur_page) OR ( $this->use_page_numbers && (int) $this->cur_page === 0)) {
$this->cur_page = $base_page;
} else {
// Make sure we're using integers for comparisons later.
$this->cur_page = (int) $this->cur_page;
}
// Is the page number beyond the result range?
// If so, we show the last page.
if ($this->use_page_numbers) {
if ($this->cur_page > $num_pages) {
$this->cur_page = $num_pages;
}
} elseif ($this->cur_page > $this->total_rows) {
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
// If we're using offset instead of page numbers, convert it
// to a page number, so we can generate the surrounding number links.
if (!$this->use_page_numbers) {
$this->cur_page = (int) floor(($this->cur_page / $this->per_page) + 1);
}
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with.
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// And here we go...
$output = '';
// Render the "First" link.
if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + !$this->num_links)) {
// Take the general parameters, and squeeze this pagination-page attr in for JS frameworks.
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
$output .= $this->first_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('start') . '>'
. $this->first_link . '</a>' . $this->first_tag_close;
}
// Render the "Previous" link.
//if ($this->prev_link !== FALSE && $this->cur_page !== 1)
if ($this->prev_link !== FALSE) {//REMOVED $this->cur_page !== 1
$i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, ($this->cur_page - 1));
if ($i === $base_page || $this->cur_page == 1) {//ADDED $this->cur_page == 1
// First page
$output .= $this->prev_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('prev') . '>'
. $this->prev_link . '</a>' . $this->prev_tag_close;
} else {
$append = $this->prefix . $i . $this->suffix;
$output .= $this->prev_tag_open . '<a href="' . $base_url . $append . '"' . $attributes . $this->_attr_rel('prev') . '>'
. $this->prev_link . '</a>' . $this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE) {
// Write the digit links
for ($loop = $start - 1; $loop <= $end; $loop++) {
$i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop);
if ($i >= $base_page) {
if ($this->cur_page === $loop) {
// Current page
$output .= $this->cur_tag_open . $loop . $this->cur_tag_close;
} elseif ($i === $base_page) {
// First page
$output .= $this->num_tag_open . '<a href="' . $first_url . '"' . $attributes . $this->_attr_rel('start') . '>'
. $loop . '</a>' . $this->num_tag_close;
} else {
$append = $this->prefix . $i . $this->suffix;
$output .= $this->num_tag_open . '<a href="' . $base_url . $append . '"' . $attributes . '>'
. $loop . '</a>' . $this->num_tag_close;
}
}
}
}
// Render the "next" link
//if ($this->next_link !== FALSE && $this->cur_page < $num_pages)
if ($this->next_link !== FALSE) {//REMOVED $this->cur_page < $num_pages
$i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page;
if($this->cur_page == $num_pages){//WHEN LAST LINK
$i = $num_pages;
}
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1);
$output .= $this->next_tag_open . '<a href="' . $base_url . $this->prefix . $i . $this->suffix . '"' . $attributes
. $this->_attr_rel('next') . '>' . $this->next_link . '</a>' . $this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + !$this->num_links) < $num_pages) {
$i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages);
$output .= $this->last_tag_open . '<a href="' . $base_url . $this->prefix . $i . $this->suffix . '"' . $attributes . '>'
. $this->last_link . '</a>' . $this->last_tag_close;
}
$output = preg_replace('#([^:"])//+#', '\\1/', $output);
return $this->full_tag_open . $output . $this->full_tag_close;
}
}
Just removed 2 condition
$this->cur_page !== 1 (This is below // Render the "Previous" link COMMENT)
$this->cur_page < $num_pages (This is below // Render the "next" link COMMENT)
Added 2 condition
if ($i === $base_page){... changed this as if ($i === $base_page || $this->cur_page == 1) {...
Added this inside if ($this->next_link !== FALSE) {... condition
if($this->cur_page == $num_pages){
$i = $num_pages;
}
None you have to do except putting this file in libraries directory and now your << and >> links will show always even you may change it in config as normal configuration
Well, you'll have to modify the create_links of the Pagination class. What I'd do it's extending the system/libraries/Pagination.php class with a MY_Pagination.php, so you override the behaviour and you can modify it accordingly to your preferences.
By the way, checking the class, I think you should look into lines 563 on:
// Render the "First" link.
if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1 + ! $this->num_links))
{
// Take the general parameters, and squeeze this pagination-page attr in for JS frameworks.
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
$output .= $this->first_tag_open.'<a href="'.$first_url.'"'.$attributes.$this->_attr_rel('start').'>'
.$this->first_link.'</a>'.$this->first_tag_close;
}
You'll have to take care of the if condition to always render the link.
The product id is given to which multiple images need to be added in magento.
$count = 0;
$imgArray = array($fpath.'configurable.png');
foreach ($imgArray as $image){
$imgUrl = _save_image( $image,$objectManager );
if ($count == 0){
$configProduct->addImageToMediaGallery( $imgUrl , $mediaAttribute, true, false );
}else {
$configProduct->addImageToMediaGallery( $imgUrl , null, true, false );
}
$count++;
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load product object
$mediaAttribute = array ('thumbnail','small_image','image');
$mediaDir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList')->getPath('media');// Im Magento 2
$mediaDir = Mage::getBaseDir('media');// In Magento 1
//Case 1: When image files are alredy in your server
$fpath = 'product/images/';// path to your file
$count = 0;
$imgArray = array('image1.png','image2.png','image3.png','image4.png');
foreach ($imgArray as $image){
$imgUrl = _save_image( $fpath.$image,$objectManager,$mediaDir );// copies the file from your local storage to your-magento-root-path/pub/media
if ($count == 0){
$product->addImageToMediaGallery( $imgUrl , $mediaAttribute, true, false );
}else {
$product->addImageToMediaGallery( $imgUrl , null, true, false );
}
$count++;
}
function _save_image($img,$objectManager,$mediaDir) {
$imageFilename = basename($img);
$image_type = substr(strrchr($imageFilename,"."),1); //find the image extension
$filename = md5($img . strtotime('now')).'.'.$image_type; //give a new name, you can modify as per your requirement
if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
else chmod($mediaDir, 0777);
$filepath = $mediaDir . '/'. $filename; //path for temp storage folder: pub/media
file_put_contents($filepath, file_get_contents(trim($img))); //store the image from external url to the temp storage folder
return $filepath;
}
//Case 2: When you have to browse images from a form. (Then save into your server and then )
if(!empty($imageFile)){
$count = 0;
if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
else chmod($mediaDir, 0777);
foreach($imageFile['name'] as $k2=>$v2){
if($imageFile['error'][$k2] == 0 && file_exists($imageFile['tmp_name'][$k2])){
$ext[$k2] = pathinfo($imageFile['name'][$k2], PATHINFO_EXTENSION);
$filename[$k2] = md5(strtotime('now')).'.'.$ext[$k2];
$filepath[$k2] = $mediaDir .'/'. $filename[$k2];
$bin_string[$k2] = file_get_contents($imageFile['tmp_name'][$k2]);
file_put_contents($filepath[$k2], $bin_string[$k2]);
if ($count == 0) :
$product[$k]->addImageToMediaGallery( $filepath[$k2] , $mediaAttribute, true, false );
else :
$product[$k]->addImageToMediaGallery( $filepath[$k2] , null, true, false );
endif;
$count++;
}
}
}
The following code works for me.
https://www.pearlbells.co.uk/programmatically-add-multiple-images-magento-2/
if(sizeof($imgs) > 1) {
/* Assign additional images to existing products */
$product = $_objectManager->create('Magento\Catalog\Model\Product')->load($newProdId);
$productRepository = $_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$productRepository->save($product);
for ( $i=1; $i<sizeof($imgs); $i++ ) {
echo 'Add Images :' . $prdbasepath.basename(trim($imgs[$i])) . PHP_EOL;
$image_directory = $prdbasepath.'data'.DS.basename(trim($imgs[$i]));
if (file_exists($image_directory) && getimagesize($image_directory)) {
echo 'File exists'.PHP_EOL;
$product->addImageToMediaGallery($image_directory, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();
}
}
}
How to generate URL in my current code, so I can pass the values to my directions function.
This is my code for displaying markers on map for each company:
$n = 0;
foreach ($firm as $f) {
if ($f->active == 1 && in_array($f->skd_n, $dejavnost) && $f->lat != 0) {
$lat_f = $f->lat;
$lng_f = $f->lng;
$distance = (($this->distance($lat, $lng, $lat_f, $lng_f)) * 1000);
if ($distance <= $rad && $n <= 199) {
$marker = array();
$marker['position'] = "$lat_f, $lng_f";
if ($f->phone != 0) {
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '<br/>' .
'<div class="phone_icon"></div>' .
"$f->phone" . '<br/>' .
//generate URL with 4 arguments
'DIRECTION' .
'</div><br/>';
}else{
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '</div>';
}
$marker['animation'] = 'DROP';
$marker['zIndex'] = '0';
$marker['icon'] = '../images/pin-map-red.png';
$this->googlemaps->add_marker($marker);
$n++;
}
}
}
I want to add anchor to next function, where question marks are and use variables (coordinates) as arguments:
function direction($lat, $lng, $lat_f, $lng_f){
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'event_location';
$config['placesAutocompleteBoundsMap'] = TRUE;
$config['zoom'] = 'auto';
$config['center'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = "$lat, $lng";
$config['directionsEnd'] = "$lat_f, $lng_f";
$config['directionsDivID'] = 'directions';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('header', $data);
$this->load->view('domov_view', $data);
$this->load->view('footer');
}
How can I use values in second function (direction) from first?
Thank you!
You could pass the arguments in url and fetch them inside your direction method via $_GET method
Example:
You could generate link like that
DIRECTION
So your function would look like this:
$n = 0;
foreach ($firm as $f) {
if ($f->active == 1 && in_array($f->skd_n, $dejavnost) && $f->lat != 0) {
$lat_f = $f->lat;
$lng_f = $f->lng;
$distance = (($this->distance($lat, $lng, $lat_f, $lng_f)) * 1000);
if ($distance <= $rad && $n <= 199) {
$marker = array();
$marker['position'] = "$lat_f, $lng_f";
if ($f->phone != 0) {
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '<br/>' .
'<div class="phone_icon"></div>' .
"$f->phone" . '<br/>' .
'DIRECTION' .
'</div><br/>';
}else{
$marker['infowindow_content'] = '<div class="info_window">' . "$f->title" . '<br/>' .
'<div class="pin_icon"></div>' .
"$f->address" . '</div>';
}
$marker['animation'] = 'DROP';
$marker['zIndex'] = '0';
$marker['icon'] = '../images/pin-map-red.png';
$this->googlemaps->add_marker($marker);
$n++;
}
}
}
And fetch them this way in directions function
function direction(){
$lat = $this->input->get('lat');
$lng = $this->input->get('lng');
$lat_f = $this->input->get('lat_f');
$lng_f = $this->input->get('lng_f');
$config['places'] = TRUE;
$config['placesAutocompleteInputID'] = 'event_location';
$config['placesAutocompleteBoundsMap'] = TRUE;
$config['zoom'] = 'auto';
$config['center'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = "$lat, $lng";
$config['directionsEnd'] = "$lat_f, $lng_f";
$config['directionsDivID'] = 'directions';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('header', $data);
$this->load->view('domov_view', $data);
$this->load->view('footer');
}
P.S.: If you are sending langitude and longitude via url you will probably have problems with sending disallowed chars via url (dot(.)).
You can configure allowed url chars in config file
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_=+-'
You can extend url helper. Add function some:
create_url('controller/action', [
'getParam1' => 'value1',
'getParam2' => 'value2',
'getParam3' => 'value3',
]);
And it generate http://base.url/controller/action?getParam1=value&getParam2=value2&getParam3=value3
or use
http://www.codeigniter.com/userguide2/libraries/uri.html
create link $this->uri->assoc_to_uri()
parse link $this->uri->uri_to_assoc()
i want ot change new product images prospective to original images.
when i am upload image for product , images are squazed so any help?
We modified the tep_image function to accept -1 which means it will only output a "height" or a "width" constraint but not both. You can modify this to your liking but you want to look at includes/functions/html_output.php for tep_image()
// The HTML image wrapper function
function tep_image($src, $alt = '', $width = '', $height = '', $parameters = '') {
if ( (empty($enter code heresrc) || ($src == DIR_WS_IMAGES)) && (IMAGE_REQUIRED == 'false') ) {
return false;
}
if($src=='images/')
$src='images/noimage.jpg';
// alt is added to the img tag even if it is null to prevent browsers from outputting
// the image filename as default
$image = '<img src="' . tep_output_string($src) . '" border="0" alt="' . tep_output_string($alt) . '"';
if (tep_not_null($alt)) {
$image .= ' title=" ' . tep_output_string($alt) . ' "';
}
if(((int)$height==-1) && ((int)$width)==-1){
$image .= '';
}elseif((!empty($width) && ((int)$height)==-1)){
$image .= ' width="' . tep_output_string($width) . '" ';
}elseif((!empty($height) && ((int)$width)==-1)){
$image .= ' height="' . tep_output_string($height) . '" ';
}else{
if ( (CONFIG_CALCULATE_IMAGE_SIZE == 'true') && (empty($width) || empty($height)) ) {
if ($image_size = #getimagesize($src)) {
if (empty($width) && tep_not_null($height)) {
$ratio = $height / $image_size[1];
$width = intval($image_size[0] * $ratio);
} elseif (tep_not_null($width) && empty($height)) {
$ratio = $width / $image_size[0];
$height = intval($image_size[1] * $ratio);
} elseif (empty($width) && empty($height)) {
$width = $image_size[0];
$height = $image_size[1];
}
} elseif (IMAGE_REQUIRED == 'false') {
return false;
}
}
if (tep_not_null($width) && tep_not_null($height)) {
$image .= ' wddidth="' . tep_output_string($width) . '" height="' . tep_output_string($height) . '"';
}
}
if (tep_not_null($parameters)) $image .= ' ' . $parameters;
$image .= '>';
return $image;
}
I followed this page, and the code is not working as it should in my project. I've tried to find other tutorial on how to execute what I need, however, it does not work as it should in my project either. Is anyone able to direct me to a tutorial that explains in a detailed fashion on how to use Captcha plug-in properly in CodeIgniter?
Controller:
<?php
class Prova extends Controller
{
function prova()
{
parent :: Controller();
$this -> load -> plugin( 'captcha' );
$this->load->library('validation');
$rules['user'] = "required";
$rules['captcha'] = "required|callback_captcha_check";
$this->validation->set_rules($rules);
$fields['user'] = 'Username';
$fields['captcha'] = 'codice';
$this->validation->set_fields($fields);
if ($this->validation->run() == FALSE)
{
$expiration = time()-300; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
$vals = array(
//'word' => 'Random word',
'img_path' => './tmp/captcha/',
'img_url' => base_url().'tmp/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '100',
'img_height' => '30',
'expiration' => '3600'
);
$cap = $this->captcha->create_captcha($vals);
//
$dati['image']= $cap['image'];
//mette nel db
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
$this->load->view('captcha',$data);
}else{
echo "Captcha can't be made";
}
return $cap ['image'];
}
function captcha_check()
{
// Then see if a captcha exists:
$exp=time()-600;
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($this->input->post('captcha'), $this->input->ip_address(), $exp);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$this->validation->set_message('_captcha_check', 'Codice di controllo non valido');
return FALSE;
}else{
return TRUE;
}
}
}
View:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?=$this->validation->error_string; ?>
<?=form_open('XXXXXXXXX type your controller'); ?>
<h5>Username</h5>
<?=$this->validation->user_error; ?>
<input type="text" name="user" value="<?php echo ($this->validation->user) ;?>" size="50" />
<br/>
<?=$image;?>
<br/>
<?=$this->validation->captcha_error; ?>
<input type="text" name="captcha" value="" />
<br/>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Captcha:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/*
Instructions:
Load the plugin using:
$this->load->plugin('captcha');
Once loaded you can generate a captcha like this:
$vals = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
echo $cap['image'];
NOTES:
The captcha function requires the GD image library.
Only the img_path and img_url are required.
If a "word" is not supplied, the function will generate a random
ASCII string. You might put together your own word library that
you can draw randomly from.
If you do not specify a path to a TRUE TYPE font, the native ugly GD
font will be used.
The "captcha" folder must be writable (666, or 777)
The "expiration" (in seconds) signifies how long an image will
remain in the captcha folder before it will be deleted. The default
is two hours.
RETURNED DATA
The create_captcha() function returns an associative array with this data:
[array]
(
'image' => IMAGE TAG
'time' => TIMESTAMP (in microtime)
'word' => CAPTCHA WORD
)
The "image" is the actual image tag:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
The "time" is the micro timestamp used as the image name without the file
extension. It will be a number like this: 1139612155.3422
The "word" is the word that appears in the captcha image, which if not
supplied to the function, will be a random string.
ADDING A DATABASE
In order for the captcha function to prevent someone from posting, you will need
to add the information returned from create_captcha() function to your database.
Then, when the data from the form is submitted by the user you will need to verify
that the data exists in the database and has not expired.
Here is a table prototype:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(16) default '0' NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY `captcha_id` (`captcha_id`),
KEY `word` (`word`)
)
Here is an example of usage with a DB.
On the page where the captcha will be shown you'll have something like this:
$this->load->plugin('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';
Then, on the page that accepts the submission you'll have something like this:
// First, delete old captchas
$expiration = time()-7200; // Two hour limit
$DB->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND date > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
*/
/**
|==========================================================
| Create Captcha
|==========================================================
|
*/
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
$defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! #is_dir($img_path))
{
return FALSE;
}
if ( ! is_really_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < 8; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 153, 102, 102);
$text_color = imagecolorallocate ($im, 204, 153, 153);
$grid_color = imagecolorallocate($im, 255, 182, 182);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
/* End of file captcha_pi.php */
/* Location: ./system/plugins/captcha_pi.php */
The whole tutorial is in the captcha_pi file. The captcha tutorial in the wiki works on a different script (a class).
try this, CodeIgniter Captcha User Guide