Call to a member function getClientOriginalExtension() on string - php

In my laravel controller when i try to upload image i get this error..
My I Know what the problem is
This is inside my controller
$image = $request['images'];
if ($image)
{
$imgfile = $request['images'];
$imgpath = 'uploads/users/images/'.$user->id;
File::makeDirectory($imgpath, $mode = 0777, true, true);
$imgDestinationPath = $imgpath.'/'; // upload folder in public directory
$ext1 = $imgfile->getClientOriginalExtension();
$filename1 = uniqid('vid_').'.'.$ext1;
$usuccess = $imgfile->move($imgDestinationPath, $filename1);
}
This is my jquery code my form id is update profile and i get all the field values by its name
$("#updateprofile").on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var myData = {
name: $(this).find("[name='name']").val(),
gender:$(this).find("[name='gender']").val(),
lastname:$(this).find("[name='lastname']").val(),
email:$(this).find("[name='email']").val(),
mobile:$(this).find("[name='mobile']").val(),
address:$(this).find("[name='address']").val(),
city: $(this).find("[name='city']").val(),
state:$(this).find("[name='state']").val(),
country:$(this).find("[name='country']").val(),
pin:$(this).find("[name='pin']").val(),
images: document.getElementById('imageToUpload').files[0],
}
console.log("data", myData);
$.ajax({
type: "PUT",
url: url,
dataType: 'JSON',
data: myData,
success: function(data) {
console.log(data);
//alert("Profile update successfully")
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
alert("das");
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});

Try this (assuming your form input's id and name value is images),
if($request->hasFile('images')) {
$imgfile = Input::file('images');
$imgpath = 'uploads/users/images/'.$user->id;
File::makeDirectory($imgpath, $mode = 0777, true, true);
$imgDestinationPath = $imgpath.'/';
$ext1 = $imgfile->getClientOriginalExtension();
$filename1 = uniqid('vid_').'.'.$ext1;
$usuccess = $imgfile->move($imgDestinationPath, $filename1);
}
In your jQuery code :
try changeing
images: document.getElementById('imageToUpload').files[0],
to
images: document.getElementById('imageToUpload').files[0].value,
and as you are uploading files through your form yous should specify contentType: 'multipart/form-data', in your ajax call

Related

Upload image to server using Jquery

I need your help to upload an image on my server.
Indeed, with this code, I have an array(0) {} response while the values are well populated.
No image is uploaded... thank you for your help, here are my two files:
index.php
<input type="file" id="txt_image_user" name="txt_image_user" accept="image/*" required >
<script>
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: {fd:fd, handle:handle, reference:reference},
contentType: false,
processData: false,
error: function (e) {console.log('Ajax Error', e);alert('Erreur Ajax');},
success: function(response){
console.log(response);
},
});
}
</script>
_upload-image.php
<?php require($_SERVER['DOCUMENT_ROOT']."/ew-includes/config.php");
var_dump($_POST);
$PathImage = $_SERVER['DOCUMENT_ROOT']."/ew-content/images/images-clients/";
if (!is_dir($PathImage)) {mkdir($PathImage);}
if(isset($_POST["handle"])) {
if(is_array($_POST["handle"])) {$handle = implode(", ", $_POST['handle']);} else {$handle = $_POST['handle'];}
if(is_array($_POST["reference"])) {$reference = implode(", ", $_POST['reference']);} else {$reference = $_POST['reference'];}
$img_name = $_FILES["txt_image_user"]["name"];
$img_tmp = $_FILES["txt_image_user"]["tmp_name"];
$filename = "ew".$reference."_".$handle."_".date("YmdHi");
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
$photo = $filename.".".$ext;
$resultat = move_uploaded_file($img_tmp, $PathImage.$photo);
echo "img_name: ".$img_name."\n";
echo "img_tmp: ".$img_tmp."\n";
echo "ext: ".$ext."\n";
echo "photo: ".$photo."\n";
echo "resultat: ".$resultat."\n";
}
Thanks for your help.
I specify that I am new in Jquery
That's not the way to use FormData it should be the data. You can append other values to it.
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
fd.append('handle', handle);
fd.append('reference', reference);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: fd,
contentType: false,
processData: false,
error: function(e) {
console.log('Ajax Error', e);
alert('Erreur Ajax');
},
success: function(response) {
console.log(response);
},
});
}

