PHP file path updating after unlink the previous file - php

In my php file using file uploading control. After unlink previous file and update with new file it's not getting update with new image file. It's showing previous image in listing, when i refresh it's showing new image. Using both listing and update screen in single php file. I used the document cache clear. Even it's not working.
<?php
require_once("../config/config.php");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
<?php
require_once("../images.inc.php");
if(Tools::isLoggedIn('admin') == false)
{
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."index")));
}
$id_product = (Tools::getVar("id_product")) ? Tools::getVar("id_rpoduct") : 0;
$page = intval(Tools::getVar("page"));
$product = new Product($id_product);
if(Tools::isSubmit("OnSave"))
{
$id_product = Tools::getVar("id_product");
$product = new Product($id_product);
$product->name = Tools::getVar("name");
$product->id_category = Tools::getVar("id_category");
$product->short_description = Tools::getVar("short_description");
$product->code = Tools::getVar("code");
$product->weight = Tools::getVar("weight");
$product->price = Tools::getVar("price");
$product->size = Tools::getVar("size");
$product->meta_title = Tools::getVar("meta_title");
$product->meta_description = Tools::getVar("meta_description");
$product->meta_keyword = Tools::getVar("meta_keyword");
$product->status = Tools::getVar("status");
if(($product->name)=="")
{
$errors['err_name'] = "Name is required";
}
if(($product->short_description)=="")
{
$errors['err_short_description'] = "Description is required";
}//edit on
if($product->id_category <= 0)
{
$errors['err_id_category'] ="Parent Category is required";
}
if($product->code == '')
{
$errors['err_code'] ="Product Code is required";
}
if(sizeof($errors) == 0)
{
if($id_product) {
$product->date_upd = date('Y-m-d H:i:s');
if(isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL && $id_product) {
$postimage = $product->postImage($id_product);
}
if($product->update())
{
$redirect = array("template"=>ADMIN_URI."product");
$session->set("success","Product Updated Successfully");
Tools::redirectTo($link->rewrite_link($redirect));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
else {
$product->date_add = date('Y-m-d H:i:s');
$product->date_upd = date('Y-m-d H:i:s');
$id_product = $product->add(DB::RETURN_INSERT_ID);
if(isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL && $id_product) {
$product->postImage($id_product);
}
if($id_product){
$redirect = array("template"=>ADMIN_URI."product");
$session->set("success","Product Added Successfully");
Tools::redirectTo($link->rewrite_link($redirect));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
}
}
if(Tools::getVar('action') == 'delete' && Tools::getVar('id_product') )
{
$id_product = Tools::getVar('id_product');
$product = new Product($id_product);
if($product->delete()) {
$session->set("success","Product Deleted successfully");
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."product")));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
if(Tools::getVar('action') == "status_change" && Tools::getVar('id_product'))
{
$id_product = Tools::getVar('id_product');
$product = new Product($id_product);
$product->status =Tools::getVar("status");
$product->update();
$session->set("success","Status updated successfully");
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."product")));
}
require_once("header.php");
?>
My Image upload class like,
<?php
class Product extends ObjectModel
{
protected function uploadImage($id, $name, $dir, $ext = false)
{
if (isset($_FILES[$name]['tmp_name']) AND !empty($_FILES[$name]['tmp_name']))
{
// Delete old image
if (file_exists($dir.$id.'.'.$this->imageType)) {
$imagesTypes = $this->productImageTypes;
foreach ($imagesTypes AS $k => $imageType)
{
if (file_exists($dir.$id.'-'.stripslashes($imageType['name']).'.jpg'))
{
unlink($dir.$id.'-'.stripslashes($imageType['name']).'.jpg');
}
}
unlink($dir.$id.'.'.$this->imageType);
}
// Check image validity
if ($error = checkImage($_FILES[$name], $this->maxImageSize))
$_errors[] = $error;
elseif (!$tmpName = tempnam(TEMP_DIR, 'SST') OR !move_uploaded_file($_FILES[$name]['tmp_name'], $tmpName))
return false;
else
{
$_FILES[$name]['tmp_name'] = $tmpName;
// Copy new image
if (!imageResize($tmpName, $dir.$id.'.'.$this->imageType, NULL, NULL, ($ext ? $ext : $this->imageType)))
$_errors[] = Tools::displayError('An error occurred while uploading image.');
else {
$imagesTypes = $this->productImageTypes;
foreach ($imagesTypes AS $k => $imageType)
imageResize($dir.$id.'.jpg', $dir.$id.'-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height']));
}
if (sizeof($_errors))
return false;
else
{
unlink($tmpName);
return true;
}
return false;
}
}
return true;
}
}

