I am sending multiple user_id with form data in a flutter to PHP page but my PHP API did not see array or obj. I used this code for other projects it could work with javascript but I could no work with flutter. my flutter code=
Future<FormData> grupDuzenleData() async {
var token = await dbcon.tumKullanicilar();
if (grupPhoto != null) {
var fileName = path.basename(grupPhoto.path);
return FormData.fromMap(
{
'token': token.single['token'],
'group_description': grupHakkindaController.text ?? '',
'music_type': _currentType ?? '',
'city': _currentCity ?? '',
'group_name': grupAdiController.text ?? '',
'group_id': widget.BandID ?? '',
'id': uyeler,
'image':
await MultipartFile.fromFile(grupPhoto.path, filename: fileName)
},
);
} else {
return FormData.fromMap(
{
'token': token.single['token'],
'group_description': grupHakkindaController.text ?? '',
'music_type': _currentType ?? '',
'city': _currentCity ?? '',
'id': uyeler,
'group_id': widget.BandID ?? '',
'group_name': grupAdiController.text ?? '',
},
);
}
}
````````````````````````
**my other flutter functions**
````````````````````````
void grupDuzenleKaydet() async {
var dio = Dio();
Response response;
var formData = await grupDuzenleData();
response = await dio.post(
//"/upload",
ApiURL().URL('groupEdit'),
data: formData,
onSendProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + '%');
}
},
);
if (response.statusCode == 200) {
Map<String, dynamic> _responseMap = json.decode(response.data);
await showDialog(
context: context,
builder: (BuildContext context) {
return PlatformDuyarliAlertDialog(
baslik: '${_responseMap['sonuc']}',
icerik: '',
anaButonYazisi: '');
});
} else {
Map<String, dynamic> _responseMap = json.decode(response.data);
await showDialog(
context: context,
builder: (BuildContext context) {
return PlatformDuyarliAlertDialog(
baslik: '${_responseMap['sonuc']}',
icerik: '',
anaButonYazisi: '');
},
);
}
}
````````````````````````
My php code =
I get post from flutter.
````````````````````````
$token= #strip_tags($_POST["token"]);
$group_id= #strip_tags($_POST["group_id"]);
$user_id = #strip_tags($_POST["id"]);
$group_name = #strip_tags($_POST["group_name"]);
$image = #$_FILES["image"];
$description = strip_tags($_POST["group_description"]);
$music_type = strip_tags($_POST["music_type"]);
$city = strip_tags($_POST["city"]);
$user = new user();
$token_bak = #$user->userTokenCheck($token);
if($token=="" or !$token or $token_bak<=0){
$sonuc = "Lütfen Üye Girişi Yapın.";
$sonuclar = array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} elseif ($group_name=="" or !$group_name) {
$sonuc = "Lütfen Grup Adını Girin.";
$sonuclar = array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} elseif ($description=="" or !$description) {
$sonuc = "Lütfen Grup Açıklamasını Girin.";
$sonuclar = array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} elseif ($music_type=="" or !$music_type or $music_type=="0") {
$sonuc = "Lütfen Grubun Genelde Çaldığı Müzik Türünü Seçin.";
$sonuclar = array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} elseif ($city=="" or !$city) {
$sonuc = "Lütfen Grubun Genelde Sahne Aldığı Şehiri Seçin.";
$sonuclar = array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} else {
if($image!=""){
if(isset($_FILES['image'])){
$hata = $_FILES['image']['error'];
if($hata != 0) {
echo 'Yüklenirken bir hata gerçekleşmiş.';
} else {
$tip = $_FILES['image']['type'];
$isim = $_FILES['image']['name'];
$uzanti = explode('.', $isim);
$uzanti = $uzanti[count($uzanti)-1];
$uzanti_bak=fileTypeControl($uzanti);
$tip_bak=fileTypeControl2($tip);
if($uzanti_bak==1) {
$sonuc="Yalnızca Fotoğraf Yükleyebilirsiniz (jpg,jpeg,png).";
$sonuclar= array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} elseif ($tip_bak==1) {
$sonuc="Yalnızca Türünde Fotoğraf Yükleyebilirsiniz (jpg,jpeg,png).";
$sonuclar= array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
} else {
$dosya = $_FILES['image']['tmp_name'];
copy($dosya, '../uploads/group_images/' . $_FILES['image']['name']);
$avatar2='uploads/group_images/'.$_FILES['image']['name'].'';
}
}
}
} else {
$avatar2="";
}
if(isset($user_id) AND count($user_id)>0){
for ($i=0; $i <= count($user_id); $i++){
$user_id_ekle = $user_id[$i];
$ekle = new GroupMemberAdd($user_id_ekle, $group_id);
}
}
$sonuc = "$user_id[0] ve $user_id[1]";
$sonuclar = array("kod"=>"1","sonuc"=>$sonuc);
echo json_encode_tr($sonuclar);
new GroupEdit($group_id, $token, $group_name, $description, $avatar2, $music_type, $city);
}
Very interesting my user_id is not come to be array or object
my english is very bad i am sory
SOLVED
İ used explode function after i did foreach. it solves. Thank you all.
Related
i need to pass data with video that i wan upload but i don't know how to do that just like these data i need to pass it with the video to the php page
var data = {
"fileInput": videoFile.path,
"titleInput": titleController.text,
"descriptionInput": descriptionController.text,
"privacyInput": selectedCategorise.value,
"categoryInput": listcategory.map((e) => {e['name']}),
};
I know how to pass it on without a video like this function i pass the email and password
`signin() async {
var formdata = formstatesignin.currentState;
if (formdata.validate()) {
formdata.save();
var data = {"email": email.text, "password": password.text};
var url = "http://10.0.2.2/mobtech2/login.php";
var response = await http.post(url, body: data);
var responsebody = jsonDecode(response.body);
if (responsebody['status'] == "success") {
savePref(responsebody['username'], responsebody['email'],
responsebody['id']);
Navigator.of(context).pushNamed("homepage");
} else {
Navigator.of(context).pop();
}
} else {
print("Not vaild");
}
}`
this is the function that i wan pass data to it
`Future uploadVideo(File videoFile) async {
var uri = Uri.parse("http://10.0.2.2/videoTube/file_upload.php");
var request = new http.MultipartRequest("POST", uri);
var multipartFile =
await http.MultipartFile.fromPath("video", videoFile.path);
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
//final response = await http.post(uri, body: data);
if (response.statusCode == 200) {
print("Video uploaded");
} else {
print("Video upload failed");
}
}`
this code for class processing in php
`<?php
include "config.php";
if (!isset($_POST["video"])) {
echo "No video sent to page";
exit();
}
// 1) create file Uplaod Data
$videoUploadData = new VideoUploadData(
$_FILES["video"],
$_POST["titleInput"],
$_POST["descriptionInput"],
$_POST["privacyInput"],
$_POST["categoryInput"],
"REPLACE-THIS"
);
// 2) Process video data (upload)
$videoProcessor = new VideoProcessor($con);
$wasSuccessful = $videoProcessor->upload($videoUploadData);
?>`
this code for class VideoUploadData in php
`<?php
class VideoUploadData{
public $videoDataArray, $title, $description, $privacy, $category, $uploadedBy;
public function __construct($videoDataArray, $title, $description, $privacy, $category, $uploadedBy) {
$this->videoDataArray = $videoDataArray;
$this->title = $title;
$this->description = $description;
$this->privacy = $privacy;
$this->category = $category;
$this->uploadedBy = $uploadedBy;
}
}
?>`
this code for class VideoProcessor in php
`<?php
class VideoProcessor{
private $con;
private $sizeLimit = 500000000;
private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
public function __construct($con) {
$this->con = $con;
}
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if (!$isValidData) {
return false;
}
if (move_uploaded_file($videoData["video"]["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".mp4";
if (!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed";
return false;
}
}
}
private function processData($videoData, $filePath) {
$videoType = pathInfo($filePath, PATHINFO_EXTENSION);
if (!$this->isValidSize($videoData)) {
echo "File too large. Can't be more than" . $this->sizeLimit . " bytes";
return false;
}
else if (!$this->isValidType($videoType)) {
echo "Invalid file type";
return false;
}
else if ($this->hasError($videoData)) {
echo "Error code: " . $videoData["error"];
return false;
}
return true;
}
private function isValidSize($data) {
return $data["size"] <= $this->sizeLimit;
}
private function isValidType($type) {
$lowercased = strtolower($type);
return in_array($lowercased, $this->allowedTypes);
}
private function hasError($data) {
return $data["error"] != 0;
}
private function insertVideoData($uploadData, $filePath){}
}
?>`
yes you can upload a video with discription like name and title use dio package
this is an example i use to upload a video with some discription to my server backend use the MultipartFile
when you use the function _upload(video1) i pass the video as an argument but you can do it other way if you want i also set the progress indicator for the video upload progress.
// create listing,post and upload video to the server
void _upload(video1) async {
// get variables from shared preferences
token = await SharedPreferencesProvider.getUserToken();
userId = await SharedPreferencesProvider.getUserId();
// api to upload video
// Post a video to
var url = 'https://example.com/api/v1/video';
var video1Path;
if (video1 == null) {
return;
} else {
video1Path = await MultipartFile.fromFile(video1.path);
}
FormData data = FormData.fromMap({
"title": title,
"products": "1",
"description": description,
"category_id": categoryId,
"category_name": categoryName,
"longitude": _longitude,
"latitude": _latitude,
"video1": video1Path,
});
Dio dio = new Dio();
dio.options.headers["Authorization"] = "Bearer $token";
dio.post(url, data: data, onSendProgress: (int sent, int total) {
setState(() {
_isUploading = true;
// show a progress %
progressString ='uploading :' + ((sent / total) * 100).toStringAsFixed(0) + "%";
if ( ((sent / total) * 100).toStringAsFixed(0) == '100'){
progressString = 'Saving...';
}
//progressString = ((sent / total) * 100).toStringAsFixed(0) + "%";
});
}).then((response) async => {
setState(() {
progressString = DemoLocalizations.of(context).uploadCompleted;
}),
print(response),
//after successful product post we redirect to(Main page)
goHome()
})
.catchError((error) => print(error));
}
I use Yii2-advanced-app(2.0.15) and i need to do the logon operation with OTP.
With the cell number and password, everything is correct and the cookie is correct but when I use an opt, no value is created for the cookie.
My ajax code:
$("#m-sendCode__form-submit").click(function() {
$(this).attr('disabled','true');
let mobile = $('#mobile').val();
let csrfToken = $('meta[name="csrf-token"]').attr("content");
let rememberMe = $("#remember2").prop('checked');
// console.log(rememberMe);
$.ajax({
url: '/loginbysms',
method: 'POST',
data: {
_csrfFrontend: csrfToken,
phone: phone,
rememberMe: rememberMe
},
timeout: 6000
})
.done(function(data) {
let response = JSON.parse(data);
// console.log(data);
if (response.sent === 1){
$.ajax({
url: '/loginbysms',
method: 'POST',
data: {
_csrfFrontend: csrfToken,
verify: verify,
// rememberMe: rememberMe
},
})
.done(function(data) {
let s = JSON.parse(data);
if (s.status === 1){
window.location.href = '/';
}
});
}
})
.fail(function(error)){
console.log(error);
});
});
And my controller is:
public function actionLoginbysms()
{
$dataAjax = Yii::$app->request->post();
$session = Yii::$app->session;
if(isset($dataAjax)) {
if (isset($dataAjax['phone']) && !empty($dataAjax['phone'])) {
$phone = $dataAjax['phone'];
$user = User::findByPhone2($phone);
$sendSMS = new SendSMS();
if ($sendSMS->SendSMS($user->user_otp, $phone)) {
echo json_encode(['sent' => 1]);
exit;
} else {
echo json_encode(['sent' => 0]);
exit;
}
}
if(isset($dataAjax['verify]) && !empty($dataAjax['verfy'])){
$authorizedUser = User::findByOtp($session-
>get('user_phone'), $dataAjax['verify']);
if (isset($authorizedUser) && !empty($authorizedUser)) {
Yii::$app->user->login($authorizedUser, 3600 * 24 *
30)
echo json_encode(['status' => 1]);
exit;
}
}
}
}
When everything is true and the code is sent correctly by the user, the user enters the home page correctly but no value for the cookie is saved.
Please tell me the mistake.
The controller should be changed as follows:
public function actionLoginbysms()
{
$dataAjax = Yii::$app->request->post();
$session = Yii::$app->session;
if(Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
if (isset($dataAjax['phone']) && !empty($dataAjax['phone'])) {
$mobile = $dataAjax['phone'];
$user = User::findByPhone2($phone);
if ($user) {
unset($dataAjax['phone']);
$numbers = range(10000, 99999);
shuffle($numbers);
$session->set('user_phone', $phone);
if (isset($dataAjax['rememberMe']) && !empty($dataAjax['rememberMe'])
&& ($dataAjax['rememberMe'] == true)) {
$session->set('rememberMe', 'yes');
unset($dataAjax['rememberMe']);
}
$user->user_otp = $numbers[0];
$user->save();
try {
$sendSMS = new SendSMS();
$sendSMS->SendSMS($user->user_otp, $phone);
} catch (\Throwable $e) {
return [
'sent' => 0
];
}
return [
'sent' => 1
];
} else {
return ['user_not_found' => 1];
}
}
else if (isset($dataAjax['verify']) && !empty($dataAjax['verify'])) {
if ($session->isActive && $session->has('user_phone')) {
$authorizedUser = User::findByOtp($session->get('user_phone'), $dataAjax['verify']);
if (isset($authorizedUser) && !empty($authorizedUser)) {
unset($dataAjax['verify']);
$session->remove('user_phone');
$authorizedUser->user_otp = '';
$authorizedUser->save();
if(Yii::$app->user->login($authorizedUser, 3600 * 24 * 30)) {
return ['authenticationSuccess' => 1];
}
}
}
return ['authenticationSuccess' => 0];
}
}
}
As #rob006 said, we should not use exit.
With the help of Yii::#app->response->format = Response::FORMAT_JSON, everything works fine
Hi im creating a project in laravel 4.2 that uploads different files (e.g Pdf and images) in specific folders about 8 or 9 folders to be exact i just try the do a if statement but dont know what happend but its not working and there are no error displayed when i execute the code. please help me work this code or do you have any idea to simplify my code TIA!
Here's my code in my controller
public function upload()
{
$finame = Input::get('name');
$ftype = Input::get('type');
$username = Input::get('user');
$desc = Input::get('desc');
$date = Input::get('date');
$upload = Input::file('file');
$add = Files::upload2($finame,$ftype,$username,$desc,$date,$upload);
if ($add == true && $ftype == "pf") {
$upload -> move(public_path('pf'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} elseif ($add == true && $ftype == "sf") {
$upload -> move(public_path('sf'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} } elseif ($add == true && $ftype == "gale") {
$upload -> move(public_path('gale'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} } elseif ($add == true && $ftype == "advisory") {
$upload -> move(public_path('advisory'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} else {
return Redirect::back()->with('message', 'error|Error');
}
}
And my code in model:
public static function upload2($finame,$ftype,$username,$desc,$date,$upload)
{
$files = new self;
$files->file_name = $finame;
$files->file_type = $ftype;
$files->username = $username;
$files->description = $desc;
$files->date = $date;
$files->upload = $upload->getClientOriginalName();
try {
$files->save();
} catch (Exception $e) {
dd($e);
}
}
and in the view add this script:
<script>
var form = document.getElementById('upload');
var request = new XMLHttpRequest();
form.addEventListener('submit', function(e){
e.preventDefault();
var formdata = new FormData(form);
request.open('post', '/upload');
request.addEventListener("load", transferComplete);
request.send(formdata);
});
function transferComplete(data){
response = JSON.parse(data.currentTarget.response);
if(response.success){
document.getElementById('message').innerHTML = "File Successfully Uploaded!";
}
}
</script>
Im trying to convert some of my PHP functions to mongodb, but cant figure it out, could someone help me out?
PHP function applications:
function applications($gangId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `status`='avaliable' and `gangid`='$gangId'");
return ($applications ? $applications : false);
}
my attempt on function applications:
gangshema.methods.applications(thisid) {
// some sort of callback?
db.gang_applications.find({status:avaliable, gangid: thisid}, function(err, cursor) {
if (cursor != 0) {
console.log(cursor);
}
});
}
PHP function application_done
function application_done($applicationId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `id`='$applicationId'")->row();
return ($applications->status == 'avaliable' ? false : true);
}
my attempt on function application_done
gangshema.methods.application_done(applicationid) {
db.gang_applications.find({id:applicationid}, function(err,cursor) {
// return ($applications->status == 'avaliable' ? false : true);
});
}
but my main consern is a function called accept_applications. I have no clue on how to do this part, including calling other functions for their response.
function accept_application($userid,$applicationId) {
$box = 'failure';
if (empty($applicationId)) {
$message = "applicationId is empty";
} elseif ($this->application_done($applicationId)) {
$message = "Already registred!";
} else {
$application = $this->getApplication($applicationId);
$test = true;
if(!($test)) {
$message = "false test";
} else {
$this->db->query("UPDATE `gang_applications` SET `status`='accepted', `by`='$userid' where `id`='$applicationId'");
$this->gangs->add_member($application->userid,'gang','member',$application->gangid);
$message = "Accept!";
}
}
return $message;
}
Using this at the beginning of the Node.js script:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
First snippet:
function applications($gangId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `status`='avaliable' and `gangid`='$gangId'");
return ($applications ? $applications : false);
}
becomes:
var findApplications = function(db, gangId) {
var cursor = db.collection('gang_application').find({
"status": "available"
"gangId": gangId
});
var results = [];
cursor.each(function(err, doc) {
if (err) console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
results.push(doc);
}
});
return results;
};
Second snippet:
function application_done($applicationId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `id`='$applicationId'")->row();
return ($applications->status == 'avaliable' ? false : true);
}
becomes:
function applications(gangId) {
db.gang_application
}
var applicationsDone = function(db, applicationId) {
var cursor = db.collection('gang_application').find({
"id": applicationId
});
var results = [];
cursor.each(function(err, doc) {
if (err) {
console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
results.push(doc.status);
}
});
return results;
};
Call both as follows:
MongoClient.connect(url, function(err, db) {
if (!db) {
console.log("Database did not connect.");
}
else {
findApplications(db, "102"); // Replace "102" with gangId
applicationsDone(db, "104"); // Replace "104" with applicationId
}
});
EDIT per comments, here's how to include a callback:
// Note extra `callback` parameter
var applicationsDone = function(db, applicationId, callback) {
var cursor = db.collection('gang_application').findOne({
"id": applicationId
});
cursor.each(function(err, doc) {
if (err) {
console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
return (doc.status == "available");
}
});
};
To call:
MongoClient.connect(url, function(err, db) {
if (!db) {
console.log("Database did not connect.");
}
else {
var callback = function(doc) { console.log(doc.status); };
applicationsDone(db, "104", callback);
}
});
EDIT Third snippet:
function accept_application($userid, $applicationId) {
$box = 'failure';
if (empty($applicationId)) {
$message = "applicationId is empty";
} elseif ($this->application_done($applicationId)) {
$message = "Already registred!";
} else {
$application = $this->getApplication($applicationId);
$test = true;
if(!($test)) {
$message = "false test";
} else {
$this->db->query("UPDATE `gang_applications` SET `status`='accepted', `by`='$userid' where `id`='$applicationId'");
$this->gangs->add_member($application->userid,'gang','member',$application->gangid);
$message = "Accept!";
}
}
return $message;
}
becomes this. Note some changes to the functions above to get this to work, such as returning an array of documents from applications, and using .findOne() for applicationDone():
function acceptApplication(userId, applicationId) {
if (!applicationId) return "No application ID";
if (applicationDone(db, applicationId)) return "Application already submitted.";
// Left out `if (!$test)`
db.gang_applications.update({
"id": applicationId,
"userId": userId
}, {
"status": "accepted"
}, upsert: false);
// $this->gangs->add_member($application->userid,'gang','member',$application->gangid);
return "Accepted!";
}
I am working on some code and i have scraped together the following some from stackoverflow and some from my old code. Any way, I am trying to just have the file parsed and processed without actually displaying its content untell a later stage.
There is the PHP:
$c = 0;
if($fp = fopen($newname,"r"))
{
while (($line = fgets($fp)) !== false)
{
//CHECK STRING TO SEE IF IT CONTAINS AN EMAIL
$checkResult = $this->checkCSVContentForEmail($line,$c);//$content
if(!empty($checkResult))
{
if($checkResult == TRUE && is_bool($checkResult) == true)
{
$this->contactsAddedCounter += 1;
}
elseif(is_string($checkResult))
{
$errLine .= '
<p> CheckResult: '.$checkResult.' Line number: '.$c.' does not have an email</p>';
array_push($this->LogError_contactsUpload, $errLine);
}
}
else
{
$errLine = "<p>Line number: ".$c." contain's an empty string</p><br>\n";
array_push($this->LogError_contactsUpload, $errLine);
}
$c++;
}
}
fclose($fp);
I have spend the whole day yesterday coding through all the involved code - functions and all but nothing should be doing any displaying but i still get the follwing displayed,
The unwanted output:
Array ( [0] => " [1] => [2] => [3] => [4] => Normal"" [5] => ""False"" [6] => [7] => [8] => ""Normal""";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; )
of-course this is displayed repeatedly for each line read.
Any help on what may be causing this?
The rest of the code involved in processing:
//Check line for Email Method
public function checkCSVContentForEmail($csvLine, $lineNum)
{
if(!empty($csvLine))
{
$partedCSV = explode(',',$csvLine);
if(!empty($partedCSV[57]))
{
$csvEmail = $partedCSV[57];
if(!empty($csvEmail))
{
if($Result = $this->checkEmail($csvEmail, $lineNum))
{
//convert csv line into sql statement
$csv2sqlInsertMultiLine = '(';
$csvTosql = '';
foreach($partedCSV as $csvContent)
{
$str = strip_tags($csvContent);
$letters = array('"', "'");
$Quotes = array('', ' ');
$strN = str_replace($letters, $Quotes, $str);
$letters = array('(', ")");
$Quotes = array('', '');
$c2s_str = str_replace($letters, $Quotes, $strN);
$csvTosql[] .= $c2s_str;
}
//(4,5,6);
$theSQL = implode(',',$csvTosql);
$csv2sqlInsertMultiLine .= $theSQL;
$csv2sqlInsertMultiLine .= '),';
array_push($this->csv2sqlInsertMultiLine, $csv2sqlInsertMultiLine);
return $Result;
}
}
}
else
{
$show = 'No Entry for Email address field - WILL NOT BE ADDED TO DATABASE! '.print_r($partedCSV);
return $show;
}
}
else
{
$show = 'This line is empty';
return $show;
}
}
//Validate Email Method
public function checkEmail($email, $row)
{
if(!empty($email))
{
$str = strip_tags($email);
$letters = array('"', "'");
$Quotes = array('', ' ');
$em = str_replace($letters, $Quotes, $str);
if(!empty($em) or $em !=' ')
{
$check = preg_match('/^\S+#[\w\d.-]{2,}\.[\w]{2,6}$/iU', $em) ? TRUE : FALSE;
if($check == TRUE)
{
$this->contactEmail[$row] = $em;//array_push();
return TRUE;
}
}
else
{
$msg = 'There is no email passed in: '.$em.' <br>Our check resulted in: '.$check;
return $msg;
}
}
else
{
$msg = 'There is no email passed in: '.$email.' <br>Our check resulted in: '.$check;
return $msg;
}
}
The JQuery
// Upload Contacts
function uploadContacts()
{
var obj = '#upImprtFile';
var file_data = $k('#ContactsImprt').prop('files')[0];
var form_data = new FormData();
form_data.append("action", "uploadContacts");
form_data.append("upImprtFile", "submit");
form_data.append("ContactsImprt", file_data);
$k.ajax({
url: 'inc/runUtilities.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data)
{
$k('#doUpload').html(data).fadeIn('slow');
}
});
}
See the following lines inside checkCSVContentForEmail method.
else
{
$show = 'No Entry for Email address field - WILL NOT BE ADDED TO DATABASE! '.print_r($partedCSV);
return $show;
}
Use of print_r must be causing the output.