Ajax image uploading and displaying - php

I am using php mysql and uploading image using ajax( jquery). The image is being uploaded successfully but is not being dispalyed immediately, on reloding the page it displaying correctly.
The upload and display are working when I am using this code..
<?php
// Set the upload folder path
$target_path = "uploads/";
// Set the new path with the file name
$target_path = $target_path . basename( $_FILES['myfile']['name']);
// Move the file to the upload folder
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
// print the new image path in the page, and this will recevie the javascripts 'response' variable
echo $target_path;
} else{
// Set default the image path if any error in upload.
echo "default.jpg";
}
?>
But instead of uploading the image to upload directory with the original name of the image which is being uploaded I want to change the name on upload to image01.jpg and if the image with this name is present then I want it to get replaced with the new one. For this I use this code...
<?php
// Set the upload folder path
$place_file="";
$target_path = "1/";
$target_path1 = "1/image01.jpg";
// Set the new path with the file name
$target_path = $target_path ."image01.jpg";
// Move the file to the upload folder
$place_file=move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path1);
echo $target_path;
?>
The image is uploding fine but it is not being displayed immediately but gets displayed on page refresh. It displays the previous image only and I think the replacing of image is causing a problem.
I am new in file uploading coding thats why having problem.
This js code uploads the image
new AjaxUpload(button,{
action: 'upload.php',
name: 'myfile',
onSubmit : function(file, ext){
spinner.css('display', 'block');
// you can disable upload button
this.disable();
},
onComplete: function(file, response){
button.stop(false,true).fadeOut(200);
spinner.css('display', 'none');
$('#profile_img').attr('src', response);
// enable upload button
this.enable();
}
});
The above php code was upload.php

Related

PHP 7 Imagick writeimage() path issue

I'm trying to create a simple thumbnail image and upload to server using imagick. The image is being selected via a form and I am able to get the thumb created via Imagick, however it is not saving to the right location.
When I use the below code, the image saves to the same directory as the page the code is on and includes the file path within the image name. For example "\images\myuploaded.jpg" as the file name.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$errors = array();
if(preg_match("!image!", $_FILES['image']['type'])){
$image = $_FILES['image']['tmp_name'];
$imagethumb = new Imagick("$image");
$imagethumb->setImageFormat("jpg");
$imagethumb->thumbnailImage(100, 0);
$imgpath = "\images\\".$_FILES['image']['name'];
$imagethumb->writeImage($imgpath);
$_SESSION['message']=$image;
}else{
$errors['image'] = "You must select a .png, .jpg, or .gif images file.";
$_SESSION['message']=$errors['image'];
}
}
Thanks for any help.
_t

How to render an image on a php page by dynamically taking the path returned on the same page from MySQL database

