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));
}
Related
I have this Smart Webview I got on https://github.com/ which was great. Being Android newbie developer, I have been having issue trying to solve this problem. If I select image from the phone directory and send to the backend(PHP); everything worked fine: image is moved to the upload folder; but If I take picture using the Android camera, the image never send to folder but the name of the image is saves into the database.
MainActivity for image upload
// handling input[type="file"]
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
if(check_permission(2) && check_permission(3)) {
if (ASWP_FUPLOAD) {
asw_file_path = filePathCallback;
Intent takePictureIntent = null;
Intent takeVideoIntent = null;
if (ASWP_CAMUPLOAD) {
boolean includeVideo = false;
boolean includePhoto = false;
// Check the accept parameter to determine which intent(s) to include.
paramCheck:
for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
// Although it's an array, it still seems to be the whole value.
// Split it out into chunks so that we can detect multiple values.
String[] splitTypes = acceptTypes.split(", ?+");
for (String acceptType : splitTypes) {
switch (acceptType) {
case "*/*":
includePhoto = true;
includeVideo = true;
break paramCheck;
case "image/*":
includePhoto = true;
break;
case "video/*":
includeVideo = true;
break;
}
}
}
// If no `accept` parameter was specified, allow both photo and video.
if (fileChooserParams.getAcceptTypes().length == 0) {
includePhoto = true;
includeVideo = true;
}
if (includePhoto) {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = create_image();
takePictureIntent.putExtra("PhotoPath", asw_pcam_message);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
asw_pcam_message = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
}
if (includeVideo) {
takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File videoFile = null;
try {
videoFile = create_video();
} catch (IOException ex) {
Log.e(TAG, "Video file creation failed", ex);
}
if (videoFile != null) {
asw_vcam_message = "file:" + videoFile.getAbsolutePath();
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
} else {
takeVideoIntent = null;
}
}
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
if (!ASWP_ONLYCAM) {
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType(ASWV_F_TYPE);
if (ASWP_MULFILE) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
}
Intent[] intentArray;
if (takePictureIntent != null && takeVideoIntent != null) {
intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
} else if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else if (takeVideoIntent != null) {
intentArray = new Intent[]{takeVideoIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, asw_file_req);
}
return true;
}else{
get_file();
return false;
}
}
//Creating image file for upload
private File create_image() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".jpg", sd_directory);
}
//Creating video file for upload
private File create_video() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".3gp", sd_directory);
}
PHP that handles upload
if(isset($_FILES['photo'])){
$upload_dir = 'profile_img/'; // upload directory
$email = $_POST['email'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$imgType = $_FILES['photo']['type'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png'); // image extensions
$vid_extensions = array('avi', 'mp4', 'wav','3gp','AAC','flv','wmv'); // video extensions
$aud_extensions = array('mp3'); // audio extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($imgFile)){
$pic = $userpic;
}else{
$pic = '';
}
if(!empty($imgFile) && in_array($imgExt, $valid_extensions)){
move_uploaded_file($tmp_dir,$upload_dir.$pic);
}
if(!empty($imgFile) && in_array($imgExt, $vid_extensions)){
move_uploaded_file($tmp_dir,$video.$pic);
}
if(!empty($imgFile) && in_array($imgExt, $aud_extensions)){
move_uploaded_file($tmp_dir,$audio.$pic);
}
$query = mysqli_query($mysqli,"UPDATE customer_login SET img = '$pic' WHERE email='$email'");
if($query){
echo 1;
}else{
echo "Error occured: ".$mysqli->error;
}
}
Uri.fromFile(photoFile))
Since Android N/7 you cannot use a file uri.
It will produce a FileUriExposedException.
Use FileProvider.getUriForFile() instead to obtain a content scheme uri.
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.
I have a registration form which asks for details such as firstname, lastname, email, etc and it asks for uploading a pdf file at the end. I am not using any database, I am storing all the details in a json file using php in the server. I am able to store the data as well as the pdf file in the directory path, I cannot figure out how should I connect the pdf with the user details(i.e.how can I store the pdf so that it has a field in the json file so that when the next time user logs in, he should be able to see his pdf file).
Below is the php file to store the pdf file:
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
$userId = $_POST['userId'];
$type = $_POST['type'];
$model = array();
$uploaded = false;
$found = false;
$imgDir = 'data/transcripts/';
$users = json_decode(file_get_contents('../data/studentdata.json'));
switch ($type) {
case 'cis300':
$model = $users->cis300;
break;
case 'cis400':
$model = $users->cis400;
break;
case 'cis500':
$model = $users->cis500;
break;
}
if (isset($_FILES["file"]["name"])) {
foreach ($model as $key => $user) {
if ($user->id == $userId) {
$found = true;
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = str_replace(' ', '', ($user->firstname . $user->lastname)) . '-' . date('Y-m-d-h-m-s') . '.' . end($temp);
if (move_uploaded_file($_FILES["file"]["tmp_name"], '../data/transcripts/' . $newfilename)) {
unlink('../' . $user->tfile);
$uploaded = true;
$fileName = str_replace(' ', '', ($user->firstname . $user->lastname)) . $user->year;
$user->tfile = $imgDir . $newfilename;
echo json_encode(array('uploaded' => $uploaded, 'user' => $user));
} else {
echo json_encode(array('uploaded' => $uploaded, 'user' => array()));
}
break;
}
}
if ($found) {
unlink('../data/studentdata.json');
file_put_contents('../data/studentdata.json', json_encode($users, JSON_PRETTY_PRINT));
}
if (!$found) {
echo json_encode(array('uploaded' => $uploaded, 'user' => array()));
}
}
?>
Below is the angular js file where I have get requests and upload function:
csel.controller('studentController', function (AppServices, $rootScope, $scope, Upload, $http, $routeParams, $timeout, $location) {
$scope.formdata.tfile = function () {
if ($scope.forms.registerForm.file.$valid && $scope.formdata.file) {
$scope.upload($scope.formdata.file);
}
};
$scope.upload = function (file) {
file.upload = Upload.upload({
url: $rootScope.baseURL + 'php/uploadT.php',
data: {
file: file,
'userId': $scope.formdata.id,
'type': $scope.formdata.type
},
});
file.upload.then(function (response) {
$timeout(function () {
console.log("CAlled in Upload");
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
When I press upload the file, the file is uploaded, however the file path is stored in a different json object.
Thank you in advance!
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'm trying to develop a Php Photo Gallery only for my personal use and I put a Php System Rating using a modified script that I found on the web... all works fine except for one thing, I cannot stop users from posting several votes in the same day! I'd like that users vote the photos (several photos as well) but voting one time in the same day (one vote for each photo)... I post here the script that I have modified.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if ($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if ($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
} else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
if ($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
} else { # Create a new one if it doesn't
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1);
$this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']);
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
# ---
# end class
}
?>
ratings.js:
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings/ratings.php',
out_data,
function(INFO) {
$(widget).data('fsr', INFO);
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings/ratings.php',
clicked_data,
function(INFO) {
widget.data('fsr', INFO);
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes (' + exact + ' rating)' );
}
I tried to implement IP mechanism in ratings.php as below without lucky
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if ($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if ($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
} else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
if ($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
$this->data[$ID]['remote_ip'] = $_SERVER['REMOTE_ADDR'];
} else { # Create a new one if it doesn't
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
$this->data[$ID]['remote_ip'] = $_SERVER['REMOTE_ADDR'];
}
if ($this->data[$ID]['remote_ip'] != $_SERVER['REMOTE_ADDR']) {
$this->data[$ID]['dec_avg'] = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1);
$this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']);
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
# ---
# end class
}
?>
The simplest way is to notify in a data table who vote and which day.
For example : Toto vote on 2014-07-04, so he can't vote twice today.
In data table user you add a colum date to notify the last day of vote.
You can use cookies but it's very very ugly !