Post saves filename as array;jpg instead of input name - php

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);
?>

Related

renaming file with php not working

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.

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.

PHP can't pick up file

I've been trying to create a registration form that requires students to upload documents at the very end. However, after picking up the form values via jQuery, the PHP document can't seem to pick up my uploaded form. Any ideas?
Form:
<form id="joinUs" enctype="multipart/form-data" method="post">
<!--various form fields-->
<input type="file" name="transcript" id="transcript">
<div class="button" id="submit">Submit!</div>
</form>
jQuery:
$("#submit").click(function(){
//firstName, lastName, grade, studentID, email, phone are all form values
var data = "firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
$.ajax({
type: "POST",
url: "join_submit.php",
data: data,
success: function() {
location.href="http://mvcsf.com/new/success.php";
}
});
join_submit.php
$allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts";
$filename = $_FILES["transcript"]["name"];
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
if ($_FILES["transcript"]["error"] > 0) {
echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
}
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}
I ran this, and I got no errors. I also tried to print out the file name, except nothing printed out.
This should do it for you :
$("#submit").click(function () {
var transcript = $("#transcript").val();
var data = "firstName=" + firstName + "&lastName=" + lastName + "&grade=" + grade + "&studentID=" + studentID + "&email=" + email + "&phone=" + phone;
var formData = new FormData();
formData.append("file", transcript);
formData.append("data", data);
$.ajax({
type: "POST",
url: "join_submit.php",
enctype: 'multipart/form-data',//optional
cache: false,
contentType: false,
processData: false,
data: {
file: file
data: data
},
success: function () {
location.href = "http://mvcsf.com/new/success.php";
}
});
});
Cheers
First, In your code, you are posting data with $.ajax({...}) and the data sent is
"firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
There is no transcript at all.
Secondly, and most important, you cannot post file with $.ajax({...}) like that, it will not working like that. As #Roy M J says, you should take a look at FormData (for recent browser only), or take a look on the web for an upload jQuery plugin (don't re-invent the whell, some good plugin already exists :))
Take a look here
You cannot send a file like you do the values of HTML elements. There are two methods to file upload, the one I've used successfully is the AJAX method using a third-party feature called 'AjaxUploader'.You can download it here via GitHub. Once you've done it, add the ajaxuploader.js file in your 'js' folder (or wherever you've put all of your script files), include the file in the HTML page where you've to use the uploader. Now, uploading is as simple as follows.
HTML:
<input type="file" name="transcriptUploader" id="transcriptUploader" value="Upload" />
jQuery (you need to have the jQuery file included in your page):
new AjaxUpload('transcriptUploader', {
action: "page_to_handle_upload.php", // You need to have either a separate PHP page to handle upload or a separate function. Link to either one of them here
name: 'file',
onSubmit: function(file, extension) {
// This function will execute once a user has submitted the uploaded file. You can use it to display a loader or a message that the file is being uploaded.
},
onComplete: function(file, response) {
// This function will execute once your file has been uploaded successfully.
var data = $.parseJSON(response); // Parsing the returning response from JSON.
if(data.error == 0)
{
// If the file uploaded successfully.
}
else if(data.error == "size"){
// If the response object sent 'size' as the error. It means the file size exceeds the size specified in the code.
}
else if(data.error == "type"){
// If the response object sent 'type' as the error. It means the file type is not of that specified in the code (in your case, pdf).
}
else{
// In case the file didn't upload successfully or the code didn't return a usual error code. It is still an error so you need to deal with it appropriately.
}
}
});
Your back-end PHP code that will be doing all the heavy lifting (uploading the file, checking extensions, moving it etc):
if(isset($_FILES)) // Checking if a file is posted.
{
if ($_FILES['file']['error'] == 0) //Checking if file array contain 0 as an error. It means AJAX had no error posting the file.
{
$response = array(); // Initializing a new array.
$allowedExts = array("pdf"); // Allowable file format.
$filename = stripslashes($_FILES['file']['name']); // Storing file name.
//$extension = strtolower(self::_getExtension($filename)); // Fetching file extension.
// Code block to extract file extension and storing it in a variable called $extraction.
$i = strrpos($str, ".");
if (!$i)
{
$extension = "";
}
$l = strlen($str) - $i;
$extension = strlower(substr($str, $i + 1, $l));
$size = $_FILES['file']['size']; // Storing file size (in bytes).
$fileNameAfterUpload = md5((time() + microtime())) . '.' . $extension; // Concatinating file name and extension.
$baseSystemPath = "/var/www/<your_folder_name>/uploaded_transcripts/" // Path on which the file will be uploaded. Need to be relative web path.
$maxSize = 10*10*1024; // Storing file size. Be advised the file size is in bytes, so this calculation means max file size will be 10 MB.
$webPath = "uploaded_transcripts/". $filename; // Creating web path by concatinating base web path (the folder in which you'd be uploading the pdf files to) with file name.
if (in_array($extension, $allowedExts)) // Checking if file contains allowabale extensions.
{
if($size <= $maxSize) // Checking if the size of file is less than and equal to the maximum allowable upload size.
{
$moved = move_uploaded_file($_FILES['file']['tmp_name'], $webPath); // Moving the file to the path specified in $webPath variable.
if($moved == true)
{
$response['error'] = 0; // If moved successfully, storing 0 in the response array.
$response['path'] = $webPath; // Storing web path as path in the response array.
$response['filename'] = $filename; // Storing file name in the response array.
}
else
{
$response['error'] = 'internal'; // If move isn't successfull, return 'internal' to AJAX.
}
}
else
{
$response['error'] = 'size'; // If file size is too small or large, return 'size' to AJAX.
}
}
else
{
$response['error'] = 'type'; // If file type is not that of defined, return 'type' to AJAX.
}
echo json_encode($response); // Returning the response in JSON format to AJAX.
}
}
Do let me know if you need further assistance.
P.S: Don't forget to mark it as an answer if it worked.

Are canvas.toDataURL compatible with PHP's base64_decode?

My problem is as follows...
I have a screen in which the user can select a PNG image from its computer, using this:
<input id='icon' type='file' accept='image/png' style='width:400px; height:20px' onchange='llenarThumbnail(this)'>
<img id='thumb' src='#'>
When the user selects the image, a thumbnail is shown automatically, using onclick='llenar Thumbnail(this)', like this:
function llenarThumbnail(input){
if (input.files && input.files[0]){
var reader = new FileReader();
reader.onload = function (e){
$('#thumb').attr('src', e.target.result).width(48).height(48);
};
reader.readAsDataURL(input.files[0]);
}
}
Then, when the user clicks on the proper button to upload the image (not a submit button), I do the following to encode the image into Base64:
function getBase64Image(img){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
Then, using AJAX I send this encoded image data to the server, and a PHP script does the following:
$binary=base64_decode($imagen_data);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen($icono, 'wb');
fwrite($file, $binary);
fclose($file);
As I was printing diferent alerts along the process, I could see that the encoding was performing (i'm not so sure if correctly or not), and PHP receives the data and creates the PNG file, but when I open the image, the image is empty, there's no data... Thats why I'm asking if this to methods are compatible... I guess they are because they're both Base64... But if its not this, then what am i doing wrong???
Please, I'm tired of looking for this all over the internet! I need some answers! Thank you!
Without seeing your ajax POST, here's a Wild Guess:
Try leaving the prefix on until the URL gets to php.
Which php server are you using?
Some other usual gotchas:
Make sure you have properly set up your upload directory.
Make sure you have permissions set properly on the upload directory.
Client Side:
// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();
// post the dataUrl to php
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
// you will get back the temp file name
// or "Unable to save this image."
console.log(respond);
});
Server File: upload.php
<?php
// make sure the image-data exists and is not empty
// php is particularly sensitive to empty image-data
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
// get the dataURL
$dataURL = $_POST["image"];
// the dataURL has a prefix (mimetype+datatype)
// that we don't want, so strip that prefix off
$parts = explode(',', $dataURL);
$data = $parts[1];
// Decode base64 data, resulting in an image
$data = base64_decode($data);
// create a temporary unique file name
$file = UPLOAD_DIR . uniqid() . '.png';
// write the file to the upload directory
$success = file_put_contents($file, $data);
// return the temp file name (success)
// or return an error message just to frustrate the user (kidding!)
print $success ? $file : 'Unable to save this image.';
}
I could not get markE solution to work, had to change the data modification :
From :
$parts = explode(',', $dataURL);
$data = $parts[1];
$data=base64_decode($data)
To :
$img = str_replace('data:image/png;base64,', '', $dataURL);
$img = str_replace(' ', '+', $img);
$data=base64_decode($img);
Method from

Categories