403 Forbidden when post request with unEscape html content in laravel - php

403 error when this type data save.
this problem is only Namecheap server
when save then result in this
**but without unEscape HTML content data save successfully **
data seve with unEscape HTML content.
.................. /admin/page/update route point code below
public function update(Request $request)
{
$input = $request->all();
$content = $request->except(['page_code', 'status', '_token']);
$pageCode = $input['page_code'];
$page = Page::where('code', $pageCode)->first();
if ($page->type == 'dynamic') {
$content = [
'section_id' => $input['section_id'] ?? null,
'meta_keywords' => $input['meta_keywords'],
'meta_description' => $input['meta_description'],
'content' => Purifier::clean(htmlspecialchars_decode($input['content'])),
];
$data = [
'title' => $input['title'],
'data' => json_encode($content),
'status' => $input['status'],
];
} else {
$oldData = json_decode($page->data, true);
foreach ($content as $key => $value) {
if (is_file($value)) {
$oldValue = Arr::get($oldData, $key);
$content[$key] = self::imageUploadTrait($value, $oldValue);
} elseif ($key == 'content') {
$content[$key] = Purifier::clean(htmlspecialchars_decode($value));
}
}
$content = array_merge($oldData, $content);
$data = [
'status' => $input['status'] ?? true,
'data' => json_encode($content)
];
}
$page->update($data);
if ($page->type == 'dynamic') Cache::pull('pages');
notify()->success($page->title . ' ' . __(' Updated
Successfully'));
return redirect()->back();
}

Related

How to fix time out issue in FCM?

I'm working on a laravel apis which is consumed by a mobile application. The issue is i am using this library ( https://github.com/kreait/firebase-php ) to send FCM to device Ids. I have 10k device ids in my db. Issue is the code is implemented badly and it gets timedout after 1 minute. I need advice what is the best way to overcome this issue?
I have written this code:
// General Notification
$deviceTokens = PushDevices::all()->pluck( 'device_id' )->toArray();
if ( $request->hasFile( 'file' ) || $request->file ) {
try {
$request->validate( [
'image' => 'image|mimes:jpeg,jpg|max:2048|size:400'
] );
$originName = $request->file( 'file' )->getClientOriginalName();
$fileName = pathinfo( $originName, PATHINFO_FILENAME );
$extension = $request->file( 'file' )->getClientOriginalExtension();
$fileNames = time() . '.' . $extension;
$request->file( 'file' )->move( public_path( 'storage/notification' ), $fileNames );
$notiData = [
'title' => $request->title,
'body' => $request->body,
'imageurl' => $fileNames
];
// Create a copy in database for notifications.
NotificationTable::create( $notiData );
// Initiate token with https
$notification = [
'title' => $validation->safe()->only( 'title' )['title'],
'body' => $validation->safe()->only( 'body' )['body'],
'image' => 'https://example.com/storage/notification/' . $fileNames
];
$data = [
'first_key' => 'First Value',
'second_key' => 'Second Value',
];
$response[] = '';
foreach ( $deviceTokens as $object ) {
// $message = CloudMessage::new()->withTarget('token', $object)->withNotification($notification);
$message = CloudMessage::fromArray( [
'token' => $object,
'notification' => $notification
] );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( \Throwable $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
} catch ( \Throwable $th ) {
return response()->json( [
'status' => false,
'message' => $th->getMessage()
], 500 );
}}
$batchSize = 1000;
$deviceGroups = array_chunk($deviceTokens, $batchSize);
$notification = ['title' => $validation->safe()->only( 'title' )['title'], 'body' => $validation->safe()->only( 'body' )['body'],];
NotificationTable::create( $notification );
$data = ['first_key' => 'First Value', 'second_key' => 'Second Value',];
$response = array();
foreach ( $deviceTokens as $object ) {
$message = CloudMessage::new()->withTarget( 'token', $object )->withNotification( $notification )->withData( $data );
try {
$sendReport = $this->messaging->send( $message );
$response[] = $sendReport;
} catch ( MessagingException|FirebaseException $e ) {
$response[] = $e;
}
}
return response()->json( [ 'status' => true, 'response', $response ], Response::HTTP_ACCEPTED );
I want to send messages to all 10k devices but am unable to understand how to do it.

How to validate if user already exists?

I want to validate if it already exists in the DB, so then show an error message. But I am always getting user already exists in both cases. How can I fix it?
Below is my code:
public function add(Request $request)
{
$request_data = $request->all();
$customer_ids = $request_data['ids'];
$campaigns_id = $request_data['campaigns_id'];
$customer_id_array = explode(',', $customer_ids);
$whereIn = $customer_id_array;
$check_customer = Participant::where('id', $campaigns_id)->whereIn('customer_id', $whereIn)->get();
if (!empty($check_customer)) {
return ['code' => 402, 'status' => 'error', 'data' => $check_customer, 'message' => 'Customer Already Exists'];
}
foreach ($customer_id_array as $key => $value) {
$participantObj = new Participant;
$participantObj['customer_id'] = $value;
$participantObj->campaign_id = $campaigns_id;
// $participantObj->pin_number = $this->randomNumber(3).''.$key;
$data = $participantObj;
$data ->save();
}
return['code' => 200, 'status' => 'success'];
}
Change this line
if (!empty($check_customer)) {
to
if ($check_customer->isNotEmpty()) {

403 forbidden when i send PHP code into request to Laravel function

i have a problem in my Laravel function , i am creating a forum for web developers and all requests to the function works fine without no problem in any programming language but when i write PHP code in request which i send to the laravel function it's give me 403 forbidden i don't know why ? this happen when the request include
and if i make
return $req->all(); at the top of the function which receive the request i get Error in the request 301 You can try it by yourself here https://mohamedatef-staging.space/ng-websquare/ in the page of New discussion
https://mohamedatef-staging.space/ng-websquare/new-discuss
public function new_discussion(Request $request){
// return $request->all()['images'];
$data_array = $request->all()['dataArray'];
$data = json_decode($data_array, true);
$validator = Validator::make($data, [
'title' => 'required',
'data' => 'required',
'tags' => 'required',
],[
'title.required' => 'missingTitle',
'data.required' => 'missingData',
'tags.required' => 'missingTags',
]);
if($validator->fails()){
return response($validator->messages(), 200);
}
// $images_array = $request->all()['images'];
// return $images_array;
$urls = [];
if(!empty($request->all()['images'])){
$validator2 = Validator::make($request->all(), [
'images' => 'required|array|min:1',
'images.*' => 'image|mimes:jpeg,jpg,png|max:20000',
], [
'images.*image' => 'image_file_error',
'images.*mimes' => 'image_file_error',
'images.*max' => 'image_file_max',
]);
if($validator2->fails()){
return response($validator2->messages(), 200);
}
$images = $request->all()['images'];
foreach ($images as $image) {
$count = 0 ;
$image_name = time() . '.' . $image->getClientOriginalName();
$image->move(public_path('/images/forum'), $image_name);
$image_url = '/images/forum/'.$image_name;
$urls[] = $image_url;
$count++;
}
}
// }
// return response(['urls' => $urls[0]]);
// return response(['owner' => auth('members')->user()->id]);
$forum_slug = preg_replace('~[^\pL\d]+~u', '-', $data['title']);
$forum_slug2 = strtolower($forum_slug);
$forum = new forum ;
$forum->ownerID = auth('members')->user()->id;
$forum->title = $data['title'];
$forum->slug = $forum_slug2;
$forum->content = $data['data'];
$forum->tags = $data['tags'];
if(!empty($urls[0])){
$forum->img1 = $urls[0];
}
if(!empty($urls[1])){
$forum->img2 = $urls[1];
}
if(!empty($urls[2])){
$forum->img3 = $urls[2];
}
$forum->views = 0;
$forum->status = 0;
$forum->comments = 0;
$done = $forum->save();
if($done){
return response(['status' => 'done']);
}
}

Non static method 'load' should not be called statically

this is the function, the error is in line 25 in
'$data = Excel::load($path)->get();' saying that None-Static méthode 'load' should not be called statically:
function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'zi' => $row['zi'],
'siteId' => $row['siteId'],
'gsmId' => $row['gsmId'],
'topoCont' => $row['topoCont'],
'plannRedr' => $row['plannRedr'],
'Country' => $row['country'],
'dateReal' => $row['dateReal'],
'semReal' => $row['semReal'],
'statuts' => $row['country'],
);
}
}
if(!empty($insert_data))
{
DB::table('tbl_customer')->insert($insert_data);
}
}
return back()->with('success', 'Excel Data Imported successfully.');
}
}
add this in your controller :
use Maatwebsite\Excel\Facades\Excel;

