undefined variable while i defined it - php

so im trying to make sure that if i upload an imagefile (a profile update for my user) that i'm fetching the filepath but i get an Undefined variable:imagePath error.
so i tried to dd my imagepath but it came out with noting while i do define it.
i want to put the filepath here
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'url' => 'url',
'image' => '', //filepath here
]);
here i define it.
if(request('image'))
{
$imagePath = request('image')->store('profile', 'public'); //here i define the variable
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1000, 1000); // here i try to use it
$image->save();
}
dd(array_merge(
$data,
['image' => $imagePath] //the error occurs here while trying to merge
));
so i expected this array merge to give me a readable path but i get an error instead. i might've made a spelling mistake somewehre as english is not my first language but i read over my code and it all looks to be okay.

remove the {}
$image = Image::make(public_path("storage/$imagePath"))->fit(1000, 1000);
or concatenate separately
$image = Image::make(public_path('storage/'.$imagePath))->fit(1000, 1000);
Let's say $imagePath = 'randomString', the code will try to get the variable named randomString if you use it like this {$imagePath}.
We use this trick to call dynamic variables.
$textVariable = 'this text';
$text2 = 'textVariable';
echo ${$text2}; // will echo "this text"

try this
if($request->image)
{
$imagePath = $request->image->store('profile', 'public'); //here i define the variable
$image = Image::make(public_path("storage/".$imagePath))->fit(1000, 1000); // here i try to use it
$image->save();
}
dd(array_merge(
$data,
['image' => $imagePath] //the error occurs here while trying to merge
));
I just change your request('image') to $request->image and remove the {} here $image = Image::make(public_path("storage/".$imagePath))->fit(1000, 1000);
I assume that you're in controller and you have Request $request
Hope it helps.

