PHP Uploading images and getting the url - php

I've been working on a premade image upload template for fun and I'm not too good with php so I can't seem to get around this problem.
I need to be able to extract the direct link to my image (the $upload_dir variable + file extension) so I can use it in my index.php page. I've tried to include my post_file.php file in my index.php but I am getting the Wrong HTTP-method message.
My website is in html5 and it's using the drag-and-drop to initiate the uploading if that is something that messes with my upload file.
post_file.php:
$demo_mode = false;
$upload_dir = 'uploads/'.date(d).rand(0000,9999);
$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!');
}
// Uploads are being ignored, but logged.
if ($demo_mode) {
$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 image,rename it and log it all
if (move_uploaded_file($pic['tmp_name'], $upload_dir.'.'.get_extension($pic['name']))) {
$line = implode(' ', array( date(r), 'http://website.com/'.$upload_dir.'.'.get_extension($pic['name'])));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Upload was successful');
}
}
exit_status('Something went wrong with your upload!');
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);
}
When I use the include('post_file.php') is when I receive the error message, how can I get the new image name + path and extension without including the post_file.php in my index.php file and then echo it in a variable?
Thanks in advance!

Related

PHP file_exists With Contents Instead of Name?

Is there a function built into PHP that acts like file_exists, but given file contents instead of the file name?
I need this because I have a site where people can upload an image. The image is stored in a file with a name determined by my program (image_0.png image_1.png image_2.png image_3.png image_4.png ...). I do not want my site to have multiple images with the same contents. This could happen if multiple people found a picture on the internet and all of them uploaded it to my site. I would like to check if there is already a file with the contents of the uploaded file to save on storage.
This is how you can compare exactly two files with PHP:
function compareFiles($file_a, $file_b)
{
if (filesize($file_a) == filesize($file_b))
{
$fp_a = fopen($file_a, 'rb');
$fp_b = fopen($file_b, 'rb');
while (($b = fread($fp_a, 4096)) !== false)
{
$b_b = fread($fp_b, 4096);
if ($b !== $b_b)
{
fclose($fp_a);
fclose($fp_b);
return false;
}
}
fclose($fp_a);
fclose($fp_b);
return true;
}
return false;
}
If you keep the sha1 sum of each file you accept you can simply:
if ($known_sha1 == sha1_file($new_file))
You can use a while loop to look look through the contents of all of your files. This is shown in the example below :
function content_exists($file){
$image = file_get_contents($file);
$counter = 0;
while(file_exists('image_' . $counter . '.png')){
$check = file_get_contents('image_' . $counter . '.png');
if($image === $check){
return true;
}
else{
$counter ++;
}
}
return false;
}
The above function looks through all of your files and checks to see if the given image matches an image that is already stored. If the image already exists, true is returned and if the image does not exist false is returned. An example of how you can use this function shown is below :
if(content_exists($_FILES['file']['tmp_name'])){
// upload
}
else{
// do not upload
}
You could store hashed files in a .txt file separated by a \n so that you could use the function below :
function content_exists($file){
$file = hash('sha256', file_get_contents($file));
$files = explode("\n", rtrim(file_get_contents('files.txt')));
if(in_array($file, $files)){
return true;
}
else{
return false;
}
}
You could then use it to determine whether or not you should save the file as shown below :
if(content_exists($_FILES['file']['tmp_name'])){
// upload
}
else{
// do not upload
}
Just make sure that when a file IS stored, you use the following line of code :
file_put_contents('files.txt', hash('sha256', file_get_contents($file)) . "\n");

Upload fails "move uploaded file"

First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.

How to copy an image from one folder to another using php

