Yii not able to save Image files CFileUploaded - yii

I am not able to save the image uploaded from simple Form with this code
public function actionImage()
{
print_r($_FILES);
$dir = Yii::getPathOfAlias('application.uploads');
if(isset($_POST['img']))
{
$model = new FileUpload();
$model->attributes = $_POST['img'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->validate())
{
$model->image->saveAs($dir.'/'.$model->image->getName());
// redirect to success page
}
}
}

To Answer my own question instead of using above code I used this:
public function actionImage()
{
$dir = Yii::getPathOfAlias('application.uploads');
if (isset($_FILES['img']))
{
$image = CUploadedFile::getInstanceByName('img');
$image->saveAs($dir.'/'.$image->getName());
}
}

To Answer my own question instead of using above code I used this:
public function actionImage() {
$dir = Yii::getPathOfAlias('application.uploads');
if (isset($_FILES['img']))
{
$image = CUploadedFile::getInstanceByName('img');
$image->saveAs($dir.'/'.$image->getName());
} }

Related

cannot echo data in a file located in extension/bootstraps/widgets

I am using Yii 1.1 .I have a class file inside widgets folder named MyCommentsTbEditableSaver.
when i try to echo data with in that php file .it doesnot return any thing.
What is the reason behind this?
my code:`
public function insertRps()
{
//get params from request
$this->primaryKey = yii::app()->request->getParam('pk');
$this->attribute = yii::app()->request->getParam('name');
//$this->attribute = yii::app()->request->getParam('comments');
$this->value = yii::app()->request->getParam('value');
//checking params
if (empty($this->attribute)) {
throw new CException(Yii::t('MyCommentsTbEditableSaver.editable', 'Property "attribute" should be defined.'));
}
if (empty($this->primaryKey)) {
throw new CException(Yii::t('MyCommentsTbEditableSaver.editable', 'Property "primaryKey" should be defined.'));
}
$model=new ProjectComments();
$comments=Yii::app()->db->createCommand()
->select('count(project_id) as countProject')
->from('pm_project_comments')
->where("project_id = $this->primaryKey ")
->queryRow();
if($comments['countProject']==0)
{
$model->isNewRecord=TRUE;
$model->comments_rps=$this->value;
$model->project_id=$this->primaryKey;
//also set update details,added by bishal
$model->crtd_by=Yii::app()->user->id;
$model->crtd_dt = date('Y-m-d');
print_r($model);die;
$model->save();
}
}`

how rename image before upload in Yii framework