Php ajax multiple file upload with new array

its mine upload html code ;
<div class="col-xs-12">
<label for="upload" class="btn btn-sm btn-outline green btn-block">
<i class="fa fa-upload"></i>
upload
</label><input type="file" multiple id="upload" class="hidden"/>
</div>
its file element on change method
$("#upload").change(function (event) {
var files = event.target.files;
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
});
Ajax code when click upload button..
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles', file);
});
myFormData.append('a', 1);
$.ajax({
url: 'ajax/upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
And Last of code is php code;
$myFiles=$_FILES["myFiles"];
for($i=0; $i<count($myFiles); $i++){
$target_path = "uploaded_files/";
print_r($myFiles[$i]);
echo $myFiles[$i]["tmp_name"]."\n";
$ext = explode('.',$myFiles[$i]["tmp_name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
$sonuc=move_uploaded_file($myFiles[$i], $target_path);
if(move_uploaded_file($myFiles[$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
i get this message when run the code. There was an error uploading the file, please try again! I want to upload multiple file to server with array. Why i need an array because I delete some file in array and i want to upload last result of array to server.
What is my fault ? I didn't find anything.
The $myFiles[$i] is a null object.
You are appending single file using this line of code myFormData.append('myFiles', file);. You have to use this code myFormData.append('myFiles[]', file); to send multiple file. Below is the code that i have implemented which can upload multiple files.
in your script place below code.
<script type="text/javascript">
$("#upload").change(function (event) {
var files = event.target.files;
var uploadingFile = [];
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles[]', file);
});
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
});
</script>
And in your upload php code place below code.
$target_path = "uploaded_files/";
$myFiles=$_FILES["myFiles"];
if(count($myFiles['name']) > 1){
$total = count($myFiles['name']);
for($i=0; $i<$total; $i++){
$ext = explode('.',$myFiles["name"][$i]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"][$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error multiple uploading the file, please try again! \n";
}
}
} else {
$ext = explode('.',$myFiles["name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
try this
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
$("#finalupload").uploadFile({
url: "badocumentsupload",
id: "test",
formData: {
action: 'uploadfile',
_token: tempcsrf,
baid:curaddbaid
},
fileName: "myfile",
returnType: "json",
showDelete: true,
showDone: false,
showProgress: true,
onSuccess: function (files, data, xhr) {
},
deleteCallback: function (data, pd) {
$.post("finaluploaddeletecustom", {
action: "delete_current",
row_id: data['DBID'],
filetodelete: data['uploadedfile'],
_token: tempcsrf
},
function (resp, textStatus, jqXHR) {
reloaddatatable_final();
});
pd.statusbar.hide();//You choice to hide/not.
}
});
As you are getting null object, I don't think that you files are being submitted.I think you have not used enctype="multipart/form-data" in form tag. I think if you add this to form like below, it would work.
<form action="youraction" method="post" enctype="multipart/form-data">
</form>

AJAX/Laravel Multiple File Uploads

I'm trying to upload multiple files from a drag/drop event using jQuery/AJAX/Laravel.
MY DROP EVENT:
$( document ).on('drop dragleave', '.file-drag', function(e){
$(this).removeClass('drop-ready');
if(e.originalEvent.dataTransfer.files.length) {
e.preventDefault();
e.stopPropagation();
if (e.type === "drop") {
var files = e.originalEvent.dataTransfer.files;
AjaxFileUpload(files)
}
}
});
MY UPLOAD SCRIPT:
function AjaxFileUpload(files){
console.log(files);
//Start appending the files to the FormData object.
var formData = new FormData;
formData.append('_token', CSRF_TOKEN);
for(var i = 0; i < files.length; i++){
formData.append(files[i].name, files[i])
}
console.log(formData.entries());
$.ajax({
//Server script/controller to process the upload
url: 'upload',
type: 'POST',
// Form data
data: formData,
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Error logging
error: function(jqXHR, textStatus, errorThrown){
console.log(JSON.stringify(jqXHR));
console.log('AJAX Error: ' + textStatus + ": " + errorThrown);
},
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
success: function(data){
console.log(data);
}
});
}
MY CONTROLLER CODE:
class UploadsController extends Controller
{
public function UploadFiles(Request $request){
return $request->all();
}
}
I THINK my images are getting to the server side, as when I return the request object, I get the following in console:
Thus, the CSRF token is getting through, and the images (I think?) are getting through. My problem from here is accessing the files with PHP and storing them via ->store();.
In the countless examples online/documentation, they typically use something along the lines of:
$path = $request->photo->store('images');
However, I don't understand the 'photo' aspect of this. What if a video or a PDF is uploaded? I basically don't understand how I am to access the different parts of the request object. Documentation on Laravel site is pretty sparse for this and only gives an example using 'photo' of which it never explains.
Figured it out.
In my uploadscontroller:
class UploadsController extends Controller
{
public function UploadFiles(Request $request){
$arr = [];
foreach($request->all() as $file){
if(is_file($file)){
$string = str_random(16);
$ext = $file->guessExtension();
$file_name = $string . '.' . $ext;
$filepath = 'uploads/' . Auth::user()->username . '/' . $file_name;
$file->storeAs(('uploads/' . Auth::user()->username), $file_name);
array_push($arr, [$file_name, $filepath]);
}
}
return $arr;
}
}
This took me a while but I finally got a working solution. I'm using Dropzone so the list of file objects is returned by getAcceptedFiles() but it should be the same concept for you. I'm also attaching the files to an existing form.
Upload:
var formElement = document.getElementById("addForm");
var formData = new FormData(formElement);
// Attach uploaded files to form submission
var files = myDZ.getAcceptedFiles(); // using Dropzone
for (var i = files.length - 1; i >= 0; i--) {
formData.append('files[]', files[i]);
}
$.ajax({
url: 'home/',
data: formData,
processData: false,
contentType: false,
timeout: 1000,
type: 'POST',
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken,
},
success: function(){
...
},
error: function (jqXHR, textStatus) {
...
}
});
Controller:
foreach($request->only('files') as $files){
foreach ($files as $file) {
if(is_file($file)) { // not sure this is needed
$fname = $file->getClientOriginalName();
$fpath = $file->store('docs'); // path to file
}
}
}
Dropzone Script:
Dropzone.autoDiscover = false;
var myDZ = new Dropzone("#my-dropzone", {
url: "/home/files",
maxFilesize: 5,
maxFiles: 5,
addRemoveLinks: true,
dictDefaultMessage: 'Drop files here or click to upload <br> (max: 5 files)',
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken
},
});
Regarding the examples found in Laravel's documentation, 'photo' is simply making use of a magic method to reference a file uploaded with a name of 'photo'. You can replace 'photo' with whatever your specific file names is/are. Specific functions capable of being called on your uploaded files can be found here.

How to extract values from jquery `formData` to insert into Mysql?

My code is about submitting a multipart form, through $.ajax, which is successfully doing it & upon json_encode in submit.php , its giving me this :
{"success":"Image was submitted","formData":{"fb_link":"https:\/\/www.google.mv\/",
"show_fb":"1",
"filenames":[".\/uploads\/homepage-header-social-icons\/27.jpg"]}}
Can someone explain me, in submit.php, how can i extract values from formData, to store in mysql table ? I have tried, so many things including :
$fb_link = formData['fb_link'];
$show_fb = formData['show_fb'];
and
$arr = json_encode($data);
$fb_link=$arr['fb_link'];
and
$fb_link = REQUEST['fb_link'];
$show_fb = REQUEST['show_fb'];
but, nothing seems to work ? Any Guesses ?
Thanks
update :
JS code on parent-page is :
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form#upload_form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
//var data = new FormData($(this)[0]);
$.ajax({
url: 'jquery_upload_form_submit.php?files=files',
type: 'POST',
data: data,
//data: {data, var1:"fb_link" , var2:"show_fb"},
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'jquery_upload_form_submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
UPDATE CODE OF - submit.php :
<?php
// Here we add server side validation and better error handling :)
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = './uploads/homepage-header-social-icons/';
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename($file['name']))) {
$files[] = $uploaddir . $file['name'];
//$files = $uploaddir . $file['name'];
}
else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your image-files') : array('files' => $files);
}
else {
$data = array(
'success' => 'Image was submitted',
'formData' => $_POST
);
}
echo json_encode($data);
?>
If you're using POST method in ajax, then you can access those data in PHP.
print_r($_POST);
Form submit using ajax.
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
You can access the data on PHP
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
If you want to access file object, you need to use $_FILES
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];
This problem is different in terms that :
1. Its sending MULTIPLE files, to upload
2. Contains a SELECT
3. Contains an INPUT
So, images are serialized & sent via GET . And, rest FORM data is being sent via POST. So Solution is :
var data = new FormData($(this)[0]);
inside : function uploadFiles(event){}
And in submit.php :
print_r($_POST);
print_r($_GET);
die();
This will give you both values. Then comment these & as per the Code, make these changes :
$filename_wpath = serialize($files);
$fb_link = $_POST['fb_link'];
$show_fb = $_POST['show_fb'];
$sql = "INSERT INTO `tblbasicheader`(fldFB_image, fldFB_link, fldHideShow)
VALUES('$filename_wpath','$fb_link','$show_fb')";
mysqli_query($db_conx, $sql);
Works like Charm ! :)

Upload Image and insert in Database MySQl withAjax

i m user JQuery mobile and PHP and Ajax to upload Image and insert it in Database,but i have a probleme in insert the name of image in a database,the result in database is :"C:fakepathLighthouse.jpg",i would insert just the name of image after upload it.
Mu code in php
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
£fichier=basename($file['name'];
$uploaddir = 'photo/';
foreach($_FILES as $file)
{if(move_uploaded_file($file['tmp_name'], $uploaddir. $fichier)))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
my code script:
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
console.log('nom de l image:' + '&filenames[]=' + value);
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
my initial page(index.html)
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var latt = position.coords.latitude;
var lngg = position.coords.longitude;
var nom=$('input[id=nom]').val();
var photo= $('input[id=file_upload]').val();
var ville= $('input[id=ville]').val();
var pays= $('input[id=pays]').val();
long.value="Longitude: " + lngg;
lat.value="Latitude: " + latt;
//var adr="Sousse";
codeLatLng(latt, lngg);
// var adresse=codeLatLng(latt, lngg);
var sendAjax = $.ajax({
type: "POST",
url: 'api.php?rquest=insertMosque',
data: 'lat='+latt+'&lng='+lngg+'&nom='+nom+'&pays='+pays+'&ville='+ville+'&photo='+photo,
success: handleResponse
});
function handleResponse(){
$('#answer').get(0).innerHTML = sendAjax.responseText;
//console.log(data);
}
}
function errorFunction(){
alert("Geocoder failed");
}
}
code api.php
private function insertMosque() {
if ($this->get_request_method() != "POST") {
$this->response('', 406);
}
$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];
$photo=$_POST['photo'];
//$photo = addslashes($file['name']);
$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
if ($query) {
$data['success'] = 'Insertion avec success';
} else {
$data['errors'] = 'failed';
}
$this->response($this->json($data), 200);
}
You could use the explode function in your api.php to parse the filepath you are getting from POST:
$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];
//for example, say $_POST['photo'] = "C:/my/fake/directory/testfile.jpg"
$photopath = explode("/", $_POST['photo']);
//print_r($photopath) results in Array ( [0] => C: [1] => my [2] => fake [3] => directory [4] => testfile.jpg )
$photo = end($photopath); //gets last result in the array (your filename)
$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
Please note that this may not be the most efficient method of getting the filename from a path, and your delimiter ("/" in the example above) might need to change based on how you are getting your path. If you have any questions feel free to ask.

Categories