I'm having difficulty in copying an image from one folder to another, now i have seen many articles and questions regarding this, none of them makes sense or work, i have also used copy function but its giving me an error. " failed to open stream: No such file or directory" i think the copy function is only for files. The image i wanna copy is present in the root directory. Can anybody help me please. What i am doing wrong here or is there any other way???
<?php
$pic="somepic.jpg";
copy($pic,'test/Uploads');
?>
You should write your code same as below :
<?php
$imagePath = "/var/www/projectName/Images/somepic.jpg";
$newPath = "/test/Uploads/";
$ext = '.jpg';
$newName = $newPath."a".$ext;
$copied = copy($imagePath , $newName);
if ((!$copied))
{
echo "Error : Not Copied";
}
else
{
echo "Copied Successful";
}
?>
You should have file name in destination like:
copy($pic,'test/Uploads/'.$pic);
For your code, it must be like this:
$pic="somepic.jpg";
copy($pic,'test/Uploads/'.$pic);
Or use function, like this:
$pic="somepic.jpg";
copy_files($pic,'test/Uploads');
function copy_files($file_path, $dest_path){
if (strpos($file_path, '/') !== false) {
$pathinfo = pathinfo($file_path);
$dest_path = str_replace($pathinfo['dirname'], $dest_path, $file_path);
}else{
$dest_path = $dest_path.'/'.$file_path;
}
return copy($pic, $dest_path);
}

Where do I put my link in this php?

This is a really trivial question, but I can't figure it out:
I have this php scrip
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'upload/';
$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.'Bild.jpg')){
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);
}
?>
After finishing the process, I want to redirect to another page, or even better, directly start another script.
I tried inserting
header('Location: start_conversion.php');
after the last if (File was uploaded sucessfully), but that didn't work.
Where is my mistake?
exit_status appears to terminate your script. So you'd need to put your redirect before that.
Perhaps instead you could use:
function exit_redirect($loc){
header("Location: $loc",TRUE,302);
exit;
}
Ok, the solution was an originally added javascript. I had to redirect from there, then everything worked.

Copy images from one folder to another

My Web application stored in directory of XAMPP/htdocs/projectname/. And I have images(source) & img(destination) folders in above directory.I am writing following line of code to get the copy images from one folder to another. But I get the following Warnnigs: (Warning: copy(Resource id #3/image1.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs) and images are not copied into destination.
<?php
$src = opendir('../images/');
$dest = opendir('../img/');
while($readFile = readdir($src)){
if($readFile != '.' && $readFile != '..'){
if(!file_exists($readFile)){
if(copy($src.$readFile, $dest.$readFile)){
echo "Copy file";
}else{
echo "Canot Copy file";
}
}
}
}
?>
Just a guess (sorry) but I don't believe you can use $src = opendir(...) and $src.$readFile like that. Try doing this:
$srcPath = '../images/';
$destPath = '../img/';
$srcDir = opendir($srcPath);
while($readFile = readdir($srcDir))
{
if($readFile != '.' && $readFile != '..')
{
/* this check doesn't really make sense to me,
you might want !file_exists($destPath . $readFile) */
if (!file_exists($readFile))
{
if(copy($srcPath . $readFile, $destPath . $readFile))
{
echo "Copy file";
}
else
{
echo "Canot Copy file";
}
}
}
}
closedir($srcDir); // good idea to always close your handles
Replace this line in your code, this will work definitely.
if(copy("../images/".$readFile, "../img/".$readFile))
you are giving wrong path ,if path of your file say script.php is "XAMPP/htdocs/projectname/script.php" and images and img both are in "projectname" folder than you should use following values for $srcPath and $destPath,change their values to
$srcPath = 'images/';
$destPath = 'img/';
public function getImage()
{
$Path='image/'; //complete image directory path
$destPath = '/edit_image/';
// makes new folder, if not exists.
if(!file_exists($destPath) || file_exists($destPath))
{
rmdir($destPath);
mkdir($destPath, 0777);
}
$imageName='abc.jpg';
$Path=$Path.$imageName;
$dest=$destPath.$imageName;
if(copy($Path, $dest));
}

Categories