Set a $_file variable in jQuery - php

I want to verifie if an image has a valid format with ajax. But I have a problem, how do I set a $_file variable in jQuery?
So I want to "translate" this php code:
$Avatar = $_FILES['Avatar']['name'];
$AvatarTmp = $_FILES['Avatar']['tmp_name'];
To jquery.
And here is (the important part of) the Php script that will be call ($.post):
if(!empty($AvatarTmp))
{
$AvatarSize = getimagesize($AvatarTmp);
if($AvatarSize['mime'] =='image/jpeg')
{
$AvatarSrc = imagecreatefromjpeg($AvatarTmp);
}else
if($AvatarSize['mime'] =='image/png')
{
$AvatarSrc = imagecreatefrompng($AvatarTmp);
}else
if($AvatarSize['mime'] =='image/gif')
{
$AvatarSrc = imagecreatefromgif($AvatarTmp);
}else
{
$Errors[] = "Error006";
$AvatarSrc = false;
}
}
PS: if more code or anything is needed, ask, I'll add it right away.

Unfortunately jQuery (JavaScript) is a wholly different beast from PHP, and so it doesn't have a File object of any type. As #VIPINJAIN mentioned there is the HTML5 file API coming, but it is in its infancy.
You're much better off checking by file extensions (see Check input file for correct format with jquery) or doing the check server-side and outputting an error back from the server if it's in the wrong format.
== EDIT ==
Here is an example of how to use File API, including how to check file type with it, but bear in mind that this will only work in a limited number of browsers:
http://robertnyman.com/2010/12/16/utilizing-the-html5-file-api-to-choose-upload-preview-and-see-progress-for-multiple-files/#highlighter_81142

No you cannot send file in ajax request until and unless you are using html5 file api in mozilla firefox.
alternatively you can do this,
submit the form with file input to an iframe and on the load of the iframe get the contents of body element of iframe using jquery. and check the response of the server.

Related

Using php variable from one isset to another

I have a page where on form submit from previous page a div with something like invoice is created. I send that data to server and populate the invoice for print/generate PDF etc.
if (isset($_POST['kreiraj'])) {
$emailuser = $_POST["na_email"];
}
On same page I create with JS a PDF from canvas of that invoice and send it via Ajax for posting into PHP mail script witch is also on same page.
if (isset($_POST['fileDataURI'])) {
$pdfdoc = $_POST['fileDataURI'];
};
This all works but I have problems accessing PHP variables from each other.
I have read about function global and $_GLOBLAS[varables] but nothing seems to work for me. Can someone point out a way to do it?
TO be exact i need to access $emailuser from example code above in if (isset($_POST['fileDataURI'])) php mailing script.

PhP reading script erros from console

i am trying to test if my script is loaded on a given website and if the script is actually working without any errors onload (later on i will have to do the same for onclick)
So far i have
$testResult = array();
$homepage = 'http://www.example.dk/';
$data = file_get_contents($homepage);
if (strpos($data,'example_script.js'))
{
$testResult['scriptLoaded'] = true;
print_r("win");
}else{
$testResult['scriptLoaded'] = false;
}
Now this loads the page and checks if the javascript is on the page. But how can i read from the console to check if there is any errors while loading the script?
Also is this the right way to check if the script is on the page? The only restriction i have is that i HAVE to use PHP.
The only thing you can check with your code is weather or not somewhere in the code/contents you've gotten from the given url, there is a string example_script.js. If you were to use the url to this page, you'd get true and "win", too, because the substring will be found.
The JS might be riddled with fauklts, but since PHP doesn't understand Js, you won't be able to see that.
If you want to test your site, without a browser, the only thing I can think of is using phantomjs:
Which can be found Here
Using PHP alone, you might be able to do a couple of checks using scriptable browser, cUrl, and the DOMDocument class (to parse and validate the markup).

Apache load php and local file error: "Unsafe JavaScript attempt to access frame with URL..."

