add timestamp to images within array - php

i have a php code that works great everything is fine. all images are uploadet to server and also store info in database. BUT i have decided to add time to each uploaded file right before file extension and also want to store that information in database.
This is my code:
<?php
function jaunProd() {
include 'database.php';
$message = '';
if (isset($_POST['jaunProdPoga'])) {
if(!empty($_POST['prod_vards']) && !empty($_POST['kat_id']) && !empty($_POST['subkat_id']) && !empty($_POST['prod_apraksts']) ){
$prod_vards = $_POST['prod_vards'];
$kat_id = $_POST['kat_id'];
$subkat_id = $_POST['subkat_id'];
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for ($i=0; $i <count($tmp_name_array); $i++){
move_uploaded_file($tmp_name_array[$i],'img/prod_img/'.time().$name_array[$i]);
}
$prod_kods = $_POST['prod_kods'];
$prod_cena = $_POST['prod_cena'];
$prod_apraksts = $_POST['prod_apraksts'];
$stmt=$conn->prepare("INSERT INTO produkti (prod_vards, kat_id, subkat_id, prod_img1, prod_img2, prod_img3, prod_img4, prod_img5, prod_kods, prod_cena, prod_apraksts) VALUES ('$prod_vards', '$kat_id', '$subkat_id', '$name_array[0]', '$name_array[1]', '$name_array[2]', '$name_array[3]', '$name_array[4]', '$prod_kods', '$prod_cena', '$prod_apraksts')");
if($stmt->execute()){
$message = '<p class="green">Produkts pievienots </p>';
} else {
$message = '<p class="red">SEIT LAIKA MIR KLIASHF </p>';
}
} else {
$message = '<p class="red">Lauki ar * nedrīkst būt tukši! </p>';
}
}
echo $message;
}
?>
Here move_uploaded_file($tmp_name_array[$i],'img/prod_img/'.time().$name_array[$i]);
i add time to file but this adds to front of file, but how to add after name and before extension.
And also i dont know how to store that dynamical info in database.
Thanks for help.

<?php
$ImageName = str_replace(' ', '-', strtolower($_FILES['myfile']['name']));
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.', '', $ImageExt);
$ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName .time(). '.' . $ImageExt;
move_uploaded_file($tmp_name_array[$i],'img/prod_img/'.$NewImageName);
?>

Related

laravel saving images start with comma

I have implemented dropzone js on my laravel project but af facing one issue on saving the images on the database
,/uploads/products/27/607f0fc0942b0_1618939840_fc3cde370d846c4d14b0200a29e9206f.png,/uploads/products/27/607f0fc0945e8_1618939840_copy-space-with-opened-quran_23-2148214357.jpg,/uploads/products/27/607f0fc09474d_1618939840_1 (1).jpg
the issue is the images start with a comma which is wrong and it must be after the image for example
image1.png,image2.png
Here is my Controller
$product_images = json_decode($request->product_images[0],true);
$images = [];
$path = "";
$productsPath = 'uploads/products/';
$productPath = 'uploads/products/'.$request->product_id;
if(!file_exists($productsPath)){
mkdir($productsPath);
}
if (!file_exists($productPath)) {
mkdir($productPath, 0777,true);
}
foreach($product_images as $img){
$file = $img['name'];
// $extension = $img->guessExtension();
$filename = uniqid() .'_'. time() .'_'. $file;
$img = explode(',',$img['file'])[1];
$img = str_replace('', '+', $img);
$data = base64_decode($img);
$file = $productPath .'/'. $filename;
$success = file_put_contents($file, $data);
// dd($file);
$images[] = '/'. $file;
}
// Update Product Information On "products" table
$product = Product::where('id', $request->product_id)->first();
$product->created_by = auth()->user()->id;
$product->name = request('name_en');
$product->name_ar = request('name_ar');
$product->description = request('description_en'); // Must be moved to "product_information"
$product->description_ar = request('description_ar'); // Must be moved to "product_information"
$product->youtube = request('youtube'); // Must be moved to "product_information"
$product->youtube_ar = request('youtube_ar'); // Must be moved to "product_information"
$product->slug = slugify($request->name_en, 'Product', '', '');
// $product->image = request('name_en');
$product->brand_id = request('brand');
$product->status = request('status');
$data = explode(',' ,$product->image);
$data = array_merge($data,$images);
$remove_images = json_decode($request->removed_images, true);
$temp = [];
$i = 0;
foreach($data as $key => $imag){
$i = $i + 1;
if(!empty($remove_images) && in_array($imag, $remove_images)){
if (file_exists($productPath .'/'. $imag)) {
unlink($productPath .'/'. $imag);
}
}else{
if($i < 8)
$temp[] = $imag;
}
}
$product->image = implode($temp, ',');
// dd (explode(',' ,$product->image));
$product->save();
thank you
use implode like this
implode(',', $temp);