I have follow yii site to work with upload image, code here:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs('path/to/localFile');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
however how can I rename file by currentdate+filename.png and upload to path,also I need code for update and delete.
thankyou very much
I have resolve this problem:
public function currentDate(){
$date = date('m-d-Y-h-i-s', time());
return $date;
}
public function actionCreate(){
$model = new News();
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$uploadedFile = CUploadedFile::getInstance($model, 'images');
$fileName = "{$this->currentDate()}-{$uploadedFile}";
$model->images = $fileName;
if($model->save()){
$uploadedFile->saveAs("upload/".$fileName);
$this->redirect(array('news/index'));
}else{
$model = new News();
$this->render('create',
array('model' =>$model,
'result'=>'insert new fail !',
));
}
}else{
$this->render('create',
array(
'model'=>$model,
));
}
}
public function actionCreate()
{
$model=new News;
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$name = $_FILES['News']['name']['images'];
$filename = pathinfo($name, PATHINFO_FILENAME);
$ext = pathinfo($name, PATHINFO_EXTENSION);
$newName = date("m-d-Y-h-i-s", time())."-".$filename.'.'.$ext;
$model->images = CUploadedFile::getInstance($model,'images');
if($model->save())
$fullImgSource = Yii::getPathOfAlias('webroot').'/upload/'.$newName;
$model->images->saveAs($fullImgSource);
$model->images = $newName;
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array('model'=>$model,));
}
To rename the file after upload and update in DB, try this code.
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
if($model->save())
{
$imageName = #$_FILES["MenuItems"]["name"]["image"];
$uniqueName = (imageName . $model->id) . '.' . (end(explode('.', $imageName)));
$model->image=CUploadedFile::getInstance($model,'image');
$model->image->saveAs('path/to/localFile/'.$uniqueName);
$model->image = $uniqueName;
$model->save();
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
you can use this method that I had created later to upload file and change its name before upload it :
public static function createAttach($model, $imageAttrName) {
$model->$imageAttrName = CUploadedFile::getInstance($model, $imageAttrName);
$fecha = date('YmdHms');
if ($model->$imageAttrName) {
$attach_src = Yii::app()->basePath . '/../upload/' . $fecha.'.'.$model->$imageAttrName->getExtensionName(); //. '_' . $model->$imageAttrName;
$model->$imageAttrName->saveAs($attach_src);
$model->$imageAttrName = $fecha.'.'.$model->$imageAttrName->getExtensionName();// . '_' . $model->$imageAttrName;
}
}

yii cdbdatareader and readObject function

I am trying to construct an object from a stored procedure will yii.
http://www.yiiframework.com/doc/api/1.1/CDbDataReader
I am unsure how to use the function $dataReader->readObject('image', $image);
to construct an object- anyone any ideas if this is the correct way or if this is very slow way of constructing objects
function __construct($image) {
print "In BaseClass constructor\n";
}
public static function getImageFromAliasTitle($alias_title)
{
// $alias_title =Utils::checkEnteredData($alias_title);
$connection = Yii::app()->db;
$command = $connection->createCommand("CALL get_associated_image_detail(:in_image_alias_title, :in_image_visible, :in_image_approved, :in_album_visible, :in_album_approved)");
$command->bindParam(":in_image_alias_title",$alias_title,PDO::PARAM_STR);
$command->bindValue(":in_image_visible",'1',PDO::PARAM_STR);
$command->bindValue(":in_image_approved",'Yes',PDO::PARAM_STR);
$command->bindValue(":in_album_visible",'1',PDO::PARAM_STR);
$command->bindValue(":in_album_approved",'Yes',PDO::PARAM_STR);
try{
$dataReader = $command->query();
if($dataReader->count() >0)
{
$image = $dataReader->read();
}
$dataReader->readObject('image', $image);
// $image = $dataReader->read();
$dataReader->nextResult();
$album = $dataReader->readAll();
$dataReader->nextResult();
$tag = $dataReader->readAll();
$dataReader->nextResult();
$user_image = $dataReader->readAll();
$dataReader->close();
}
catch(Exception $e){
Yii::log('', CLogger::LEVEL_ERROR, 'Message Here...');
}
return $image;
}
What about this:
foreach($row as $dataReader->readAll()){
echo $row["image"];
}
if It does not help then try to print:
print_r($dataReader->readAll());

How do I pass SQL database query from the Model to the Controller and then the View on Code Igniter 2.0.3?

I was trying to pass SQL values from Model to Controller but the value couldn't be passed.
This the code in my model file:
class Has_alert extends CI_Model {
function __construct()
{
parent::__construct();
}
function __get_query() {
$sql = 'alerts_get_alerts';
$query = $this->db->query($sql);
$row = $query->first_row();
$header_data['hasAlert'] = $row->active;
}
}
And this is the code in my controller file:
class Chart extends CI_Controller {
// Default Constructor
public function __construct() {
parent::__construct();
$this->load->helper('html');
$this->load->model('Has_alert', '', TRUE);
$this->Has_alert->__get_query();
//$sql = 'alerts_get_alerts';
//$query = $this->db->query($sql);
//$row = $query->first_row();
//$header_data['hasAlert'] = $row->active;
}
public function index()
{
//Data Arrays
$this->load->helper('html');
$header_data['page_title'] = 'Title';
$header_data['tabid'] = "home";
//Load the headtop.php file and get values from data array
$this->load->view('includes/headertop.php', $header_data);
$this->load->view('homepage');
$this->load->view('includes/newfooter.php');
}
I got this error message on my view file:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: hasAlert
Filename: includes/headertop.php
Line Number: 184
Does anyone know what the problem is? Thank you.
Model
function __get_query() {
$sql = 'alerts_get_alerts';
$query = $this->db->query($sql);
$row = $query->first_row();
return $row->active;
}
Controller
public function index(){
$this->load->model("Has_alert");
//Data Arrays
$this->load->helper('html');
$header_data['page_title'] = 'Title';
$header_data['tabid'] = "home";
$header_data['hasAlert'] = $this->Has_alert->__get_query();
//Load the headtop.php file and get values from data array
$this->load->view('includes/headertop.php', $header_data);
$this->load->view('homepage');
$this->load->view('includes/newfooter.php');
}
I'm assuming that things like "alerts_get_alerts" is pseudocode.

General internet "scraping" question

I just started studying programming about 6 months ago and I have really been diving deep into Objective-C. Unfortunately, I don't know any programmers IRL to bounce general questions off of.
What languages are being used when people write programs that will search a website for information and then send it back? For example, if I wanted to write a program that would search weather.com for the daily temperature of the last 30 days in a given location and then send it back as say...an NSArray or NSDictionary, how would i do that? Can I do that in Objective C or is that super-advanced scripting language stuff? If I CAN do it in Objective-C, can someone link to a tutorial or place that may get me started learning that type of stuff? (I don't really know the term for this type of programming so my google searches have been unfruitful.)
I most commonly use PHP and MySQL with CURL
http://en.wikipedia.org/wiki/CURL
You can do some fun things like Search Engine Results Page queries, etc.
Here is the source from a crawler I use. I've cut out some parts for anonymity's sake, but it's a good almost-working example. I can help you get it running if need be.
<?php
class Crawler {
protected $markup = '';
protected $uri = '';
protected $db_location = "localhost";
protected $db_username = "***";
protected $db_password = "***";
protected $db_name = "***";
public function __construct() {
ini_set('memory_limit', -1);
}
public function getMarkup() {
$markup = "";
$markup = #file_get_contents($this->uri);
return $markup;
}
public function get($type) {
$method = "_get_{$type}";
if (method_exists($this, $method)){
return call_user_method($method, $this);
}
}
protected function db_query($query) {
$connection = mysql_connect($this->db_location,$this->db_username,$this->db_password) or die(mysql_error());
mysql_select_db($this->db_name,$connection) or die(mysql_error()." >> ".$query);
//echo $query."<br/>"; //for debugging
$result = mysql_query($query,$connection) or die (mysql_error()." >> ".$query);
$i = 0;
if($result != 1)
{
while ($data_array = mysql_fetch_array($result))
{
foreach($data_array as $key => $value)
{
$tableArray[$i][$key] = stripslashes($data_array[$key]);
}
$i++;
}
return $tableArray;
}
}
protected function db_insert($table,$array) {
$tableArray = $this->db_query("show columns from ".$table);
$inputString = "";
foreach($tableArray as $key => $value)
{
if (array_key_exists($value[0], $array) && $value[0]) {
$inputString .= "'".addslashes($array[$value[0]])."', ";
} else {
$inputString .= "'', ";
}
}
$inputString = substr($inputString, 0, -2);
$this->db_query("insert into $table values(".$inputString.")");
return mysql_insert_id();
}
protected function _get_data() {
//$scrape['id'] = $this->get('id');
$scrape['name'] = $this->get('name');
$scrape['tags'] = $this->get('tags');
$scrape['stat_keys'] = $this->get('stat_keys');
$scrape['stat_values'] = $this->get('stat_values');
foreach($scrape['stat_values'] as $key => $value) {
$scrape['stat_values'][$key] = trim($scrape['stat_values'][$key]);
if(strpos($value,"<h5>Featured Product</h5>")) {
unset($scrape['stat_values'][$key]);
}
if(strpos($value,"<h5>Featured Company</h5>")) {
unset($scrape['stat_values'][$key]);
}
if(strpos($value,"<h5>Featured Type</h5>")) {
unset($scrape['stat_values'][$key]);
}
if(strpos($value,"sign in")) {
unset($scrape['stat_values'][$key]);
}
if(strpos($value,"/100")) {
unset($scrape['stat_values'][$key]);
}
}
if(sizeof($scrape['tags']) > 0 && is_array($scrape['tags'])) {
foreach($scrape['tags'] as $tag) {
$tag_array[$tag] = $tag_array[$tag] + 1;
}
$scrape['tags'] = $tag_array;
foreach($scrape['tags'] as $key => $tag_count) {
$scrape['tags'][$key] = $tag_count - 1;
}
}
$scrape['stat_values'] = array_merge(array(),$scrape['stat_values']);
return $scrape;
}
protected function _get_images() {
if (!empty($this->markup)){
preg_match_all('/<img([^>]+)\/>/i', $this->markup, $images);
return !empty($images[1]) ? $images[1] : FALSE;
}
}
protected function _get_links() {
if (!empty($this->markup)){
preg_match_all('/<a([^>]+)\>(.*?)\<\/a\>/i', $this->markup, $links);
return !empty($links[1]) ? $links[1] : FALSE;
}
}
protected function _get_id() {
if (!empty($this->markup)){
preg_match_all('/\/wine\/view\/([^`]*?)-/', $this->markup, $links);
return !empty($links[1]) ? $links[1] : FALSE;
}
}
protected function _get_grape() {
if (!empty($this->markup)){
preg_match_all('/ class="linked" style="font-size: 14px;">([^`]*?)<\/a>/', $this->markup, $links);
return !empty($links[1]) ? $links[1] : FALSE;
}
}
}
if($_GET['pass'] == "go") {
$crawl = new Crawler();
$crawl->go();
}
?>
So, you want to know how to write server-side code? Well, in theory you can write that in whatever you want. I also assure you it isn't "super-advanced".
You might find it easiest to get started with PHP. W3schools.com has a fine tutorial.
What you are describing is a crawler (e.g. Google).
Any language that has the ability to send HTTP requests and receive responses can do this (which is most languages).
If you don't care to code this thing from scratch, try downloading an open source crawler framework that will allow for custom plugins to parse the resulting HTML.
For your example, you would tell the crawler what site you want it to crawl (i.e. your weather site), add URI constraints if necessary, and create a custom plugin to parse the weather data out of the HTML it responds with. You can then save that data however you see fit.