Assuming that your browser is displaying a cached version of the image since your saving new data to the same file name, try appending a query string containing a randomized string or timestamp to the image url when generating the HTML to display it. Something like this:
PHP
$image_tag='<img src="image-file.jpg?t='.timestamp().'" />';
This should make the browser fetch a fresh version of the image instead of using it's cached version.

Related

Image taken from Android webview camera not saving to folder

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.

Update query not working if added the code to update image and pdf

Update query not working if added the code to upload image and pdf. I have the same code for insert and update except prepare and execute, insert query works very fine, update query doesn't. I have also included enctype="multipart/form-data" in the form so that I can get data from $_FILES as well. Moreover, I have used $_FILES['photo']['tmp_name'] and $_FILES['pdf']['tmp_name'] in order to move them using function move_uploaded_file move_uploaded_file($_FILES['photo']['tmp_name'], 'destination'); and move_uploaded_file($_FILES['pdf']['tmp_name'], 'destination');
function edit_profile($pid)
{
if($_SERVER['REQUEST_METHOD']=='POST')
{
echo "<pre>";
print_r($_POST);
print_r($_FILES);
echo "</pre>";
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$sel_post = $_POST['sel_post'];
$txt_post = $_POST['post'];
$post = "";
if(empty($txt_post))
{
$post = $sel_post;
}
else
{
$post = $this->add_new_post($txt_post);
}
if(empty($fullname) || empty($contact))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['photo']['name']))
{
$photo = $_FILES['photo'];
$allowed_ext = array('png','jpg', 'pdf','jpeg', 'bmp', 'gif');
$allowed_size = 20000000;
$tmp_photo = $photo['tmp_name'];
$photo_size = $photo['size'];
$photo_error = $photo['error'];
$photo_ext = explode('.',$photo['name']);
$photo_ext = strtolower(end($photo_ext));
if(in_array($photo_ext,$allowed_ext))
{
if($photo_size <= $allowed_size)
{
$photo_new_name = time()."_".uniqid('',true).'.'.$photo_ext;
$upload_destination = './cdn/uploads/profile/'.$photo_new_name;
if(move_uploaded_file($tmp_photo,$upload_destination))
{
$photo_to_db = $photo_new_name;
}
else
{
array_push($this->errors, STORAGE_ERROR);
return;
}
}
else
{
array_push($this->errors, $document_name.' : '.FILE_SIZE_ERROR);
return;
}
}
else
{
array_push($this->errors, $photo_ext.' : '.FILE_EXT_ERROR);
return;
}
}
if(!empty($_FILES['pdf']['name']))
{
$pdf = $_FILES['pdf'];
$allowed_pdf_ext = array('pdf');
$allowed_pdf_size = 20000000;
$tmp_pdf = $pdf['tmp_name'];
$pdf_size = $pdf['size'];
$pdf_error = $pdf['error'];
$pdf_ext = explode('.',$pdf['name']);
$pdf_ext = strtolower(end($pdf_ext));
if(in_array($pdf_ext,$allowed_pdf_ext))
{
if($photo_size <= $allowed_pdf_size)
{
$pdf_new_name = time()."_".uniqid('',true).'.'.$pdf_ext;
$upload_pdf_destination = './cdn/uploads/profile_pdf/'.$pdf_new_name;
if(move_uploaded_file($tmp_pdf,$upload_pdf_destination))
{
$pdf_to_db = $pdf_new_name;
}
else
{
array_push($this->errors, STORAGE_ERROR);
return;
}
}
else
{
array_push($this->errors, $document_name.' : '.FILE_SIZE_ERROR);
return;
}
}
else
{
array_push($this->errors, $photo_ext.' : '.FILE_EXT_ERROR);
return;
}
}
$statement = $this->db->prepare("UPDATE `profiles` SET `fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE `pid`=?");
if($statement->execute([$fullname,$email,$contact,$post,$pid, $pdf_to_db, $photo_to_db]))
{
ExitThis::send_to(URL.'profile/view_profile?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
}
The above code will return me to the view_profile page as if the update query worked properly, however, the data remains the same before the update -- no change.
Edit: After debugging $statement before executing it get this:
PDOStatement Object
(
[queryString] => UPDATE `profiles` SET `fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE `pid`=?
)
This issue is might be the wrong sequence of parameters passed, try by following sequence:
if($statement->execute([$fullname,$email,$contact,$post,$photo_to_db,$pdf_to_db,$pid]))
You pass variables to execute method using wrong order.
...db->prepare("UPDATE `profiles` SET `fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE `pid`=?");
And next you calls execute with these variables:
...->execute([$fullname,$email,$contact,$post,$pid, $pdf_to_db, $photo_to_db]))
Last 3 should be like $photo_to_db, $pdf_to_db, $pid.
You pass wrong pid, so that's why you don't see update result.
Also you can use named parameters: http://php.net/manual/en/pdostatement.execute.php#example-1072
$statement = $this->db->prepare("UPDATE `profiles` SET
`fullname`=?,`email`=?,`contact`=?,`post`=?, `photo`=?, `pdf`=? WHERE
`pid`=?");
if($statement->execute([$fullname,$email,$contact,$post,$photo_to_db
$pdf_to_db,$pid]))
{
ExitThis::send_to(URL.'profile/view_profile?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
remove $pid on your update statement and also check your parameters please try this code

How can I optimise sending push notification in CodeIgniter PHP?

Problem
I am trying to send push notification through PHP, to both Android and iOS, but I have lots of devices to send the notification, and you can see the code that it sends the notification to all of them in a loop. It's really not optimized as my dashboard gets stuck for more than a minute due to the running loop, also somehow it is not even sending a notification to all active accounts.
Can anyone here help me out?
Code
public function insert()
{
// Set the validation rules
$this->form_validation->set_rules('title', 'Title', 'required|trim');
// If the validation worked
if ($this->form_validation->run())
{
$get_post = $this->input->get_post(null,true);
$get_post['tags'] = is_array($this->input->get_post('tags')) ? $this->input->get_post('tags') : [];
if(count($get_post['tags']) == 0)
{
$_SESSION['msg_error'][] = "Tags is a required field";
redirect('admin/newsfeed/insert');
exit;
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$image = '';
# Try to upload file now
if ($this->upload->do_upload('image'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$image = $upload_detail['file_name'];
} else {
$uploaded_file_array = (isset($_FILES['image']) and $_FILES['image']['size'] > 0 and $_FILES['image']['error'] == 0) ? $_FILES['image'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = '*';
$config['encrypt_name'] = true;
$config['max_size'] = 51200; //KB
$this->upload->initialize($config);
$audio = '';
# Try to upload file now
if ($this->upload->do_upload('audio'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$audio = $upload_detail['file_name'];
}
else
{
$uploaded_file_array = (isset($_FILES['audio']) and $_FILES['audio']['size'] > 0 and $_FILES['audio']['error'] == 0) ? $_FILES['audio'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
$get_post['image'] = $image;
$get_post['audio'] = $audio;
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image){
redirect('admin/newsfeed/crop_image?id='.$id);
} else {
redirect('admin/newsfeed/');
}
}
}
$this->data['selected_page'] = 'newsfeed';
$this->load->view('admin/newsfeed_add', $this->data);
}
Description
The method is adding a newsfeed, its checks for the validations, then it inserts the feed to the db, once thats done, it sends out the notification to all devices.
Problematic Chunk
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image) {
redirect('admin/newsfeed/crop_image?id='.$id);
} else{
redirect('admin/newsfeed/');
}
}
Thank you in advance.

Laravel 4.2 Uploading file in specific folder

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>

exif_imagetype() [function.exif-imagetype]:

hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}

Categories