am trying to upload .mp4 files with php but it's not working. Here's the script:
PHP Class to handle the upload:
class CustomFileUpload
{
public static function upload($data)
{
$errors = [];
$response = [];
$file = htmlentities(trim($data['file']['name']), ENT_QUOTES, 'UTF-8');
$tmpDir = $data['file']['tmp_name'];
$fileSize = $data['file']['size'];
$fileExt = strtolower(pathinfo($file,PATHINFO_EXTENSION));
$validExtensions = ['mp3', 'mp4'];
$uploadDir = '';
if ($fileExt == "mp4") {
$uploadDir = './public/ex-media/videos/';
} elseif ($fileExt == "mp3") {
$uploadDir = './public/ex-media/audios/';
} else {
$errors['msg'] = 'file type not allowed.';
$response['status'] = 407;
$response['msg'] = "error";
$response['error'] = $errors;
return $response;
}
if(!in_array($fileExt,$validExtensions))
{
$errors['msg'] = "Invalid extension detected for selected image file, please use a supported image extension.";
$errors['ext-detected'] = $fileExt;
}
if(empty($errors))
{
$uuid = explode("-", $data['uuid']);
$fileNewName = $uuid[0]."-".time().".".$fileExt;
var_dump($tmpDir);
exit();
$moved = move_uploaded_file($tmpDir, $uploadDir.$fileNewName);
if ($moved) {
$response['status'] = 200;
$response['msg'] = "success";
$response['fileUrl'] = $fileNewName;
echo('heres ur newly uploaded file - '.$fileNewName);
exit();
return $response;
} else {
$response['status'] = 502;
$response['msg'] = "failed";
$response['error'] = "upload failed for UNKNOWN reasons!";
echo('error while uploading file - go to CustomFileUpload.php');
exit();
return $response;
}
}
else {
$response['status'] = 407;
$response['msg'] = "error";
$response['error'] = $errors;
return $response;
}
}
}
PHP Controller Action that calls the CustomFileUpload class:
public function uploadAction()
{
$response = ['status_code' => 404];
if ($this->getRequest()->isPost())
{
$data = $this->params()->fromPost();
$request = $this->getRequest();
$data = array_merge_recursive(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$fileUpload = CustomFileUpload::upload($data);
}
return new JsonModel($response);
}
If I upload an mp3 file, it works perfectly but for mp4, it's the opposite. So I tried to dump the content of the tmp_dir var_dump($tmpDir); exit(); as seen the CustomFileUpload class. After doing this, it turns out that the tmp_dir is empty for mp4 files which is not so for the mp3 files as seen in the screenshots below (taken from Postman).
tmp_dir IS NOT EMPTY for mp3 file:
enter image description here
tmp_dir IS EMPTY for mp3 file:
enter image description here
Please, how do I fix these?
Related
I would like to use the following class to resize my image before storing it on my server: https://www.verot.net/php_class_upload.htm?lang=en-GB
I have image data stored in a MySQL table encoded as base64.
So far I've gotten this far:
$data = $myBase64DataFromDb;
//if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
// $data = substr($data, strpos($data, ',') + 1);
// $type = strtolower($type[1]); // jpg, png, gif
// $data = base64_decode($data);
$path = '/img/put/here/';
// $filename = $data.'.'.$type;
// $handle = new upload($filename);
$handle = new upload($data);
$handle->file_max_size = '5000000';
$handle->image_resize = true;
$handle->image_x = 600;
$handle->image_ratio_y = true;
$handle->process($path);
if ($handle->processed) {
echo $filename;
$handle->clean();
} else {
echo 'error : ' . $handle->error;
}
// }
I keep getting error:
error : File not uploaded. Can't carry on a process.
What am I missing?
<?php ## Heading ##
require_once 'include/db_connection.php';
global $connection; $upload_path = 'uploads/';
//this is our upload folder
$server_ip = gethostbyname(gethostname());
//Getting the server ip
$upload_url = 'http://'.$server_ip.'/android_upload/'.$upload_path;
//upload url
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['caption'])) {
$caption = $_POST['caption'];
$fileinfo = pathinfo($_FILES['image']['name']);
//getting file info from the request
$extension = $fileinfo['extension'];
//getting the file extension
$file_url = $upload_url . getFileName() . '.' . $extension;
//file url to store in the database
$file_path = $upload_path . getFileName() . '.'. $extension;
//file path to upload in the server
$img_name = getFileName() . '.'. $extension;
//file name to store in the database
try{
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
//saving the file to the uploads folder;
//adding the path and name to database
$sql = "INSERT INTO photos(photo_name, photo_url, caption) ";
$sql .= "VALUES ('{$img_name}', '{$file_url}', '{$caption}');";
if(mysqli_query($connection,$sql)){
//filling response array with values
$response['error'] = false;
$response['photo_name'] = $img_name;
$response['photo_url'] = $file_url;
$response['caption'] = $caption;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//displaying the response
echo json_encode($response);
//closing the connection
mysqli_close($connection);
}else{ $response['error'] = true;
$response['message']='Please choose a file';
}
}
/* We are generating the file name so this method will return a file name
for the image to be uploaded */
function getFileName(){
global $connection;
$sql = "SELECT max(id) as id FROM photos";
$result = mysqli_fetch_array(mysqli_query($connection, $sql));
if($result['id']== null) return 1;
else return ++$result['id'];
mysqli_close($connection);
}
?>
Here is picture upload code and get response image url save your database. u hope you try this.
<?php
include('confi.php');
/**********MYSQL Settings****************/
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype)
{
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (isset($_FILES["file"]["name"])) {
$file_name=$_FILES["file"]["name"];
$temp_name=$_FILES["file"]["tmp_name"];
$imgtype=$_FILES["file"]["type"];
$ext= GetImageExtension($imgtype);
$imagename=date("m-Y")."-".rand().$_FILES['file']['name'];
$target_path ='images/'.$imagename;
if(move_uploaded_file($temp_name, $target_path)) {
$result = $url.'api/'.$target_path;
$json = array( "status" =>1,"file-url" => $result, "files" => $_FILES);
}else{
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
$json = array( "status" =>0, "error" => $_FILES['uploaded']);
}
else{
$json = array( "status" =>0,"files" => $_FILES);
}
}
}
else{
$json = array("status" =>0, "error" => "Problem occurred");
}
}else{
$json = array("status" => 0, "message" => "Request method is wrong!");
}
header('Content-type:application/json');
echo json_encode($json);
?>
I use Imagick to count the number of pages in my PDF which is uploaded by the client except that my var_dump does not return any results.
Here is my prestashop code from my ProductController.php controller for uploading files.
class ProductController extends ProductControllerCore
{
const CUSTOMIZATION_FILE_DIR = 'customizations';
protected function pictureUpload()
{
if (!($field_ids = $this->product->getCustomizationFieldIds()))
return false;
$authorized_file_fields = array();
foreach ($field_ids AS $field_id)
{
if ($field_id['type'] == Product::CUSTOMIZE_FILE)
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file' . (int)$field_id['id_customization_field'];
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES AS $field_name => $file)
{
if (in_array($field_name, $authorized_file_fields) AND isset($file['tmp_name']) AND !empty($file['tmp_name']))
{
// If there is an upload error, let the parent handle it
if ($file['error'] != UPLOAD_ERR_OK)
continue;
// If the file is not allowed, let the parent handle it
if (!$this->isUploadTypeAllowed($file))
continue;
// Unset the PDF to prevent the parent to handle this file
unset($_FILES[$field_name]);
// Create dir
mkdir(_PS_UPLOAD_DIR_ . ProductController::CUSTOMIZATION_FILE_DIR.'/'.$this->context->cart->id, 0777, true);
// Mark the file as a custom upload
$file_name = ProductController::CUSTOMIZATION_FILE_DIR.'/'.$this->context->cart->id.'/P'. md5(uniqid(rand(), true)).'.pdf';
$doc = exec("identify -format %n $file_name");
var_dump($doc);
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!move_uploaded_file($file['tmp_name'], $tmp_name))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Copy file to the upload dir
if (!copy($tmp_name, _PS_UPLOAD_DIR_.$file_name))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Chmod the new file
if (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Create a fake thumb to avoid error on delete, this hack avoids lots of core method override
file_put_contents(_PS_UPLOAD_DIR_ . $file_name . '_small', '');
chmod(_PS_UPLOAD_DIR_ . $file_name . '_small', 0777);
// Register the file
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
// Remove tmp file
unlink($tmp_name);
}
}
return parent::pictureUpload();
}
protected function isUploadTypeAllowed($file)
{
/* Detect mime content type */
$mime_type = false;
$types = array('application/pdf', 'application/zip'); // Extra mime types can be added here
if (function_exists('finfo_open'))
{
$finfo = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
}
elseif (function_exists('mime_content_type'))
{
$mime_type = mime_content_type($file['tmp_name']);
}
elseif (function_exists('exec'))
{
$mime_type = trim(exec('file -b --mime-type '.escapeshellarg($file['tmp_name'])));
}
if (empty($mime_type) || $mime_type == 'regular file')
{
$mime_type = $file['type'];
}
if (($pos = strpos($mime_type, ';')) !== false)
$mime_type = substr($mime_type, 0, $pos);
// is it allowed?
return $mime_type && in_array($mime_type, $types);
}
}
Thank you.
I have a two file upload control in my form one is for uploading a css file and other is for html file.
my css file name is style.css and html file name is test.html.
Both files are uploaded successfully but both takes a same name when it is uploaded. css file name is at the time of uploading is style.css and html is file name is also style.css.
css file uploading code is :
if(isset($_FILES['css_file']) AND $_FILES['css_file']['name'] != '') {
$xyz['upload_path'] = 'theme/'.$folder_name;
$xyz['allowed_types'] = 'css';
$xyz['overwrite'] = FALSE;
$xyz['file_name'] = $_FILES['css_file']['name'];
$this->load->library('upload', $xyz);
if (!$this->upload->do_upload('css_file')) {
echo $this->upload->display_errors();
}else{
$abc_array['file'] = $this->upload->data();
$array_rc['css_file'] = $abc_array['file']['file_name'];
}
}
html file uploading code is :
if(isset($_FILES['html_file']) AND $_FILES['html_file']['name'] != '') {
$abc['upload_path'] = 'theme/'.$folder_name;
$abc['allowed_types'] = 'html';
$abc['overwrite'] = FALSE;
$abc['file_name'] = $_FILES['html_file']['name'];
$this->load->library('upload', $abc);
if (!$this->upload->do_upload('html_file')) {
echo $this->upload->display_errors();
}else{
$xyz_array['file'] = $this->upload->data();
$array_rc['html_file'] = $xyz_array['file']['file_name'];
}
}
So how can i rename html file at the time of uploading ?
See if this helps you
$this->load->library("upload");
if(isset($_FILES['css_file']) AND $_FILES['css_file']['name'] != '')
{
$xyz['upload_path'] = 'theme/'.$folder_name;
$xyz['allowed_types'] = 'css';
$xyz['overwrite'] = FALSE;
$xyz['file_name'] = $_FILES['css_file']['name'];
$this->upload->initialize($xyz);
if (!$this->upload->do_upload('css_file'))
{
echo $this->upload->display_errors();
}
else
{
print_r($this->upload->data());
}
}
if(isset($_FILES['html_file']) AND $_FILES['html_file']['name'] != '')
{
$abc['upload_path'] = 'theme/'.$folder_name;
$abc['allowed_types'] = 'html';
$abc['overwrite'] = FALSE;
$abc['file_name'] = $_FILES['html_file']['name'];
$this->upload->initialize($abc);
if (!$this->upload->do_upload('html_file'))
{
echo $this->upload->display_errors();
}
else
{
print_r($this->upload->data());
}
}
Native
$config['encrypt_name'] = TRUE;
OR
$name = $_FILES["userfiles"]['name'];
$config['file_name'] = $name;
i am using CI 2.1.0 and mysql database for one of my projects. i am facing a problem with my image uploading method. the image i am uploading should be saved in uploads directory and create a thumbnail version of the image and the image path should be saved in database.
the code i have done works fine but there is one problem that when i upload an image, in the upload directory i get two copies of the same image and in the thumbs directory a single copy of the uploaded image. i want to have only one copy of the image instead of those two copies .
here is my code->
model:
function do_upload() //to upload images in upload directory
{
$i=$this->db->get('portfolio')->num_rows();
$i=$i+1;
$image_path=realpath(APPPATH . '../uploads');
$config=array(
'allowed_types'=>'jpeg|png|gif|jpg',
'upload_path'=>$image_path,
'max_size'=>2097152,
'file_name'=>'_'.$i.'_'
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config=array(
'source_image'=>$image_data['full_path'],
'new_image'=>$image_path.'/thumbs',
'maintain_ration'=>TRUE,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
if( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
return $image_data;
}
}
some please tell me why two copies of images are being uploaded.
there is anothe thing, i want images to be overwritten if an image with same name exists. i have changed the upload.php file inside system->libraries to this
public $overwrite = TRUE;
but it is not working. someone please help.
you are calling $this->upload->do_upload() twice ..
Please try this code
Warning : Untested
function do_upload()
{
$i=$this->db->get('portfolio')->num_rows();
$i=$i+1;
$image_path=realpath(APPPATH . '../uploads');
$config=array(
'allowed_types'=>'jpeg|png|gif|jpg',
'upload_path'=>$image_path,
'max_size'=>2097152,
'overwrite'=>TRUE,
'file_name'=>'_'.$i.'_'
);
$this->load->library('upload', $config);
if( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$image_data = $this->upload->data();
$config=array(
'source_image'=>$image_data['full_path'],
'new_image'=>$image_path.'/thumbs',
'maintain_ration'=>TRUE,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return $image_data;
}
}
I will give an alternate uploader class for handling file uploads properly. You can re use this code anywhere .
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>