I have Apache set up through xampp to test a webpage to load some .php file to read a .csv file as data source to output a bar graph chart. And I encounter this error on Chrome.
Unsafe JavaScript attempt to access frame with URL file:///C:/xampp/htdocs/search/php/loader/csvFileUploader.php from frame with URL file:///C:/xampp/htdocs/search/stackedBarChart.html. Domains, protocols and ports must match.
upclick-min.js:99
i.onload_callback.i.onload_callback upclick-min.js:99
onload
I don't think this is an iframe problem like many other posts have suggested. I tested this also through firefox, it went beyond reading the php but doesn't load the .csv file from local directory.
Any suggestions?
<script>
var uploaderCSV = document.getElementById('uploaderCSV');
upclick({
element : uploaderCSV,
action : 'php/loader/csvFileUploader.php',
onstart : function(filename) {
console.log(" -- Start upload: <" + filename + "> Here");
},
oncomplete : function(response_data) {
alert(response_data);
console.log(" -- CSV file to load: ", response_data);
var n = response_data.split("|");
if (n.length > 1) {
console.log(" >> csv file loaded at[ ", n[1], " ]");
loadDayLightFactor("php/loadCSV.php", "../" + n[1]);
}
}
});
</script>
and here's the php file
<?php
// using upload at click from http://code.google.com/p/upload-at-click/
// FileData is the name for the input file
$file_result = "";
$file = $_FILES['Filedata'];
$allowedExtensions = array("csv", "txt");
$extension = end(explode(".", $file["name"]));
echo "123".$file;
?>
Your problem seems to be the URL you are trying to reach:
file:///C:/xampp/htdocs/search
This is not the way to develop on local environment.
try to access it through
http://localhost/search
I'm sure it will work better. detailed explanation below..
This is happening because of a security standard called Cross-Domain-Policy
You can not make a call (via JavaScript) to files with a URL that is different from your current URL Address.
For example:
My website's URL is foobar.com, I'm trying to send an AJAX request to barbaz.com.
I can't!
because it's not my domain. I can try sending requests to barbaz.foobar.com (using some JavaScript code).
Another scenario that will show you why this is a "must have" security standard:
Lets say that I'm logged into my bank's website using a cookie. the cookie is persistent.
I'm entering a random website X that send AJAX request to all known bank websites. If I'm still logged into my bank's website, X website can "talk" to the bank's website using my user, and do things that I'm not aware of.
This is a small example why this is very important.
I hope this was helpful.

Why is image request generating a 302?

I'm using PHP to generate the following image element:
<img id="uploaded-image" src="http://localhost/gonzo/plans/image/123/tablemap.png" />
This image URL is routed through my PHP MVC framework to the following function, which grabs the image from my db and prints it:
public function image($hexCode='',$fileName) {
if (!$this->validRequest('get')) return false;
Framework::loadModel('plan_model.php');
$plan = new PlanModel();
// Return image data from Blob field in db.
$image = $plan->getImage('123');
if ($image) {
header("Content-Type: image/png");
print $image;
die;
} else {
echo 'error';
}
}
The request generates a 302, with the wrong location and content-type headers:
The browser does not display the image where this image tag is on the page. But, when the image URL is typed directly into the address bar, the image is displayed.
Why would my server be generating a 302 when loading the image into an tag, but generating a 200 when the image URL is typed directly into the address bar? I'm running Apache on Windows.
The described behavior isn't possible at all - since the server doesn't know a bit about how an URL is embedded in a web-page.
Provide more details of the actual call of the PHP-script: Print environmental details - $_GET, $_POST and $_SERVER - to a log file.
It might be helpful to register a tick-function and trace each executed statement to a log-file.
Check your PHP sources.
It turns out that this was caused by a strange concurrency problem. My framework was still processing the first request (which generated the page containing the img element) while the browser requested the image.
In other words, when the browser requested the image, it was still receiving output from the first request to the script. This made things go wacky.
Output buffering didn't solve the problem, but possible solutions are:
Pause execution of the second (image request) script for a sufficient amount of time to let the first one complete.
Host the image serving script on a separate subdomain.

php load page page into div ,java script not working

i am using ajax to load pages into a div
the page is loading fine
but i cant run the php and javascript
in that loaded page
in server i am loading the page like this
file_get_contents('../' . $PAGE_URL);
in the browser i am setting the content of the div
using
eval("var r = " + response.responseText);
and setting the innerHTML for that div
with the retrieve information
but when i get the new inner page
no php or java script is working
is that suppose to be like that ?
Well the php is not going to work I think because the way you are handling it, it is just text. I would suggest using something like include('../' . $PAGE_URL); and that should parse the php.
The javascript problem probably has to do with the fact that you are loading <html> <body> <head> tags in a div I'm not sure what happens when you do that, but it shouldn't work properly. Try using some type of <frame> tag.
In order for your javascript to be executed properly, you have to wait until the browser has finished to load the page.
This event is named onload(). Your code should be executed on this event.
<?php
$file = false;
if(isset($_GET['load'] && is_string($_GET['load'])) {
$tmp = stripclashes($_GET['load']);
$tmp = str_replace(".","",$tmp);
$file = $tmp . '.php';
}
if($file != false && file_exists($file) && is_readable($file)) {
require_once $file;
}
?>
called via file.php?load=test
That process the PHP file, and as long as you spit out HTML from the file simply
target = document.getElementById('page');
target.innerHTML = response.responseText;
Now, i'm fairly certain parts of that are insecure, you could have a whitelist of allowable requires. It should ideally be looking in a specific directory for the files also. I'm honestly not all too sure about directly dumping the responseText back into a DIV either, security wise as it's ripe for XSS. But it's the end of the day and I haven't looked up anything on that one. Be aware, without any kind of checking on this, you could have a user being directed to a third party site using file_get_contents, which would be a Very Bad Thing. You could eval in PHP a file_get_contents request, which... is well, Very Very Bad. For example try
<?php
echo file_get_contents("http://www.google.com");
?>
But I fear I must ask here, why are you doing it this way? This seems a very roundabout way to achieve a Hyperlink.
Is this AJAX for AJAXs sake?

Categories