Unknown PHP output image error - javascript

First I know its annoying to have so much text instead of code to display the error, its just I'm not sure where I should start debugging, and therefore I will complement the thread as I go.
Here is the thing, I have a page where I have to upload multiple images and edit them in the browser. For that matter I developed javascript code where you can upload and edit the image inside a canvas and then output it to a hidden input.
Since the number of images a variable, another javascript function is necessary to create multiple inputs for new images.
Those images are, them, uploaded with other data by a post form. The process in which the post is processed is page_with_form --> process_form_page --> redirect_to_page, which is used to save the data into the database and the images to the server.
When uploading these multiple images in my local server no error is generated, but when I upload the code to the web server the script go bananas.
Every time I post the form WITH a multiple image (without the image uploaded the post is successful) an error occurs, but not always the same error. I had many different errors occurring actually.
The errors variate from outputting gibberish, like this:
‰PNG IHDR´ð©NH IDATxœd»wTUY‚¾]Ó=Ý=ÓSªzª«ÚŠ†2'Ì ”œsÎ9HF‚"* ‚ˆ(*"¨¨˜³¥‚JÎ9Þtn«»ºº,y~`÷Ì|ßï:÷œ³îZg­óœw½{ïw°nñ "üqýF› B|Ùüù·¬ž±-_,ä›ßþ‰­Ÿ~Ég¿þÛ¿YÀŸ~ó[>úÕò›_þ]]<6êâ±b5Ñ!DúcôÙ7|ò«?¢÷ç/0ûbž³çá2k!!u\¯CøcÂ,pÒÞIl`8q»¢‰ÛElhñÑ1ÄFEMLp±þaÄEÆCLxÑ»¢‰ $&$‚˜b㉊!66–¸Ø8â"£ˆ%>>žøø8’““IJˆ'1Ò„]>$z¹ëCÒ.7LV.ÂJ{úØmYI‰Û7šà¦§ƒî‚o°Ú¢EB’É»ˆõ7#ÖÛ„Ä]$„†ëJ´‹^;vadI˜Ž þëôpÑ5ÃtËV¶,^ŠÉÆ,ÿf6+gÎa§ÖZÌÖ¯'f—+ZŸ.ÄDk«–aµr#Kþ¬…Ùúõ˜¬]‰ÅÆͬœ¹„¿ü~&[V`ªãÄWÿ=—û¿ÿøÝoþÀï~óG>üõïøÏû-‰‰IìÙ³—øøxbcc‰%&&...
Or giving an errors like:
PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in E:\Home\gerenciamentodelegac\Web\documents\imgs\tatoos\51d115e8909cc397141e9a39651fa88a6d7302aeaee4248d257b8c8f16bf87ba.png on line 18
PHP Parse error: syntax error, unexpected ')' in E:\Home\gerenciamentodelegac\Web\documents\imgs\tatoos\d8e6765d3ab791adce3b325f6a1b8270e244a70df3739f34202f9158fa540f80.png on line 46
Or it just does not redirect to any page or show any error, it sits on the same page, and if a try to upload again a new error is generated:
PHP Warning: include(documents/imgs/tatoos/97ebacba3f87fd2477bb74a523fcc4810002a474b569b43b485ddac7c885ede5.png) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in E:\Home\gerenciamentodelegac\Web\fetch_page.php on line 70
PHP Warning: include() [<a href='function.include'>function.include</a>]: Failed opening 'documents/imgs/tatoos/97ebacba3f87fd2477bb74a523fcc4810002a474b569b43b485ddac7c885ede5.png' for inclusion (include_path='.;c:\PHP_5.3\includes') in E:\Home\gerenciamentodelegac\Web\fetch_page.php on line 70
But here is the crazy part: All the data is outputted correctly! The data is correctly saved to the database and the images are saved to the server.
Now, the local server uses PHP 5.5 and the web server uses PHP 5.3, and here is the code to save the image:
for ($i = 0; $i < sizeof($tatoos); $i++) {
if (!file_exists($tatoos[$i])) {
$uri = substr($tatoos_src[$i], strpos($tatoos_src[$i], ",") + 1);
$success = file_put_contents($tatoos[$i], base64_decode($uri));
}
}
Where should I start trouble shooting? Any idea where the error may relies?

Related

Codeigniter 4 enviroment make JSON.parse fail

I'm new in codeigniter 4
I just started a new project in Codeigniter 4, and i got an error using JSON.parse,
Unexpected token < in JSON at position 30
I get two different results from using different enviroments:
Default// did not make any change to codeigniter config
-The code run totaly fine, though for a second i manage to see a bug in console
-The bad thing, in this enviroment most of debugging tools are deactivated something that i would like to have while working.
SetEnv CI_ENVIRONMENT production // which makes the debugging tools from CI4 appear, this line is in .htacess
-The code stops at JSON.parse and get the error described before in console
So here it is how my code is estructured:
//controller
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//response rgets data from callback from a controller
console.log(response);//{status:0,message:'Access denied'}
data=JSON.parse(response); //error
//Other fixes i already tried
data=JSON.parse(JSON.stringify(response)); //Works fine, but returns a string, need an object
data=JSON.parse(JSON.parse(JSON.stringify(response))); //error
data=JSON.parse("{status:0,message:'Access denied'} "); //Even trying to use directly a JSON format throws error
data=JSON.parse({status:0,message:'Access denied'}) //error, without the comas
data=JSON.parse([{status:0,message:'Access denied'}]) //error
The debbuging tools seem to stop the loading when they find a bug, but i have not managed to find what i am doing wrong. Hope you can help me with this and thanks in advance.
EDIT
I´m using webix libraries for request, but they return string format.
I tried manually what you suggested,but the result was the same. It works if use CI4 in production env, but fails at development mode.
//Solutions tried
response = JSON.parse({"status":0,"message":"Access denied"});//error
response = JSON.parse("{'status':0,'message':'Access denied'}");//error
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//the response should be like this
{"status":0,"message":"Access denied"}
and then use like this
data=JSON.parse(response);
and kindly check your datatype during the post and it should be a json

"Unexpected end of JSON input" error on loading JSON file from local file system

Hi I'm trying to retrieve data from a title.JSON file into an index.html file using AJAX calls.Both these files resides in my local file system.I have created a new instance of the chrome and 've set its target property as "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"--disable-web-security --user-data-dir="c:/chromedev"(I'm aware that this is not a good practice. Just trying out a server less way).Below is my code
<h1><a id="headName" href="#">Name</a></h1>
<p onclick="spaLoad()">NameChange</p>
function spaLoad(){
var xhr = new XMLHttpRequest();
xhr.open('GET','title.json',true);
xhr.send();
xhr.onreadystatechange=function () {
//var obj=xhr.responseText;
var obj = JSON.parse(xhr.responseText);
console.log(obj);
console.log(xhr.readyState);
console.log(xhr.status);
console.log(xhr.statusText);
//document.getElementById('headName').innerHTML = obj;
document.getElementById('headName').innerHTML = obj.name;
}
}
title.json
{"name":"stackoverflow","age":"100"}
I get my h1 updated as "stackoverflow" through an ajax call along with the error
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at XMLHttpRequest.xhr.onreadystatechange
Here are my doubts:
1.I hope AJAX is for the communication between the client and the server. Though I have avoided using a server by modifying the browser settings, how did the ajax call work for me?Is it logical?
2.The JSON file contains the data as objects.Then why should I use JSON.parse(responseText)?(JSON.parse() is for converting the string from server into object for client I hope).If i directly give var obj=xhr.responseText;I get undefined.
3.readystate is changing to 4, but status is always 0.Why is it so?How could I resolve it.
Please give a brief explanation of how this server less ajax call works.I'm very new to ajax and is confused with this.
It is because readystate change fires multiple times and you expect it to fire once. You would need to check for readystate to be equal to 4 and the status to be 200 (or zero in your case since you are on the file protocol). Or use the onload and onerror events instead.
And if you still get a parsing error than you need to debug what is being returned.
//see what is returned
console.log(xhr.responseText)
//Look to see if you have hidden characters in the file.
console.log(escape(xhr.responseText))
Parsing errors occur either the file you are loading returns something else like an error page OR it has special hidden characters that cause the parser to choke.

TCPDF - How can I stop function file_exists in php from interfering with browser cache?

I have a button "print" , when it's clicked I send an AJAX request to my php script.
request contains :
Filename
other data.
I generate a pdf with this script Using TCPDF and return the link to the file to my ajax request.
Inside my PHP script :
I first test if the fileName sent exists in the folder where I keep all pdf files, if it existes I "UNLINK" it , if not I proceed with my script.
The problem I have is that whenever I make a change in the data I send to the script , the same pdf is created ( first one ) , so I assume it is a problem with the cache , and as I searched a bit , I found that the function file_exits has something to do with it ?
Any taughts on this issue ? or maybe a solution ?
I can provide any piece of code you want to help understant the issue.
EDIT:
my file_exits on php script :
if (file_exists('../store_files/'.$_POST["pdf_name"].'.pdf')) {
unlink('../store_files/'.$_POST["pdf_name"].'.pdf');
}
and just before the output I use the headers :
header ( 'Expires: 0' );header ( 'Cache-Control: must-revalidate' );
$pdf->Output(savepath.'/'.$name_pdf, 'F');
I think TCPDF is capable of overwriting an existing PDF. You would not need to use unlink(), and I cannot think of any reason file_exists() would be in play. It's possible (not sure) that the browser has cached the PDF document. If that's the case, you might try changing the file name or changing the URL when the document is created, something like /path/to/my.pdf?q=random
in order to make sure that file_exists() actually checks the filesytem, and doesn't return a cached result, run clearstatcache(true) first.
btw, have you considered that you might be experiencing a race condition? that several ajax requests are processed at the same time, that generates the same filename, and php#1 does file_exist("foo.pdf") , sees that it doesn't exist, and starts creating it - but at the same time, before its done creating the foo.pdf , php#2 also does file_exist , sees that it doesn't exist, and start creating it - and then php #1 finishes, writes foo.pdf - and then php#2 finishes, tries to write foo.pdf - but notices that it already exists, and doesn't want to overwrite it - and errors out?

PHP error reporting suppresses AJAX error

The development server I work on had PHP errors logging turned off, so when I start a new project I add my own logging config:
error_reporting(E_ERROR);
ini_set('display_errors','On');
ini_set('error_log','/var/tmp/don-errors.log');
With this set my ajax/php widget works perfectly.
When I remove the logging set up I get a parseerror and the famous:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
If I add just the first line back:
error_reporting(E_ERROR);
The ajax JSON error goes away and everything is back to working perfectly. I've been searching everything I can find on what would cause the JSON error, but that's another question. I'm curious why I get no PHP errors in my PHP log with logging on, or JSON errors in console, but with logging removed I get the JSON error in the browser console and my widget dies.
I don't want to publish my widget with the logging in just to supress the error.
Here is the JSON string I'm sending back to the JavaScript as a response.
{"status":"success","data":{"dialogTargetId":"dialog-target-2969-212430","dialogId":"dialog-2969-212430","addBtnId":"addbtn-2969-212430","prodId":"2969","poId":"212430","dialogHtml":"<div class=\"buyer-note-dialog\" id=\"dialog-2969-212430\" title=\"Buyer Product Notes\"><div class=\"buyer-note-input\">\n\t\t<textarea name=\"buyer-note-text\" id=\"input-2969-212430\" product_id=\"2969\" po_id=\"212430\" class=\"buyer-note-text\" cols=\"35\" rows=\"3\"><\/textarea>\n\t\t<br><div style=\"padding-top: 5px\"><button id=\"addbtn-2969-212430\" emp-id=\"198\" textarea_id=\"input-2969-212430\" po_id=\"212430\" product_id=\"2969\">Add Note<\/button>\n\t\t<\/div><\/div><div id=\"output-box-2969-212430\" class=\"buyer-note-output-box\"><\/div><\/div>"}}

krajee bootstrap file input upload

First , i am a french web developer ( sorry for my poor english )
i 'am looking for a bootstrap php image upload with thumbnail.
i would like to make an upload image file like :
[http://www.2ememain.be/inserer/][1]
the Krajee plugin ([http://plugins.krajee.com/file-input][2]) seems to be the one i am looking for..
But i have some problems with the upload..
i get the error message:
item1.png: SyntaxError: Unexpected token e
my form:
<input id="input-700" name="kartik-input-700" type="file" multiple=true class="file-loading">
js:
$("#input-700").fileinput({
uploadUrl: "upload.php",
uploadAsync: true,
maxFileCount: 10});
upload.php:
echo "test";
if (empty($_FILES['input-700'])) {
echo json_encode(['error'=>'No files found for upload.']);
return;
}
// get the files posted
$images = $_FILES['input-700'];
var_dump($images);
More strange:
when i delete echo(test);
i get the error:
No files found for upload
Thanks for your support
if you have another solution , i shall be glad to get it..
Since you have set the uploadUrl parameter you are using the ajax uploads feature (instead of native HTML form submission).
You need to ensure that you return a proper JSON encoded data response from the server action (as set in uploadUrl) else the plugin fails. You can read the plugin documentation for ajax uploads where this is highlighted. For example, even if you do not have any data to send - you can send a empty JSON string like {}.

Categories

Resources