file_put_contents multiple image upload through API in PHP

I am trying to upload multiple images through a PHP API.
When uploading, the data sending returns success, but it only uploads the names of the images to the Database and the files are not saved on the server side.
I tried to specify separate paths to decode, and then I used the file_put_contents function, but nothing uploads correctly to the server.
if($_SERVER['REQUEST_METHOD']=='POST'){
$pic = $_POST['pic'];
$random = random_word(20);
$path = "grocery/item_img/".$random.".jpg";
$actualpath = "$random.jpg";
$actualpath1 = "$random1.jpg";
$actualpath2 = "$random2.jpg";
$sql = "INSERT INTO item (`pic`, `pic1`, `pic2`)
VALUES (NULL, '$actualpath', '$actualpath1', '$actualpath2')";
class emp{}
if(mysqli_query($koneksi,$sql)){
foreach ($_POST['pic'] as $name) {
file_put_contents($path, $name);
}
echo json_encode(array( 'success' => 1,'message'=>'Item Added Successfully'));
}
else{
echo json_encode(array( 'success' => 0,'message'=>'Failed to Add Item Image'));
}
}
function random_word($id = 20){
$pool = '1234567890abcdefghijkmnpqrstuvwxyz';
$word = '';
for ($i = 0; $i < $id; $i++){
$word .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $word;
SOLVED
foreach gives Invalid argument supplied
when edits it to
foreach ((array) $pic as $image) {
...
}
error gone but still no uploads
then tried
move_uploaded_file($_FILES["pic"]["tmp_name"], $path1);
give error of :
Undefined index: pic
then edits to :
if (isset($_FILES['foto'])) {
move_uploaded_file($_FILES["foto"]["tmp_name"], $path1); }
error gone but won't upload
tried to edit the file_put_contents
to the param of pic1
it uploaded the second pic ,,,
so below is the working code which uploads the three images while storing their paths to the DB
anyway to make it neat while working
if($_SERVER['REQUEST_METHOD']=='POST'){
$pic = $_POST['pic'];
$pic1 = $_POST['pic1'];
$pic2 = $_POST['pic2'];
$random = random_word(20);
$random1 = random_word(20);
$random2 = random_word(20);
$path = "../item_img/".$random.".jpg";
$actualpath = "$random.jpg";
$actualpath1 = "$random1.jpg";
$actualpath2 = "$random2.jpg";
//upload files
$path1 = '../item_img/'.$actualpath;
$path2 = '../item_img/'.$actualpath1;
$path3 = '../item_img/'.$actualpath2;
$sql = "INSERT INTO item (`pic`, `pic1`, `pic2`)
VALUES (NULL, '$actualpath', '$actualpath1', '$actualpath2')";
class emp{}
if(mysqli_query($koneksi,$sql)){
file_put_contents($path1,base64_decode($pic));
file_put_contents($path2,base64_decode($pic1));
file_put_contents($path3,base64_decode($pic2));
}
echo json_encode(array( 'success' => 1,'message'=>'Item Added Successfully'));
}
else{
echo json_encode(array( 'success' => 0,'message'=>'Failed to Add Item Image'));
}
}
function random_word($id = 20){
$pool = '1234567890abcdefghijkmnpqrstuvwxyz';
$word = '';
for ($i = 0; $i < $id; $i++){
$word .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $word;

Uploading files and folders in a course programatically in Moodle

I need to upload files and folders into a course in moodle from a zip file, I have been searching and I found how to upload files. I try to upload, and the files are uploaded correctly into the database and in the file repository, but this files are not showed in the course when I enter to the course.
The code below is what I trying
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$context = context_course::instance($courseid);
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $context->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
I try to upload the files manually through the website and I've noticed that the folders ara created in another table called mdl_folder or in the table called mdl_file, but i don't know how do that and the best way to create and relate folders with files programatically for then displayed in the website well.
So if anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.
Thanks in advance.
I found a solution that works for me, I don't know if it is the most appropriate or not, if someone can take a look and tell me if it is correct or not, or what changes could make would be grateful.
The solution i found is:
Create or get it back the folder who will contain the files
Upload the files
Code:
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$folder = get_folder($courseid, 'Upload Test');
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $folder->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
And the function to create or get it back the folder is:
function get_folder($courseid, $resource_name) {
global $DB, $CFG;
//Comprobamos si la carpeta ya existe ya existe
$sql = "SELECT cm.id as cmid FROM {course_modules} cm, {folder} res
WHERE res.name = '" . $resource_name . "'
AND cm.course = " . $courseid . "
AND cm.instance = res.id";
if (! $coursemodule = $DB->get_record_sql($sql)) {
require_once($CFG->dirroot.'/course/lib.php');
echo "\tCreate new folder\n";
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
// get module id
$module = $DB->get_record('modules', array('name' => 'folder'), '*', MUST_EXIST);
// get course section
/*course_create_sections_if_missing($course->id, 0);
$modinfo = get_fast_modinfo($course->id);
$cw = $modinfo->get_section_info(0);
echo "section id: " . $cw->id;*/
$sectionid = $DB->get_record('course_sections', array('course' => $course->id, 'name' => 'Recursos'), '*', MUST_EXIST);
$folder_data = new stdClass();
$folder_data->course = $course->id;
$folder_data->name = $resource_name;
$folder_data->intro = '<p>'.$resource_name.'</p>';
$folder_data->introformat = 1;
$folder_data->revision = 1;
$folder_data->timemodified = time();
$folder_data->display = 0;
$folder_data->showexpanded = 1;
$folder_data->showdownloadfolder = 1;
$folder_id = $DB->insert_record('folder', $folder_data);
echo "folder id: " . $folder_id;
// add course module
$cm = new stdClass();
$cm->course = $courseid;
$cm->module = $module->id; // should be retrieved from mdl_modules
$cm->instance = $folder_id; // from mdl_resource
$cm->section = $sectionid->id; // from mdl_course_sections
$cm->visible = 1;
$cm->visibleold = 1;
$cm->showavailability = 1;
$cm->added = time();
$cmid = $DB->insert_record('course_modules', $cm);
// add module to course section so it'll be visible
if ($DB->record_exists('course_sections', array('course' => $courseid, 'section' => 1))) {
$sectionid = $DB->get_record('course_sections', array('course' => $courseid, 'section' => 1));
// if sequence is not empty, add another course_module id
if (!empty($sectionid->sequence)) {
$sequence = $sectionid->sequence . ',' . $cmid;
} else {
// if sequence is empty, add course_module id
$sequence = $cmid;
}
$course_section = new stdClass();
$course_section->id = $sectionid->id;
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->update_record('course_sections', $course_section);
} else {
$sequence = $cmid;
$course_section = new stdClass();
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->insert_record('course_sections', $course_section);
}
rebuild_course_cache($courseid, true);
// get context again, this time with all resources present
$context = get_folder($courseid, $resource_name);
return $context;
} else {
$context = context_module::instance($coursemodule->cmid);
return $context;
}
} // get_folder

Strict standard error in PHP

I've looked at similar posts here but couldn't crack a solution. I'm getting the Strict Standards: Only variables should be passed by reference error here on the strtolower($file['name']))), line. Tried hours now looking for a solution but couldn't figure out how to correct. Can you highlight where I've gone wrong?
Note: Code Edited as per #Kolink's suggestion below:
<?php
require_once 'upload_config.php';
$mydirectory = myUploadDir();
$uploaded_file_counter = 0;
$UploadLimit = $_POST['counter'];
for ($i = 0; $i <= $UploadLimit; $i++) {
$file_tag = 'filename' . $i;
$filename = $_FILES[$file_tag]['name'];
if ($filename != null) {
$rand = time();
$str = "$rand$filename";
// set folder name in here.
$filedir = myUploadDir();
//change the string format.
$string = $filedir . $str;
$patterns[0] = "/ /";
$patterns[1] = "/ /";
$patterns[1] = "/ /";
$replacements[1] = "_";
$dirname = strtolower(preg_replace($patterns, $replacements, $string));
//end of changing string format
//checking the permitted file types
if ($check_file_extentions) {
$allowedExtensions = allowedfiles();
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
/*if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) */
if (!in_array(array_reverse(explode(".", strtolower($file['name'])))[0], $allowedExtensions)) {
$fileUploadPermission = 0;
} else {
$fileUploadPermission = 1;
}
}
}
} else {
$fileUploadPermission = 1;
}
//end of checking the permitted file types
if ($fileUploadPermission) {
if (move_uploaded_file($_FILES[$file_tag]['tmp_name'], $dirname)) {
echo "<p>"; ?>
<div><?php echo "<img style='height:100px;width:200px' src='$dirname'>"; ?></div> <?php
echo "</p>";
$uploaded_file_counter += 1;
}
}
}
}
if ($uploaded_file_counter == 0) {
echo "<br /> <b style='font-weight:bold;color:red'>Opss! Please select an image file<b>";
} else {
echo "<br /> <b>You request " . $i . " image files to upload and " . $uploaded_file_counter . " files uploaded sucessfully</b>";
}
?>
end takes its argument by reference, since it modifies the original array by moving its internal pointer.
Since you appear to be using PHP 5.4, you can do this instead to get the last one:
if( !in_array(array_reverse(explode(".",strtolower($file['name'])))[0],$allowedExtensions))
That said, it's probably better to do it in several steps for readability:
$parts = explode(".",strtolower($file['name']));
$extension = $parts[count($parts)-1];
if( !in_array($extension,$allowedExtensions)) {

Codeigniter - The same md5 name on every upload

I have this annoying problem:
Below you will see my messy upload script in which, whenever I upload a video file, I use a md5 function to name it so there are no video files with the same names in my database/folder.
The problem is that when I upload a given file multiple times to the database, it gets stored with the same md5 file name every time. I would really appreciate it if you could help me fix this little bug. I may be tired or something. I tried a hundred different solutions, and nothing fixed it.
Here is my mess:
<?php
class Upload_model extends CI_Model {
var $gallery_path;
var $videos_path;
var $thumbnail;
var $video_name;
var $upload_data;
var $file_name;
var $name;
var $videos_folder = "http://localhost/upload/videos/";
//////////////////////////////
function Upload_model() {
parent::__construct();
$this->videos_path = realpath(APPPATH . '..\videos');
// $this->returnFromDatabase();
}
function do_upload() {
$name = $_FILES['userfile']['name']; // get file name from form
$fileNameParts = explode(".", $name); // explode file name to two part
$fileExtension = end($fileNameParts); // give extension
$fileExtension = strtolower($fileExtension); // convert to lower case
$encripted_pic_name = md5($name) . "." . $fileExtension; // new file name
$config['file_name'] = $encripted_pic_name; //set file name
$config = array(
'allowed_types' => 'avi|mp4|flw|mov',
'upload_path' => $this->videos_path,
'file_name' => $encripted_pic_name
);
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$this->upload_data = $this->upload->data(); //Returns array of containing all of the data related to the file you uploaded.
$this->file_name = $this->upload_data['file_name'];
$this->getThumbImage('C:\\xampp\\htdocs\\upload\\videos\\' . $encripted_pic_name);
$insert_data = array(
'name' => $encripted_pic_name,
'path' => 'C:\\xampp\\htdocs\\upload\\videos\\' . $encripted_pic_name,
'thumb_path' => 'C:\\xampp\\htdocs\\upload\\videos\\' . $encripted_pic_name . "_t.jpeg",
'uploaded_by' => 'admin'
);
$this->db->insert('videos', $insert_data); //load array to database
redirect('/welcome');
}
}
function getVideoInformation($videoPath) {
$movie = new ffmpeg_movie($videoPath, false);
$this->videoDuration = $movie->getDuration();
$this->frameCount = $movie->getFrameCount();
$this->frameRate = $movie->getFrameRate();
$this->videoTitle = $movie->getTitle();
$this->author = $movie->getAuthor();
$this->copyright = $movie->getCopyright();
$this->frameHeight = $movie->getFrameHeight();
$this->frameWidth = $movie->getFrameWidth();
$this->pixelFormat = $movie->getPixelFormat();
$this->bitRate = $movie->getVideoBitRate();
$this->videoCodec = $movie->getVideoCodec();
$this->audioCodec = $movie->getAudioCodec();
$this->hasAudio = $movie->hasAudio();
$this->audSampleRate = $movie->getAudioSampleRate();
$this->audBitRate = $movie->getAudioBitRate();
}
function getAudioInformation($videoPath) {
$movie = new ffmpeg_movie($videoPath, false);
$this->audioDuration = $movie->getDuration();
$this->frameCount = $movie->getFrameCount();
$this->frameRate = $movie->getFrameRate();
$this->audioTitle = $movie->getTitle();
$this->author = $movie->getAuthor();
$this->copyright = $movie->getCopyright();
$this->artist = $movie->getArtist();
$this->track = $movie->getTrackNumber();
$this->bitRate = $movie->getBitRate();
$this->audioChannels = $movie->getAudioChannels();
$this->audioCodec = $movie->getAudioCodec();
$this->audSampleRate = $movie->getAudioSampleRate();
$this->audBitRate = $movie->getAudioBitRate();
}
function getThumbImage($videoPath) {
$movie = new ffmpeg_movie($videoPath, false);
$this->videoDuration = $movie->getDuration();
$this->frameCount = $movie->getFrameCount();
$this->frameRate = $movie->getFrameRate();
$this->videoTitle = $movie->getTitle();
$this->author = $movie->getAuthor();
$this->copyright = $movie->getCopyright();
$this->frameHeight = $movie->getFrameHeight();
$this->frameWidth = $movie->getFrameWidth();
$capPos = ceil($this->frameCount / 4);
if ($this->frameWidth > 120) {
$cropWidth = ceil(($this->frameWidth - 120) / 2);
} else {
$cropWidth = 0;
}
if ($this->frameHeight > 90) {
$cropHeight = ceil(($this->frameHeight - 90) / 2);
} else {
$cropHeight = 0;
}
if ($cropWidth % 2 != 0) {
$cropWidth = $cropWidth - 1;
}
if ($cropHeight % 2 != 0) {
$cropHeight = $cropHeight - 1;
}
$frameObject = $movie->getFrame($capPos);
if ($frameObject) {
$imageName = $this->file_name . "_t.jpeg";
$tmbPath = "C:\\xampp\\htdocs\\upload\\videos\\" . $imageName;
$frameObject->resize(120, 90, 0, 0, 0, 0);
imagejpeg($frameObject->toGDImage(), $tmbPath);
} else {
$imageName = "";
}
return $imageName;
}
}
For what matters, CI's upload class has a property called encrypt_name. You can set it to true and have your filename encrypted by default without you doing something else. Take a look: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Also, since you are using CI, please use the Upload Class, don't write your own when the one provided from CI is so easy to use.
md5 will always return the same value when used on the same string, so uploading the file with the same name will end up with the same hash, add a random string to the file name
$encripted_pic_name = md5(microtime() . $name) . '.' . $fileExtension
You also need to be aware that clashes can happen with md5() where two different strings will have the same output. I wouldn't worry about this too much though for your needs.
You'll need to attach some random characters to the name before you md5 it (though even then it'll still have the chance of a duplicate name).
E.g:
$encripted_pic_name = md5($name . $randomStringHere) . "." . $fileExtension; // new file name
md5 will always give the same output for the same input, so if you upload the same file twice, then yes, you have already used that hash.
If you just want random names, then you don't even need to use MD5 and could just dynamically create a random string everytime a file is uploaded (a, b, c, etc to z, then aa, ab, ac, etc).
If the file name is same then it will return the same md5 hash
For this you have to encrypt unique name or number
You can use
$encripted_pic_name = md5(strtotime()) . "." . $fileExtension; // new file name
or
$encripted_pic_name = md5(uniqid()) . "." . $fileExtension; // new file name

Categories