How to get multiple images in laravel api?

I am creating a laravel API for complaints. This code is not saving multiple images in the database and I have to show multiple images in JSON response in an array. I am using array_get but it's not working for me. I have tried many things but it is not saving images in database. I have no idea. I am saving images in other table.
public function Complains(Request $request)
{
$response = array();
try {
$allInputs = Input::all();
$userID = trim($request->input('user_id'));
$cordID = trim($request->input('cord_id'));
$phone = trim($request->input('phone'));
$address = trim($request->input('address'));
$description = trim($request->input('description'));
// $image = array_get($allInputs, 'image');
$validation = Validator::make($allInputs, [
'user_id' => 'required',
'cord_id' => 'required',
'phone' => 'required',
'address' => 'required',
'description' => 'required',
]);
if ($validation->fails()) {
$response = (new CustomResponse())->validatemessage($validation->errors()->first());
} else {
$checkRecord = User::where('id', $userID)->get();
if (count($checkRecord) > 0) {
$complainModel = new Complains();
$complainModel->user_id = $userID;
$complainModel->cord_id = $cordID;
$complainModel->phone_no = $phone;
$complainModel->address = $address;
$complainModel->description = $description;
$saveData = $complainModel->save();
if ($saveData) {
if ($request->file('image')) {
$path = 'images/complain_images/';
// return response()->json(['check', 'In for loop']);
foreach ($request->file('image') as $image) {
$imageName = $this->uploadImage($image, $path);
$ImageSave = new ComplainImages();
$ImageSave->complain_id = $complainModel->id;
$ImageSave->image_url = url($path . $imageName);
$ImageSave->save();
}
}
$jsonobj = array(
'id' => $userID,
'name' => $cordID,
'email' => $phone,
'phone' => $address,
'description' => $description,
);
return Response::json([
'Exception' => "",
'status' => 200,
'error' => false,
'message' => "Complain Registered Successfully",
'data' => $jsonobj
]);
}
}else{
$response = (new CustomResponse())->failResponse('Invalid ID!');
}
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new CustomResponse())->queryexception($ex);
}
return $response;
}
public function uploadImage($image, $destinationPath)
{
$name = rand() . '.' . $image->getClientOriginalExtension();
$imageSave = $image->move($destinationPath, $name);
return $name;
}
There is a mistake in looping allImages. To save multiple images try below code
foreach($request->file('image') as $image)
{
$imageName = $this->uploadImage($image, $path);
// other code here
}
Check if you are reaching the loop
return response()->json(['check': 'In for loop'])

Categories