renaming file with php not working - php

by clicking on button I'm making ajax call to rename a file, i get the ajax success respond that I'm echoing from php file, but file isn't renaming.
below is my file structure
admin (root)
-swap.php (inside admin folder)
-edit.php (ajax function is inside this file) (inside admin folder)
upload (root)
- file/s to be renamed in this upload folder
edit.php
$(".swap").click(function(){
var originalPic = $("#originalPic").attr("src");
var newPic = $(this).attr("data-file");
var dataString = 'old='+ originalPic + '&new='+ newPic;
$.ajax({
type: "POST",
url: "swap.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
});
swap.php
$originalPic = $_POST['old'];
$newPic = $_POST['new'];
$temp = "/uploads/tempname";
$imgUrl = "/uploads/";
$originalPic = $imgUrl . basename($originalPic).PHP_EOL;
$newPic = $imgUrl . basename($newPic).PHP_EOL;
$temp = $imgUrl . basename($temp).PHP_EOL;
rename($originalPic, $originalPic . 'tmp' . PHP_EOL);
echo "done";
main goal is to swap out the file names of two file (originalPic and newPic), but currently I'm just trying to add tmp at the end of name, but thats not working.

Related

Uploaded file not saving in the directory (PHP AJAX) "Serious in Need"

So i try this simple upload code but it doesn't work properly for me.
As cFos Speed shows the file uploading process is OK and 150kb pic is uploading, but at the end the file is not in the directory.
Also mkdir doesn't create a new folder. although i gave all permissions such az rwx chmod and apache:apache chown completely to the files i'm working on.
Here's the codes for html and ajax :
<input type="file" name="authform" id="authform" accept="image/png">
and
$(document).ready(function()
{
$("#authform").on("change", function()
{
var input = $(this);
var inputLength = input[0].files.length;
var file;
var formData = new FormData();
for (var i = 0; i < inputLength; i++)
{
file = input[0].files[i];
formData.append( 'authform[]', file);
};
$.ajax({
url: "file_upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
});
and for the file_upload.php:
<?php
if (!file_exists('uploads')) {
mkdir('uploads', 0777);
}
$filename = time()."_".$_FILES['file']['name'];
if ( 0 < $_FILES['file']['error']) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'downloads/user-files/' . $filename);
}
echo 'downloads/user-files/'.$filename;
die;
?>
And Yes! i used a different directory because as said before mkdir does not work...
So what do you suggest guys?
Your file input does not have the multiple attribute so there is no need to loop through it as it will only have one file associated with it.
$("#authform").on("change", function()
{
var formData = new FormData();
formData.append('authform', this.files[0]);
$.ajax({
url: "file_upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
});
In your php code you refer to the file with the parameter file but you set it to authform in the js.
<?php
if (!file_exists('uploads')) {
mkdir('uploads', 0777);
}
$filename = time()."_".$_FILES['authform']['name'];
if ( 0 < $_FILES['file']['error']) {
echo 'Error: ' . $_FILES['authform']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['authform']['tmp_name'], 'downloads/user-files/' . $filename);
}
echo 'downloads/user-files/'.$filename;
die;
?>
The answer was I should have done this with copy() instead of move_uploaded_file().
I only needed a Form with enctype="multipart/form-data" and input with type="file", then with a submit action do this:
copy($_FILES['authform']['tmp_name'], "/var/www/html/test/app/downloads/user-files/" . $_FILES['authform']['name']);
And that's it! Works like a gem!

Post saves filename as array;jpg instead of input name

Trying to save a jpg file to server with the name from an input box but gets saved as Array.jpg
Contents of html file:
<input type="text" name="datepicker" id="datepicker">
Contents of php file:
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = ['datepicker'].'.jpg';
echo $_REQUEST['datepicker'];
$file = $location . $filename;
file_put_contents($file, $image_base64);
Script from the html:
<script type='text/javascript'>
function screenshot(){
html2canvas(document.body).then(function(canvas) {
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
});
}
</script>
no error messages , just saves with wrong name.
Have now tried:
$filename = ['datepicker']; - saves as: Array (no extension).
$filename = $_POST['datepicker']; (nothing gets saved at all).
$filename = $_POST['datepicker'].'.jpg'; (saves as .jpg (just extension, no file name).
$filename = $_FILES['datepicker']['name']; (nothing gets saved at all).
$filename = $datepicker; (nothing gets saved at all).
$filename = "screenshot_".uniqid().'.jpg'; saved as screenshot_5d40158a1dad5.jpg
It seems to me that the form name field, datepicker, is not available to the php file at all.
Maybe this is because the call (or whatever you call it) to the php file is wrapped in javascript tags? I dont know. Just getting frustrated after 24 hours of trying to get this to work.
I think I have to pass form name field, datepicker, to the ajax code and then use it in the php file.
Anyone know how to amend my code to do this?
I have now resolved this. I had to amend the javascript in the html to include a var with the vale from the text input box and update the ajax to include it in the data line.
<script type='text/javascript'>
function screenshot(){
html2canvas(document.body).then(function(canvas) {
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
var val1 = $('#datepicker').val();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
//data: {image: base64URL, name: datepicker},
data: {image: base64URL, datepicker: val1},
success: function(data){
console.log('Upload successfully');
}
});
});
}
</script>
Then I had to update the php file with the file name to include the txt data from the form in the filename:
<?php
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = $_POST['datepicker'].'.jpg';
$file = $location . $filename;
file_put_contents($file, $image_base64);
?>
$filename = $_POST['datepicker'].'.jpg';
What you are using is not a good way to store a file in a PHP.
you should prefix current date and some random number generated by PHP to image name before storing the image because if two images are to be stored in the same folder on server's first image will be overwritten and the second file will be stored in its place making the first image to be disappeared completely
try prefixing " date('Ymdhis').rand(100000,999999) " to your image file and use $_FILES['something']['name'] and $_FILES['something']['tmp_name'] to get name and temperary name of the image respectively to store image
I have now resolved this. I had to amend the javascript in the html to include a var with the value from the text input box and update the ajax to include it in the data line.
<script type='text/javascript'>
function screenshot(){
html2canvas(document.body).then(function(canvas) {
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
var val1 = $('#datepicker').val();
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
//data: {image: base64URL, name: datepicker},
data: {image: base64URL, datepicker: val1},
success: function(data){
console.log('Upload successfully');
}
});
});
}
</script>
Then I had to update the php file with the file name to include the txt data from the form in the filename:
<?php
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
$filename = $_POST['datepicker'].'.jpg';
$file = $location . $filename;
file_put_contents($file, $image_base64);
?>

How to access file from multipart/form-data [ PHP ]

I have a frontend of my application writen in angular which basicly pick the file and send backend file name and rest of the form information:
Frontend part looks like:
$scope.submit = function() {
if ($scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'sub.php',
data: {file: file, 'country': $scope.submodelCountry}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
My backend is written in PHP:
I basicly access this 2 variabiles by:
$fileName = $_FILES['file']['name']; // value = fileName.csv
$country = $_POST['country']; // value = CZE
So looks my backend get all needed information however I am not able to fopen the file with $file = fopen($fileName,"r");
How can I access this file guys? Or how can I upload it on a server to use it after?
you have to upload the file to some folder, then you can access that,
Your file will be present in tmp directory, so
Use move_uploaded_files(), to move your file,
<?php
$uploads_dir = '/uploads';
if(move_uploaded_file($_FILES["file"]["tmp_name"],
"$uploads_dir/".$_FILES["file"]["file_name"])){
echo "file uploaded";
}
?>

trying to upload a file using ajax file uploaded but in corrupted php ajax jquery

I am trying to upload a file using PHP ajax jquery file is uploading but in corrupted format how can i make it correct.
in my controller i am using
$product_image = $request->getParam("product_image");
defined('PUBLIC_PATH') || define('PUBLIC_PATH', realpath(dirname(dirname(dirname(dirname(dirname(__FILE__)))))));
$filename = time() . rand(10000, 99999) . ".jpg";
file_put_contents(PUBLIC_PATH . "/public_html/product_images/" . $filename, base64_decode($product_image));
$products->__set("product_image", $filename);
$data = array(
"product_image" => $this->view->baseUrl() . "/product_images/" . $filename,
);
in ajax file
var p_image = $('#product_image').val();
$.ajax({
type: "POST",
url: '<?php echo $this->baseUrl(); ?>/api/products/add',
data : {product_image:p_image},
dataType: 'json',
success: function(response){
if (response.data.product_id == true) {
alert("Success");
alert(response.data.product_image);
Getting the content of uploaded file is
windows photo viewer can't open this picture because the file appears to be damaged, corrupted, or is too large.
please guide.
open the photo file in a text editor like Notepad and you'll find out that it likely contains the string value of p_image. More specifically, you're not actually uploading anything. I'd recommend using something like jQuery's ajaxForm to upload with ajax.
$('#myForm').ajaxForm(function() {
alert("Form is submitted");
});
Tutorial:
http://hayageek.com/ajax-file-upload-jquery/
Documentation:
http://malsup.com/jquery/form/

fwrite duplicate file when saving to server

I'm trying to save data into a file using fwrite, the problem is that it is creating a second file with the same file name, and the data is saved to the second file and not the original.
It works under Windows localhost, Apache 2.4.10, PHP 5.6 (no second file), but not on live server running Linux and PHP 5.4.42.
edit.php
$(document).ready(function() {
var pageName = "<?php echo $pageName; ?> ";
$('#save').click(function(e) {
e.preventDefault();
var content = $('#content').html();
$.ajax({
type: 'POST',
url: 'includes/readInput.php',
data: {
content: content,
pageName: pageName,
}
}).done(
function(data){
}
);
});
});
readInput.php.
// Receive post variable s from "admin/ edit.php"
$content = $_POST['content'];
$pageName = $_POST['pageName'];
$dirPath= "../content/";
file_put_contents($dirPath.$pageName,$content);
If you open the file where the data will be stored with the "a" from append flag this will result to write at the end of the file content:
$file = fopen($filename, 'a');
fwrite($file, 'new content');
Then you file will be stored with old content and "new content" the the end.

Categories