else {
$sqlit_del_imgs = explode(",", "$delelte_product_images");
foreach($split_del_prd_imgs as $img_name) {
unlink("products_img/" . $_GET["prd_id"] ."/" . $img_name);
}

Related

Can someone help me to Insert multiple pictures on laravel 7 [duplicate]

This question already has answers here:
Laravel 5.3 multiple file uploads
(8 answers)
Closed 1 year ago.
I am new to laravel so tried to insert informations to table on mysql used migrate for Images table but when i insert Multiple pictures it's returns with this error :
Invalid argument supplied for foreach()
If you guys have experience to this feel free to advise thanks.
Here is Input code of multiple pictures:
<input type="file" id="file" name="file[]" multiple>
Here is Controller code
use DB;
use Illuminate\Http\Testing\MimeType;
use Illuminate\Http\Request;
use App\Images;
public function insert (Request $Request){
$name = $Request->input('name');
$price = $Request->input('price');
$qty = $Request->input('qty');
$description = $Request->input('description');
$email = $Request->input('email');
$utas = $Request->input('utas');
$uruu = $Request->input('uruu');
$garage = $Request->input('garage');
$duureg = $Request->input('duureg');
$tagt = $Request->input('tagt');
$bairshil = $Request->input('bairshil');
$talbai = $Request->input('talbai');
$haalga = $Request->input('haalga');
$tsonh = $Request->input('tsonh');
$shal = $Request->input('shal');
$ttsonh = $Request->input('ttsonh');
$bdawhar = $Request->input('bdawhar');
$ashigon = $Request->input('ashig');
$lizing = $Request->input('lizing');
$bairlal = $Request->input('bairlal');
$hereg = $Request->input('hereg');
$zahi = $Request->input('zahi');
$file='';
$file_tmp='';
$location="uploads/";
$data='';
foreach($_FILES['images']['name'] as $key=>$val)
{
$file=$_FILES['images']['name'][$key];
$file_tmp=$_FILES['images']['tmp_name'][$key];
move_uploaded_file($file_tmp,$location.$file);
$data .=$file." ";
}
DB::table('laravel_products')
->insert( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
$lastInsertedID = DB::getPdo()->lastInsertId();
$images = $Request->input('file');
foreach ($images as $image){
$image_new_name = time() . $image->getClientOriginalName();
$image->move('uploads',$image_new_name);
$post = new Images;
$post->product_id = $lastInsertedID;
$post->image = 'uploads/' . $image_new_name;
$post->save();
}
return view('createproduct');
}
}
I do like this. Hope this could be helpful for you.
$image1 = $request->image1; // keep image in variable
$image2 = $request->image2; // keep image in variable
$data = array(); // declare a array type variable
if(!empty($image1)) //check image1 is empty or not
{
$image1_name=uniqid().date('dmYhis'); // set image name
$image1_upload_path='backend/product_images/'; // set upload path
$ext6=strtolower($image1->getClientOriginalExtension()); //get extension
$image1_full_name=$image1_name.'.'.$ext6; // set image name with extension
$image1_url=$image1_upload_path.$image1_full_name; // keep image upload url to a variable
$success=$image1->move($image1_upload_path,$image1_full_name); // move to upload folder
$data['image1']=$image1_url; // finaly store image link to database
}
if(!empty($image2)) //check image2 is empty or not
{
$image2_name=uniqid().date('dmYhis'); // set image name
$image2_upload_path='backend/product_images/'; // set upload path
$ext6=strtolower($image1->getClientOriginalExtension()); //get extension
$image2_full_name=$image2_name.'.'.$ext6; // set image name with extension
$image2_url=$image2_upload_path.$image2_full_name; // keep image upload url to a variable
$success=$image2->move($image2_upload_path,$image2_full_name); // move to upload folder
$data['image2']=$image2_url; // finaly store image link to database
}
$store = Product::create($data); // store data to database with Product model

Validate a base64 decoded image in laravel

Im trying to get a image from a PUT request for update a user picture(using postman), and make it pass through a validation in Laravel 5.2, for making the call in postman use the following url:
http://localhost:8000/api/v1/users?_method=PUT
and send the image string in the body, using a json like this:
{
"picture" : "data:image/png;base64,this-is-the-base64-encode-string"
}
In the controller try a lot of differents ways for decode the image and try to pass the validation:
First I tried this:
$data = request->input('picture');
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$image = base64_decode($data);
$file = app_path() . uniqid() . '.png';
$success = file_put_contents($file, $image);
Then I tried this:
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$typeFile = explode(':', $type);
$extension = explode('/', $typeFile[1]);
$ext = $extension[1];
Storage::put(public_path() . '/prueba.' . $ext, $data);
$contents = Storage::get(base_path() . '/public/prueba.png');
Try to use the intervention image library (http://image.intervention.io/) and don't pass:
$image = Image::make($data);
$image->save(app_path() . 'test2.png');
$image = Image::make(app_path() . 'test1.png');
This is the validation in the controller:
$data = [
'picture' => $image,
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name')
];
$validator = Validator::make($data, User::rulesForUpdate());
if ($validator->fails()) {
return $this->respondFailedParametersValidation('Parameters failed validation for a user picture');
}
this is the validation in the User-model:
public static function rulesForUpdate() {
return [
'first_name' => 'max:255',
'last_name' => 'max:255',
'picture' => 'image|max:5000|mimes:jpeg,png'
];
}
If you are using Intervention anyways, then you can leverage it for a custom validation rule. I have one called "imageable". It basically makes sure that the input given will be able to be converted to an Intervention image. Base64 data image strings will pass. A string of "foo" will not.
Validator::extend('imageable', function ($attribute, $value, $params, $validator) {
try {
ImageManagerStatic::make($value);
return true;
} catch (\Exception $e) {
return false;
}
});
This obviously just checks that the input is able to be converted to an image. However, it should show you as a use-case how you can leverage Intervention and any of it's methods to create a custom rule.
You can extend the Validator class of Laravel.
Laravel Doc
But anyway try this
Validator::extend('is_png',function($attribute, $value, $params, $validator) {
$image = base64_decode($value);
$f = finfo_open();
$result = finfo_buffer($f, $image, FILEINFO_MIME_TYPE);
return $result == 'image/png';
});
Don't forget the rules:
$rules = array(
'image' => 'is_png'
);
inside extend function add this
$res= mime_content_type($value);
if ($res == 'image/png' || $res == 'image/jpeg') {
return $res;
}

array_key_exists() expects parameter 2 to be array, string when using pushWoosh Class

I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.

How do I write an image, along with other data, to my database using php and mysql

Hello: I have a web form that submits data to my db. I am able to create a signature image and save it within my directory. I want to save/store that signature image in my mysql db along with the record so I can call it later.
Written in CodeIgniter 2.0
here are my model and controller.
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
imagepng($img, 'signature.png');
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form);
}
}
public function insert_signature($data)
{
$sig_hash = sha1($data['output']);
$created = time();
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'first_name' => $data['fname'],
'last_name' => $data['lname'],
'signator' => $data['name'],
'signature' => $data['output'],
'sig_hash' => $sig_hash,
'ip' => $ip,
'created' => $created
);
return $this->db->insert('signatures', $data);
}
I found the function below on php.net but apparently I am doing something wrong or various things wrong. Does anyone know how to accomplish this functionality?
$imagefile = "changethistogourimage.gif";
$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();
Got it - For those curious here are the changes to my controller:
public function sig_to_img()
{
if($_POST){
require_once APPPATH.'signature-to-image.php';
$json = $_POST['output'];
$img = sigJsonToImage($json);
// Save to file
$file_name = trim(str_replace(" ","_",$_POST['name']));//name to used for filename
imagepng($img, APPPATH."../images/signatures/".$file_name.'.png');
$sig_name = $file_name.'.png'; //pass to model
// Destroy the image in memory when complete
imagedestroy($img);
$form = $this->input->post();
var_dump($form);
$this->coapp_mdl->insert_signature($form, $sig_name);
}
}

Tumblr API Posting A Photo from HTML Canvas

I'm having some issues trying to get my code to post the HTML canvas into Tumblr as a photo. I'm using PHP, and the code on the server side is as follows:
if(isset($_POST['postphoto']) and $_SESSION['loggedin']) {
$title = $_POST['title'];
$caption = $_POST['caption'];
tags = $_POST['tags'];
$imageData = $_POST['imageData'];
$imageData = substr($imageData,strpos($imageData,",")+1);
$imageData = str_replace(' ','+',$imageData);
# Set access token
$tumblr->set_token($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$data = array();
$data['post'] = array(
'type' => 'photo',
'generator' => 'AppName',
'data' => $imageData,
'name' => $title,
'caption' => $caption,
'tags' => $tags
);
$response = $tumblr->fetch('http://www.tumblr.com/api/write', $data);
if($response['successful']) {
echo "Update successful!<br><br>";
} else {
echo "Update failed. {$response[body]}<br><br>";
}
}
On the JavaScript side, I have the following:
var imgData = canvas.toDataURL("image/png");
$("#imageData").val(imgData);
imageData is of form type hidden so I simply set the value. The entire form is then posted to the PHP side. I have checked and the values are passed correctly (I did a similar thing for TwitPic, it works since it simply takes in the toDataURL value, but Tumblr is giving lots of issue).
Thanks for the help! :)
It could be because you are posting title to photo posts?
Photo posts don't have title. Let me know if it works when u remove 'name' => $title,.

Categories