Does anyone know how to upload images using PHP and calling the UploadHandler.php?
I'm not sure what information needs to be passed and in what format.
Here's what I have so far:
$prop="test";
session_id($prop);
#session_start();
$url = 'http://christinewilson.ca/wp-content/uploads/2013/02/port_rhdefence.png';
$file_name[] = file_get_contents($url);
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler(array(
'user_dirs' => true
));
The response is contained within the UploadHandler class object and can be retrieved like shown below.
$upload_handler = new UploadHandler();
$response = $upload_handler->response;
$files = $response['files'];
$file_count = count($files);
for ($c = 0; $c < $file_count; $c++) {
if (isset($files[$c]->error))
continue;
$type = $files[$c]->type;
$name = $files[$c]->name;
$url = $files[$c]->url;
}
I could not find a way to get the file name via php so I had to do it myself.
First you need to add a public variable under UploadHandler.php
class UploadHandler
{
public $file_name;
protected $options;
and then add that to the function that creates the name
protected function get_file_name($name,
$type = null, $index = null, $content_range = null) {
$this->file_name = $this->get_unique_filename(
$this->trim_file_name($name, $type, $index, $content_range),
$type,
$index,
$content_range
);
return $this->file_name;
}
then under index.php you could do something like this
$upload_handler = new UploadHandler();
echo "\r\n [" . $upload_handler->fileName . "]\r\n";
I hope this help you or save someone some time :)
you can use the basic plugin:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
</script>
</body>
I ran into the same problem, where in the PHP I wanted to write all the URLS that UploadHandler.php had created to a mySQL database. If you look through the code, you'll see that
public function post($print_response = true)
actually returns the data structure from generate_response (which is a array with all the processed image metadata like image size, sanitized url, etc), but the call to $this->post() never does anything which it. So I add a variable
protected $upload_content = [];
to the class definition and changed the logic in function
protected function initialize()
to
case 'POST':
$this->upload_content = $this->post(false);
break;
to update this variable after the images have been processed (you would need to do something similar with the GET case if you are using that). Then, I add a public function to the class to get this variable
public function get_upload_content() {
return $this->upload_content;
}
and now the UploadHandler class can be called like this
$upload_handler = new UploadHandler();
$images = $upload_handler->get_upload_content();
// Call a function that writes the urls in $images array to a database
Hope this helps!
First of all you should create protected variable:
protected $options;
protected $uploaded_files = [];
then you should assign to this variable the response value in post() method:
$this->uploaded_files = $response;
return $this->generate_response($response, $print_response);
then you should create public method which would return that response:
public function get_uploaded_files() {
return $this->uploaded_files;
}
and finally you should initiate the class and call the method:
$uploadPicture = new UploadHandler();
$images = $uploadPicture->get_uploaded_files();
Hope this Helps !
Related
How can I convert Base64 value to Image PNG using intervention image and laravel storage?
public function userLogout(Request $request) {
$data = $request->all();
if ($request->isMethod('post')) {
$poster = explode(";base64", $request->picture);
$image_type = explode("image/", $poster[0]);
$mime_type = '.'.$image_type[1];
$image_base = base64_decode($poster[1]);
$data['picture'] = Storage::disk('player-images')->put($image_base, file_get_contents($poster));
$path = public_path('storage/player-images/'.$image_base);
Image::make($poster)->save($path);
$data['picture'] = 'player-images/' . $image_base;
User::where('name', Auth::user()->name)->update($data);
}
return view('gallery');
}
i got an error message:
"file_get_contents() expects parameter 1 to be a valid path, array given"
and here is my ajax function
var canvas = document.getElementById('canvas');
var dataUrl = canvas.toDataURL('image/png');
$(document).ready(function(){
$('#save').click(function(e){
e.preventDefault();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
type: "POST",
url: "/gallery",
data: {
picture: dataUrl,
}
}).done(function(o) {
console.log("saved");
});
});
});
How can i save the base64 value to database like player-images/blabla.png and store image to path public/storage/player-images/
sorry, my English is bad.
thanks.
I solved it!. I changed the function in controller like this.
public function userLogout(Request $request)
{
$data = $request->all();
if ($request->isMethod('post')) {
if (preg_match('/^data:image\/(\w+);base64,/', $data['picture'])) {
$value = substr($data['picture'], strpos($data['picture'], ',') + 1);
$value = base64_decode($value);
$imageName = time() . '.png';
$val = Storage::disk('player-images')->put($imageName, $value);
$path = public_path('storage/player-images/'.$imageName);
Image::make($data['picture'])->resize(304, 277)->save($path);
$data['picture'] = 'player-images/' . $imageName;
User::where('name', Auth::user()->name)->update(['picture' => $data['picture']]);
}
}
return view('gallery');
}
I know that probably you solved your doubt, but I was looking for something similar and I didn't find it, so I will leave the following code for someone that may need it.
The goal of this code is to get an image from Pixabay using an URL.
My solution for something similar:
public function store(){
$url = json_decode(request('photo')); //Photo is the field that I fill in the view, that contain a URL to my image in pixabay;
$contents = file_get_contents($url);
$name = substr($url, strrpos($url, '/') + 1);
$blob = base64_encode($this->resizeImage($contents));
Photos::firstOrCreate(['photo' => $name,'thumb' => $blob]); //Photos is my model
}
private function resizeImage($contents) : string {
return (string) Image::make($contents)->resize(75, 75)->encode('data-url'); // Very important this cast to String, without it you can not save correctly the binary in your DB;
}
View:
For use the code in my view I put:
When I return to view the Model I use a 'for' to print all images, like that:
#foreach($photos as $element)
<img src="{{ base64_decode($element->thumb) }}" alt="" >
#endforeach
#Warning
Is very important you have a Blob field in your DB, so in your Schema on Laravel Migrate you have to put something as: $table->binary('thumb');
You can check my code on my git:
lucasfranson10/multisafepay
I am trying to save multiple images on the server. Lets start from the beginning:
//I use this function for testing
function testSave(){
$this->_renderChart(156);
}
//This function takes chart_id as a parameter to render a proper chart.
function _renderChart($chart_id = null){
if(!$chart_id)
return false;
$chartFilterList = $this->getChartFilterListFromId($chart_id);
$this->loadChartFromId($chart_id, $chartFilterList);
$this->layout = 'analytics\chart_one.ctp';
}
The above function's view contains all the necessary scripts to render the chart. This is the part that is translating the rendered chart into base64string and saves it:
//../views/layouts/analytics/chart_one.ctp
<script type="text/javascript">
$(document).ready(function(){
saveChartAsImage('#chart1');
});
</script>
And the above function's body:
function saveChartAsImage(div){
var base64string = $(div).jqplotToImageStr();
$.ajax({
url: 'saveImage',
type: "POST",
dataType: "html",
data:"data=" + base64string
});
}
}
This is not even close to be working. Am I doing something wrong here?
If these functions are controller actions you can use $this->response->body() in controller's afterFilter() callback to get the response content and save it to file. If these are helper functions you can get the content in afterLayout() or afterRender() callbacks of the helper using $this->_View->Blocks->get('content');
I advise creating a behavior, and add the action beforeValidate();
After that make the conditions necessary to invoke the specific actions (listed in your question).
Example:
app/Model/Behavior/ChartBehavior.php
class ChartBehavior extends ModelBehavior {
// if necessary, create a setup action
public function setup(Model $Model, $settings = array()) { }
public function upload(Model $Model) {
// use the $Model->data to see all information from your form
debug($Mode->data);
// now call your functions below to upload
}
public function line_chart($chart_id = null){
//magic...
}
public function bar_chart($chart_id = null){
//magic...
}
public function pie_chart($chart_id = null){
//magic...
}
I hope it helps you.
i wanna migrate my website into CI.
i just simply modified from ci sample file welcome.php
in index() function , i load the view to show.
however , i put many javascripts and css files in the header file .
and call it by $this->load->view('header');
but i can not load the javascript files correctly!
Can anyone give me some tips ? it;s hard to configure how to set the correct path.
<script type="text/javascript" src="/assets/javascripts/order.js"></script>
<script type="text/javascript" src="../assets/javascripts/order.js"></script>
<script type="text/javascript" src="../../assets/javascripts/order.js"></script>
my controller code as following
class Welcome extends CI_Controller {
public function index()
{
$this->load->helper('url');
$this->base = $this->config->item('base_url');
$this->load->view('header');
$this->load->view('welcome_message');
}
}
belows are my folder structure
put your assets folder with applications, system, assets
not in application and simple load the url helper class in controller where you call the header view part something like
$this->load->helper('url');
$this->load->view('header');
and simply use something like this in your header file..
because $this->base_url() return the / folder..
<script src="<?php echo $this->base_url();?>assets/javascript/jquery.js"></script>
Changing the folder structure because access within the application folder is just for the core part that i know..
here is the link if you want to know more about URL Helper
This is the best way with minimal code
<script src="<?php echo base_url('assets/javascript/jquery.js');?>"></script>
<script src="<?php echo base_url('assets/css/bootstrap.min.js');?>"></script>
Jogesh_p's answer will surely solve the assets loading problem you have. I would like to follow up on this question you gave
Thank you or your support. btw the way if i wanna use some library
like phpMailler or zend framwork .
You can put in application/libraries/
Then load it in the controller using the Library's Class' Name
$this->load->library('phpmailer');
Its your choice to load in on the constructor or on the individual method.
Good Luck!
To solve my problem I created helper functions to load assets. And here is my code deployed in my application.
PS: First I planned a good/flexible directory structure
[some_helper.php]
/*
* Created: 2017/12/14 00:28:30
* Updated: 2017/12/14 00:28:39
* #params
* $url_structure = 'assets/js/%s.js'
* $files = ['main.min', 'social']
* $echo = FALSE
*
*/
function load_js($files = [], $url_structure = NULL, $version = '1.0', $echo = FALSE){
$html = "";
foreach ($files as $file) {
if($url_structure){
$file = sprintf($url_structure, $file);
}
$file_url = base_url($file);
$html .= "<script src=\"{$file_url}?v={$version}\"></script>";
}
if($echo) {
echo $html;
}
return $html;
}
/*
* Created: 2017/12/14 00:28:48
* Updated: 2017/12/14 00:28:51
* #params
* $version = '1.0' // Later load from configuration
* $url_structure = 'assets/js/%s.css'
* $files = ['main.min', 'social']
* $echo = FALSE
*
*/
function load_css($files = [], $url_structure = NULL, $version = '1.0', $echo = FALSE){
$html = "";
foreach ($files as $file) {
if($url_structure){
$file = sprintf($url_structure, $file);
}
$file_url = base_url($file);
echo "<link rel=\"stylesheet\" href=\"{$file_url}?v={$version}\">";
}
if($echo) {
echo $html;
}
return $html;
}
Then called in the view
[some_view.php]
$css = [
'path' => 'assets/css/%s.css',
'files' => ['bootstrap.min','style']
];
load_css($css['files'], $css['path'], '1.0', TRUE);
Hope it helps someone.
In the case of OP $css['path'] = 'application/assets/css/%s.css'; will do the trick.
Updated the code on Github which I will keep updating.
assets/css/bootstrap.min.css"
<!-- Include JS -->
<script src="<?php echo base_url();?>assets/js/jquery.js"></script>
<script src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
function addcategory()
{
//alert("<?php echo base_url();?>")
$.ajax({
complete: function() {}, //Hide spinner
url : '<?php echo base_url();?>category/search',
data:$('#add_category').serialize(),
type : "POST",
dataType : 'json',
success : function(data) {
if(data.code == "200")
{
alert("category added successfully");
}
},
beforeSend: function(XMLHttpRequest){}, //$.blockUI();
cache: false,
error : function(data) {
}
});
}
Following this tutorial http://johnsquibb.com/tutorials/mvc-framework-in-1-hour-part-one Im trying to write my first MVC Blog.
I understood how it works, router.php Calls the suitable page controller. This controller calls the model, Then calls the View page with the returned value.
My question is, What if I want to add to the same news.php page a header\footer. Normally I would write "include("header.php"). But now when using MVC, how could I implement that?
These are my files:
router.php:
<?php
/**
* This controller routes all incoming requests to the appropriate controller
*/
//Automatically includes files containing classes that are called
//fetch the passed request
$pageURL = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$path_parts = pathinfo($pageURL);
$page_name = $path_parts['filename'];
$parsed = explode('?' , $page_name);
//the page is the first element
$page = array_shift($parsed);
// If there is any variables, GET them.
if(!empty($parsed))
{
$parsed = explode('&' , $parsed[0]);
$getVars = array();
foreach ($parsed as $argument)
{
//explode GET vars along '=' symbol to separate variable, values
list($variable , $value) = explode('=' , $argument);
$getVars[$variable] = urldecode($value);
}
}
//compute the path to the suitable file
$target ='controllers/' . $page . '_controller.php';
//get target controller
if (file_exists($target))
{
include_once($target);
//modify page to fit naming convention
$class = ucfirst($page) . '_Controller';
//instantiate the appropriate class
if (class_exists($class))
{
$controller = new $class;
}
else
{
//did we name our class correctly?
die('class does not exist!');
}
}
else
{
//can't find the file in 'controllers'!
die('page does not exist!');
}
//once we have the controller instantiated, execute the default function
//pass any GET varaibles to the main method
$controller->main($getVars);
// AutoLoad
function __autoload($className)
{
// Parse out filename where class should be located
// This supports names like 'Example_Model' as well as 'Example_Two_Model'
list($suffix, $filename) = preg_split('/_/', strrev($className), 2);
$filename = strrev($filename);
$suffix = strrev($suffix);
//select the folder where class should be located based on suffix
switch (strtolower($suffix))
{
case 'model':
$folder = '/models/';
$filename = ($className);
break;
case 'library':
$folder = '/libraries/';
break;
case 'driver':
$folder = '/libraries/drivers/';
break;
}
//compose file name
$file = SERVER_ROOT . $folder . strtolower($filename) . '.php';
//fetch file
if (file_exists($file))
{
//get file
include_once($file);
}
else
{
//file does not exist!
die("File '$filename' containing class '$className' not found in
'$folder'.");
}
}
?>
post_controller.php
<?php
/**
* This file handles the retrieval and serving of posts posts
*/
class Posts_Controller
{
/**
* This template variable will hold the 'view' portion of our MVC for this
* controller
*/
public $template = 'posts';
/**
* This is the default function that will be called by router.php
*
* #param array $getVars the GET variables posted to index.php
*/
public function main(array $getVars)
{
//$b_controller =new Bottom_Bar_Controller;
//$b_controller->main($getVars);
$postsModel = new Posts_Model;
//get an post
$post = $postsModel->get_post($getVars['id']);
//create a new view and pass it our template
$header = new View_Model('header_template');
$bottom_bar = new View_Model('bottom_bar');
$view = new View_Model($this->template);
//assign post data to view
$view->assign('header', $header->render(FALSE));
$view->assign('bottom', $bottom_bar->render(FALSE));
$view->assign('title' , $post['title']);
$view->assign('content' , $post['content']);
$view->assign('date' , $post['date']);
$view->assign('by' , $post['added_by']);
$view->render();
}
}
posts_model.php
<?php
/**
* The Posts Model does the back-end heavy lifting for the Posts Controller
*/
class Posts_Model
{
/**
* Holds instance of database connection
*/
private $db;
public function __construct()
{
$this->db = new MysqlImproved_Driver;
}
/**
* Fetches article based on supplied name
*
* #param string $author
*
* #return array $article
*/
public function get_post($id)
{
//connect to database
$this->db->connect();
//sanitize data
$author = $this->db->escape($id);
//prepare query
$this->db->prepare
(
"
SELECT * FROM `posts`
WHERE
`id` = '$id'
LIMIT 1
;
"
);
//execute query
$this->db->query();
$article = $this->db->fetch('array');
return $article;
}
}
?>
view_model.php
<?php
/**
* Handles the view functionality of our MVC framework
*/
class View_Model
{
/**
* Holds variables assigned to template
*/
private $data = array();
/**
* Holds render status of view.
*/
private $render = FALSE;
/**
* Accept a template to load
*/
public function __construct($template)
{
//compose file name
$file = SERVER_ROOT . '/views/' . strtolower($template) . '.php';
if (file_exists($file))
{
/**
* trigger render to include file when this model is destroyed
* if we render it now, we wouldn't be able to assign variables
* to the view!
*/
$this->render = $file;
}
}
/**
* Receives assignments from controller and stores in local data array
*
* #param $variable
* #param $value
*/
public function assign($variable , $value)
{
$this->data[$variable] = $value;
}
/**
* Render the output directly to the page, or optionally, return the
* generated output to caller.
*
* #param $direct_output Set to any non-TRUE value to have the
* output returned rather than displayed directly.
*/
public function render($direct_output = TRUE)
{
// Turn output buffering on, capturing all output
if ($direct_output !== TRUE)
{
ob_start();
}
// Parse data variables into local variables
$data = $this->data;
// Get template
include($this->render);
// Get the contents of the buffer and return it
if ($direct_output !== TRUE)
{
return ob_get_clean();
}
}
public function __destruct()
{
}
}
posts.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../style/style.css" rel="stylesheet" type="text/css" media="screen" />
<title> Posts (View)</title>
</head>
<body>
<div id="main">
<div class="container">
<?=$data['header'];?>
<div id="content">
<div class="content-background">
<h2> <?=$data['title'];?></h2>
<h4> <?=$data['date'];?> </h4>
<p><?=$data['content'];?></p>
</div>
</div>
</div>
</div>
</body>
</html>
Part of the problem is, that your tutorial has a pretty primitive interpretation of MVC-inspired design pattern (you actually cannot implement classical MVC in PHP, but there are patterns, that are based on it).
View is not just a template. Views are supposed to be class instances, which contain all presentation logic and deal with multiple templates. What you actually have there is a layout template which contains posts template.
// class \Application\View\Posts
public function render()
{
$layout = new Template( $this->defaultTemplateDirectory . 'layout.html');
$content = new Template( $this->defaultTemplateDirectory . 'posts.html' );
$layout->assign( 'content' , $content->render() );
return $layout->render();
}
Also, one of the things, that a view instance should do, is requesting information from the model layer.
Few materials that you might find useful:
Model-View-Confusion part 1: Why the model is accessed by the view in MVC
Simple PHP Template Engine
How should a model be structured in MVC?
And if you want to expand you knowledge in OOP, this post contains a list of recommended lectures and books.
There is no good solution in the MVC structure for that. You can find a solution in every framework. In CakePHP for example you can use an AppController, a controller which is always called for every requests. Sort of base controller.
But no, not very nice to do.
Most simple one is to ask the data directly from the view. That sounds weird but it is accepted in the MVC structure. So in your view you call $News->getLatestItems(10); and work with them.
I don't like it but it works.
If you have lots of widgets and blocks MVC alone might just not be the right structure. Then you could take a look at things like: http://techportal.inviqa.com/2010/02/22/scaling-web-applications-with-hmvc/ which is a derivate of MVC.
Another solution which you see more and more: Request it via AJAX calls. So just load them after the page has loaded. That way you also solve the issue since one MVC request then becomes multiple MVC requests.
I need 3 different templates for my Codeigniter application. I had read about Themes' library. But still I didn't get any idea about how to add a template to Codeignier ..
I got about how to involke template in Controller .
Please help
I'm using this template library, is really simple and works well for me.
application/libraries/Template.php
<?php
class Template {
var $template_data = array();
var $use_template = '';
/**
* Set variable for using in the template
*/
function set($name, $value)
{
$this->template_data[$name] = $value;
}
/**
* Set template name
*/
function set_template($name)
{
$this->use_template = $name;
}
/**
* Load view
*/
function load($view = '' , $view_data = array(), $template = '', $return = FALSE)
{
$this->CI =& get_instance();
if (empty($template)) {
$template = $this->CI->config->item('template_master');
}
if (!empty($this->use_template)) {
$template = $this->use_template;
}
$this->set($this->CI->config->item('data_container'), $this->CI->load->view($view, array_merge($view_data, array ('template' => $this->template_data)), true));
return $this->CI->load->view($this->CI->config->item('template_folder') . '/' . $template, $this->template_data, $return);
}
}
application/config/template.php
<?php
$config['template_master'] = 'main';
$config['template_folder'] = 'templates';
$config['data_container'] = 'content';
application/views/templates/main.php
Header<br />
<?php echo $content; ?></br>
Footer
application/controllers/welcome.php
<?php
class Welcome extends CI_Controller
{
public function index()
{
$this->load->config('template');
$this->load->library('template');
$this->template->load('welcome', array('view' => 'data'));
}
}
I usually put the config/library files on autoload, and you can use anytime $this->template->set_template('other_template'); to use another one :)
Hope it helps.
I've used the following setup in a CodeIgniter project:
The different templates along with stylesheets and images are in the following folder:
/templates/1/header.php
/templates/1/footer.php
/templates/1/images/*
/templates/1/style/*
/templates/2/header.php
/templates/2/footer.php
/templates/2/images/*
/templates/2/style/*
In your Controllers determine which template you want to load and pass the path to that template as a variable ( templatepath in this case ) to your View files. Inside the view files you do the following:
<?php include($templatepath.'/header.php'); ?>
at the top and
<?php include($templatepath.'/footer.php'); ?>
at the bottom.