So i want my page to show the image whose path I am getting from the mysql database and displaying on the same screen. This is my code, I have tried everything, please let me know where I'm going wrong.
while ($row = mysqli_fetch_array($return_data)) {
echo "ID:".$row['demo_id']."<br>";
echo "Name: ".$row['demo_name']."<br>";
echo "Version: ".$row['demo_version']."<br>";
echo "Details: ".$row['demo_details']."<br>";
echo "File Link: ".$row['file']."<br>";
$new = $row['file'];
echo '<img src = \"$new\"/>';
}
mysqli_free_result($return_data);
echo "Data retrieved successfully!"."<br>";
?>
<img src = "<?php echo $new?>">
echo "File Link: " returns me the whole path of the uploaded file.
How do I render the image at that path in the same page?
neither of the image tags are working. Thanks in advance!
edit
File Link: C:/Apache24/htdocs/demo_webpages_project/neweruploads/footer.jpg
this is the path I get as an output.
Basically this is the folder where I have uploaded the image from another php file
<?php
//this module is used to temporarily store the uploaded file to the server
$target_dir = "random/"; //we randomly assign a value to the upload target directory
$target_file = $target_dir . basename($_FILES["image_file"]["name"]); /*here ["name"] is the original name of the file before it was updated
target file is assigned this name by appending it to the $targer_dir
now target_file is the uploaded file name along with the path*/
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);/*this returns various kind of info about the path for eg Directory, Basename
in our case it returns extension of the file*/
//this sub module is to check whether the file is really an image file
if(isset($_POST["submit"])) { //isset is used to confirm whether the value has actually being submitted
$check = getimagesize($_FILES["image_file"]["tmp_name"]);/*here ["tmp_name"] is the location of temporary file on server
getimagesize confirms image format by returning dimensions etc*/
if($check !== false) {
echo "A file is of an image format<br>";
}
else {
echo "The file is not an image!<br>";
}
}
//Test module to upload files to a destination directory and check whether they have been uploaded or not
if (is_uploaded_file($_FILES['image_file']['tmp_name']) && $_FILES['image_file']['error']==0) { /*code to check two things: 1. whether the file exists in the temp memory 2. whether the file has any error*/
$path = 'C:\Apache24\htdocs\demo_webpages_project\neweruploads\\' . $_FILES['image_file']['name']; /*this sets the destination directory(along with expected file name)*/
if (!file_exists($path)) { //if the file does not exists at that path
if (move_uploaded_file($_FILES['image_file']['tmp_name'], $path)) { //use the php file move function to move it
echo "The file was uploaded successfully."; //success
}
else {
echo "The file was not uploaded successfully."; //failure
}
}
else {
echo "File already exists. Please upload another file."; //detects existence of file with exact same name
}
}
else {
echo "The file was not uploaded successfully."; //if any problem with original uploading
echo "(Error Code:" . $_FILES['image_file']['error'] . ")";
}
?>
Does this help?
edit 2
http://localhost:8080/demo_webpages_project/download.php?project_name=footer&version=&submit=Search
this is my local directory path.
the solution you provided is allowing me to read images which are in the demo_webpages_project folder pointing directly there), not to neweruploads folder
If your uploaded files are stored in the neweruploads subdirectory, then replace this code:
$new = $row['file'];
echo '<img src = \"$new\"/>';
By this one :
$new = basename( $row['file'] ); // GET FILE NAME ONLY, GET RID OF PATH.
echo '<img src = \"neweruploads/$new\"/>'; // FILENAME WITH UPLOAD PATH.
▲

Get image from local path in php

