Image is not showing while copying from one folder to another - php

I am trying to copy an image from one folder to another using PHP.
Image is moving fine, but when I am opening the image, the image is not showing.
Any ideas?
Thank you.
Below is my code.
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'image_copy') {
$image = $_POST['image'];
//name of file to be copied
$img = $image;
//read the file
$fp = fopen('files/post/' . $img, 'r') or die("Could not contact $img3");
$page_contents = "";
$new_text = fread($fp, 100);
$page_contents = $new_text;
//This moves you from the current directory user to the images directory in the new user's directory
chdir("files/profile");
//name of your new file
$newfile = $image;
//create new file and write what you read from old file into it
$fd = fopen($newfile, 'w');
fwrite($fd, $page_contents);
//close the file
fclose($fd);
exit;
}

I have made it some other way using file get content and put content .
$image = $_POST['image'];
$dir_to_save = "files/profile/";
if (!is_dir($dir_to_save)) {
mkdir($dir_to_save);
}
file_put_contents($dir_to_save . $image, file_get_contents('files/post/' . $image));
But i am unable to do in move method of php.

Related

How to save images from list image url in csv

I want to save images from url to my directory and its image name after downloaded into a csv.
I write the following code which store images. but its not working as I want.
in below code $img is variable which fetch url from csv.
suppose I have 1000+ products in csv and every products have image url like
www.example.com/images/image1.jpg
so I want to download this image to my local directory/server directory and store its image name after download to csv file so I can add only image name into database tables.
set_time_limit(1000);
while($url = $response->fetch()) {
$my_image = file_get_contents($img);
$my_file = fopen('/csvfiles/','w+');
fwrite($my_file,$my_image);
fclose($my_file);
}
The some solution I found on other similar questions is
$file = file_get_contents($img);
file_put_contents("/csvfiles/Tmpfile.zip", fopen($img, 'r'));
But it is not applicable in my condition or not working.
Any help would be appreciated.
Edit New -
As marked as duplicate I want to add some more info here -
As I have all products info in csv formats and while importing the products I also want to download images from its url. And it is not possible to download 1000+ product image manually. I checked the above solution but it is not applicable in this situation. As in above solution they download image from only particular page and rename it directly. so it is different scenario here.
New Code - I also tried this code still not working
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
$fp = fopen("/csvfiles/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
Try with the following code.
set_time_limit(1000);
while ($url = $response->fetch()) {
$my_image = file_get_contents($img);
// check stricly that you have content of image
if ($my_image !== false) {
// download the image and store in the database.
$my_file = fopen('/csvfiles/', 'w+');
fwrite($my_file, $my_image);
fclose($my_file);
}
}
You need a filename as well, not only a directory:
// download the inage from the internet:
$my_image = file_get_contents($url);
// get filename from url:
$filename = basename($url);
$path = '/csvfiles/' . $filename;
// save image to that file:
$my_file = fopen($path,'w+');
fwrite($my_file, $my_image);
fclose($my_file);
// save $filename to DB
Hi below code works for me .. hope it will help someone..
Thanks #Gavriel and #Alankar
if(!empty($img)){
$my_image = file_get_contents($img);
file_get_contents(filename)
$filename = $data[0] . ".jpg";
echo $filename. "\n";
if(!file_exists($filename))
{
$my_file = fopen($filename,'w+');
file_put_contents($filename, $my_image);
echo $filename . "\n";
}
}
$image = "/uploads/" . $filename;
echo $image . "\n";
Here $img store url of image. which is fetch from csv file.
Here data[0] is csv column which is used to store image name uniquely . so we can use file_exists(); otherwise whenever I run my script again and again it store images again and store it by random temp name.

Create folder and save image into this folder that is send from android application

I have following PHP code to create a folder and save an image into this generated folder. What works is the generation of the folder, but the associated image will not be inserted into the folder, so the folder is always empty:
$uid = $_POST['uid'];
$image = $_POST["image"];
$suffix = $db->createRandomID(); //function creates random numbers and stores in $suffix
$url = "http://XXX.XXX.XXX.XX/uploads_offer/";
$image_name = "img_offer_".$suffix."".$uid."_".date("Y-m-d-H-m-s").".jpg";
$path = $url."".$image_name; // path of saved image
// base64 encoded utf-8 string
$binary2 = base64_decode($image);
// binary, utf-8 bytes
header("Content-Type: bitmap; charset=utf-8");
$filepath = $image_name;
if (file_exists("../uploads_offer/".$uid)){
//$file = fopen("../uploads_offer/".$uid . $image_name, "wb");
$file = fopen("../uploads_offer".$uid.$image_name, "wb");
fwrite($file, $binary2);
fclose($file);
}else{
$result8 = mkdir("../uploads_offer/".$uid, 0755);
$file = fopen("../uploads_offer".$uid.$image_name, "wb");
fwrite($file, $binary2);
fclose($file);
}
You are missing slashes (/) in your fopen() calls:
$file = fopen("../uploads_offer/".$uid."/".$image_name, "wb");

failure to upload multiple images using move_upload_file

I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path

saving canvas in php but no data in image file

Following code i am trying to save canvas on my Machine . in folder image file is created but it is of 0kb .
on click of download button i am setting value in text and on next php page i am reading value with $_POST['img_name']; .
JQuery ::
$("#Download").click(function() {
console.log('Download clicked');
//alert('Download clicked');
var myval = canvas.toDataURL();
$('#img_txt').val(myval);
});
php code ::
<?php
$myval = $_POST['img_name'];
echo "string is ".$myval;
?>
<?php
$data = base64_decode($_POST['img_name']);
/* Name the file anything you want */
$filename = 'my_image.png';
/* Remove 1st line of base64 string */
/* Note: replace '$base64' with your own variable */
$img = str_replace('data:image/png;base64,', '', $data);
/* Replace spaces */
$img = str_replace(' ', '+', $img);
/* Decode string */
$data = base64_decode($img);
/* Full path to upload directory with at the end the filename */
$file = 'D:/upload/'.$filename;
/* Save, make sure the directory is writeable! */
file_put_contents($file, $data);
?>
I have check $_POST['img_name'] i am getting base64 string ? what is the problem in my code?
Replace upload.php file
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the image data
$data = $_POST['image'];
// remove the prefix
$uri = substr($data,strpos($data,",")+1);
// create a filename for the new image
$file = md5(uniqid()) . '.png';
// decode the image data and save it to file
file_put_contents($file, base64_decode($uri));
// return the filename
echo $file;
}
Your jQuery isn't sending anything to your .php
Try this:
// convert the canvas to base64 data
var dataURL=canvas.toDataURL();
// call upload.php and post the data
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
console.log("Saved filename: "+respond);
});
Your upload file should remove the datatype prefix before decoding.
Try this for upload.php:
<?php
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the image data
$data = $_POST['image'];
// remove the prefix
$uri = substr($data,strpos($data,",") 1);
// create a filename for the new image
$file = md5(uniqid()) . '.png';
// decode the image data and save it to file
file_put_contents($file, base64_decode($uri));
// return the filename
echo $file;
}
Also, make sure your php server is configured:
Assign an upload directory
Give write permission to the upload directory
I used Following code to save base64 as an image,
<?php
if (isset($_POST["image"]) && !empty($_POST["image"])) {
// get the image data
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
//Image name
// $filename ="image". md5(uniqid()) . '.png';
$filename = "Post_Card.png";
$file = '../ReportCard/' . $filename;
// decode the image data and save it to file
file_put_contents($file, $data);
echo $file;
}
?>
If require we can use following code to give random generated names to file ,
// create a filename for the new image
$file = md5(uniqid()) . '.png';
Are you sure it is a png format?
because when you run the method toDataURL(); the default is PNG you cant try toDataURL("image/jpeg"); or any other format that correspond wit your need.
And you might want to consider uploading it to PHP so you can save it on your server in a directory let's say Pics.

Uploading an image with rackspace

So i have the following codes that uploads an image to the dir /uploads.
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode('', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
I tried to change the code a bit. So instead of uploading to the directory, i wanted it to upload to my rackspace. I am using the following codes (which works with my other file uploads)
// cloud info
$username = ""; // username
$key = ""; // api key
// Connect to Rackspace
$auth = new CF_Authentication($username, $key);
$auth->authenticate();
$conn = new CF_Connection($auth);
// Get the container we want to use
$container = $conn->get_container('ContainerName');
// store file information
$localfile = $_FILES['pic']['tmp_name'];
$filename = $_FILES['pic']['name'];
// upload file to Rackspace
$object = $container->create_object($filename);
$object->load_from_filename($localfile);
?>
I replaced the part where the image uploads to the dir /upload to the above one. It's not working.
I am using this HTML5 drag & drop uploader.
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
Help please.
I had a problem similar to this. The issue I had was that the object doesn't have the file type associated with it. Someone probably can explain it better as I am a PHP newb, but this is what I used for it to work for me:
$object = $container->create_object($filename);
$object->content_type = "image/jpeg"; //This is where the issue is
$object->load_from_filename($localfile);

Categories