I am working on a bulk upload project using excel sheet and using CakePHP 3.2 for writing application.
I have an excel sheet with a column to give image to be uploaded.
User have 3 choices to go with either
Upload images to a pre defined directory before bulk upload and give the name of the image in the cell and image will be automatically
selected from path.
Give the url of the image (http://website/path/image.jpg)
Give the path of the image if it is on local machine. Ex., C:\user\pictures\image.jpg if windows, and
/home/user/picture/image.jpg if linux
This is what I'm doing to save images
$p_image = $objWorksheet->getCellByColumnAndRow(30, $row)->getValue();
if (filter_var($p_image, FILTER_VALIDATE_URL)) {
// get image from url
$full_image_path = $p_image;
} else {
// get image from folder
$path = Configure::read('media.bulkUpload.pre.product');
// full path of the image from root directory
$full_image_path = $path . DS . $p_image;
}
$upload_path = Configure::read('media.upload') . DS . 'files' . DS;
// new name of image
$img_new_name = uniqid('img_').round(microtime(true) * 1000).rand(1,100000);
if ($full_image_path) {
// generate uuid directory name
$dir = Text::uuid();
// create new directory
mkdir($upload_path.$dir, 0777, true);
// save file
try {
$img = new \abeautifulsite\SimpleImage($full_image_path);
// save image of original size
$img->best_fit(850,1036)->save($upload_path.$dir.'/'.$img_new_name.'.jpg');
} catch(Exception $e) {
echo 'Error: '.$e->getMessage();
}
}
Image upload using url and pre ftp upload is working fine. But, how could I get image from the path of local system and then save them.
You can't do this without the users uploading the image themselves. You cannot retrieve a file from the client's filesystem from an external server where you run your php.

php move_uploaded_file() image permission issue

my code is successfully working for upload images. but problem is it fails to display uploaded images. i checked image path output is correct in html source view but image till not displaying. i think its a file permission issue. how can i upload these images with read write full permission so images can display properly.
if(isset($_POST["submit_img"])) {
$target_dir = "../assets/img/temp_img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$randstr = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 3);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_dir.$randstr))
{
$q =mysqli_query($conn,"INSERT INTO temp_img (product_img_url) VALUES ('$randstr')");
if ($q>0) {
echo "<br>The file has been uploaded.";
}
} else {echo "<br>Error uploading your file.";}
}
//show all uploaded images
$q2 = mysqli_query($conn,"SELECT product_img_url FROM temp_img");
while ($row = mysqli_fetch_array($q2)) {
$product_img_url = $row['product_img_url'];
$img_format = ".jpg";
$broken_url = "assets/img/temp_img/";
echo '<img src="'.$main_url.$broken_url.$product_img_url.$img_format.'" class="img-rounded" alt="Cinque Terre" width="304" height="236">';
}
image missing picture
I think the following link will help you change permissions of your file.
http://php.net/manual/en/function.chmod.php
Note:
1.check whether the uploaded file is in specified folder.
2.try setting the path without "../" in the variable targetdir

PHP File upload and overwrite file with same name

I am making an application that allows users to upload a file in a directory via PHP.
I am having problems because it dose not allow me to overwrite files with the same name.
Eg I have a file called text.php and I upload it, now when I go back and change the content of file text.php and I upload it again on the server I still have the version without the edits. However if I upload another file it works. So I just can't overwrite files.
if ($_POST["greg"]=='true'){
// Set local PHP vars from the POST vars sent from our form using the array
// of data that the $_FILES global variable contains for this uploaded file
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
// Specific Error Handling if you need to run error checking
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 90000000000000) { // if file is larger than we want to allow
echo "ERROR: Your file was larger than 50kb in file size.";
unlink($fileTmpLoc);
exit();
} else if (!preg_match("/.(doc|docx|xls)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your file is not the right format contact the master of the page for clarification.";
unlink($fileTmpLoc);
exit();
}
// Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "documenti/$fileName");
// Check to make sure the uploaded file is in place where you want it
if (!file_exists("documenti/$fileName")) {
echo "ERROR: File not uploaded<br /><br />";
echo "Check folder permissions on the target uploads folder is 0755 or looser.<br /><br />";
echo "Check that your php.ini settings are set to allow over 2 MB files, they are 2MB by default.";
exit();
}
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is a <strong>$fileType</strong> type of file.<br /><br />";
echo "The Error Message output for this upload is: <br />$fileErrorMsg";
}
How can I change this code so that when I upload a file with the same name it overwrites the existing file?
Try this (put it before upload a file)
//checking if file exsists
if(file_exists("documenti/$fileName")) unlink("documenti/$fileName");
//Place it into your "uploads" folder mow using the move_uploaded_file() function
move_uploaded_file($fileTmpLoc, "documenti/$fileName");
Maybe the script does not have the rights to overwrite? Try to change the dir to 777 and test again. If it works then, you can figure out the correct value you need
if (file_exists("documenti/$fileName"))
{
unlink("documenti/$fileName");
echo "<font face='Verdana' size='2' >Last Uploaded File has been removed from uploads folder<br>back to uploadform agian and upload your file<br>";// now your file which uploaded before was deleted from uploads folder you can open it and check if it removed or not , so no you should go back to uploadform again and import your file which will uploaded correctly
echo "<font face='Verdana' size='2' ><BR><BR><BR><a href='upform.php'>Back to upform</a><BR>";
}
Have you tried checking if the file exists and deleting it if it does before you move the temporary file to the permanent storage location?
$filePathAndName = "documenti/$fileName";
//check file exists
if(file_exists($filePathAndName))
{
unlink($filePathAndName);
}
//move_uploaded_file() function
move_uploaded_file($fileTmpLoc, $filePathAndName);

Categories