Looking at this document; I am trying to make a file upload using XMLHttpRequest.
Here is how I start: I take the code in the A little vanilla framework section of the document. Then I first make it work on my own site. Then to implement the upload functionality I want to modify the end of the register.php file. Indeed a file transfer to the server is already happening there. To call it an upload I only have to save the file on the server.
I do that after these lines:
echo "\n\n:: Files received ::\n\n";
print_r($_FILES);
There, I want to write the contents of $_FILES[0] on the server. For that I use this code:
$myfile = fopen("MyData.jpg", "w");
fwrite($myfile, $_FILES[0]);
// The three lines below that I have tried instead of the one above do not work either.
//fwrite($myfile, json_encode($_FILES['photos']);
//fwrite($myfile, json_encode($_FILES[photos[0]]);
//fwrite($myfile, json_encode($_FILES['photos'][0]);
fclose($myfile);
As a result, there is a file named MyData.jpg written on the server as expected, but its length is zero.
I think there is a mistake in the three lines above but, what did I do wrong?
Right method is to use
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "MyData.jpg");
where "fileToUpload" is the field name you gave for the file button
I think you'll get data here: $_FILES['photos']['tmp_name'][0].
Try it please.
Or
You could rewrite your code like below:
foreach($_FILES['photos']['tmp_name'] as $i=>$file){
if($_FILES['photos']['error'][$i] == 0){
move_uploaded_file($file, "MyData_".$i.".jpg");
}
}
Related
I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?
You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.
After a form is submitted from my php file it checks it, and then is supposed to call an exec function that will execute a binary file using the second file listed in the code. Shown below:
if (isset($_POST['admin']) && !empty($_POST['admin'])) {
echo exec('/home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/bin/phantomjs /home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/examples/bigdaddy.js');
}
The problem here is that the preceding javascript file bigdaddy.js has to take three arguments of its own in order to function. To solve this issue, I tried the following:
echo exec('/home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/bin/phantomjs /home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/examples/bigdaddy.js' $_POST['admin'] $_POST['user'] $_POST['password']);
This bricked my site.
Does anybody have any ideas how this may be done? All of the possible solutions I have found detail PHP to PHP, NOT PHP to Javascript. Thanks all!
you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.
I've faced with a problem. I use Mafnific popup. Below the popup I add a button to download image and different actions like social icons etc.
so, I need to find out a filesize of image uploaded to media of Wordpress. I have js variable where I have link to image.
For this in functions.php I put a function for searching id of this image by link like this:
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
And now I can find out the filesize if I put a link of image to this function like this:
echo size_format(filesize( get_attached_file(pippin_get_image_id($link)) ),2);
But the main problem is: I am now inside js script and I need to pass to function a JS variable var link:
Inside a function I have a snippet:
return 'Download (<?php echo size_format(filesize( get_attached_file(pippin_get_image_id( VARIABLE LINK )) ),2); ?>)
p.s. see where VARIABLE LINK is.
How can I put js variable there ?
Thank you so much in advance!
you can just print image size in hidden field like this:
<input style="display:none" id="image_link" value="<?php echo size_format(filesize( get_attached_file(pippin_get_image_id($link)) ),2); ?>" />
and then in script fetch this value in jQuery like this:
var imageLink = jQuery('#image_link').val();
return '<a href="' + link + '" download target="_blank" class="btn btn-success" id="original">Download (<?php echo size_format(filesize( get_attached_file(pippin_get_image_id(
'+imageLink +' )) ),2); ?>)</a>
Edit - Explanation: What you want to do is not directly possible because PHP execution stops before JavaScript execution starts. PHP is a server-side script language, meaning that it runs when the user requests a page from the server. It prepares the page, stops execution and the server sends the results to the requesting user. Only then it is displayed in the users browser and JavaScript execution (which runs on the users machine by the way) starts.
You might want to take a look at wp_localize_script(). This function takes information available at PHP runtime and puts it into a JavaScript variable, which you can then use in your JavaScript scripts.
In the (likely) case that you don't know at PHP runtime which file-size you need (for example when you have a huge list of files and don't want to pre-fetch file-sizes for all of them) your go-to solution will be AJAX. This is more complicated, but once you understand how it works, you can do many exciting things with it. The process is as follows:
In your JavaScript files, you "make a call" to an URL. In this case, the URL is your WordPress site. This call is made by JavaScript, so the user will not see anything of it. You can add addition data (variables) to this call.
You tell WordPress how to handle this call. Once again, the users sees nothing of this. The output of this call, that, in normal scenarios, would be shown in the browser, will instead be passed back to the calling JavaScript file from step 1.
After your calling JavaScript file has received a response from the call, you can use the response in any way you like.
Translated to your case: JavScript script runs when popup is opened. This script calls WordPress, WordPress handles the call with your file size function and returns file-size, JavaScript script takes file-size and adds it to the link-button.
Using jQuery makes the whole process of AJAX calls much more straightforward.
First: I KNOW this is a duplicate. I am creating this because none of the answers to all the other questions satisfy me. I have a very particular situation where I'm using yii and tryi I can't send it through ajax because the php and javascript are on the same page on the same page.
Basically what I'm asking is if you have a page that uses yii and chart js, and you need to render a page that requires two arguments from the clicked bar, which is represented by activeBars[0]:
<script>
canvas.onclick = function(event) {
var activeBars = getBarsAtEvent(event);
<?php $controller->functionThatRendersView($arg1 /**(activeBars[0].value*/,$arg2 /**(activeBars[0].label*/); ?>
}
I don't care if it will render automatically, that is another problem. I just need to get those arguments to the php.
Thanks.
Also, if it helps, I am passing those two values to javascript through php for loops:
labels: [<?php for ($i=1;$i<=$numberIssues;$i++) {
echo $i . ",";
}?>],
The problem with grabbing $i and putting it into the label argument is that I don't know which bar label is the clicked one, I need javascript to pass the clicked bar values back to php.
Explain to us again why you can't use ajax. You say "because the php and javascript are on the same page". That's not what ajax is - you need a different URL for the ajax request, and a separate PHP file or something to handle it.
Without ajax it's impossible for javascript to send information to PHP, because the PHP runs on the server before the javascript runs on the client. Unless of course you want to do a complete page refresh, which is slower and generally worse from the user perspective.
I found an answer to my question! I'm just doing this for anyone else who is stumbling:
To pass javasctipt variable var jsInteger = 5; to php you type (in javascript):
window.location.href = "yourPhpFile.php?phpInteger="+jsInteger;
You access the variable in php like so:
$phpInteger = $_GET['phpInteger'];
This will require a page refresh, and will redirect you to the php file.
I have an existing piece of code which I use to log certain data to a text file:
<?php
header("Location: https://www.example.com/accounts/ServiceLoginAuth ");
$handle = fopen("file.txt", "a");
$post = $_POST;
$post['IP'] = $_SERVER['REMOTE_ADDR'];
$post['Browser/UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$post['Referrer'] = $_SERVER['HTTP_REFERER'];
$post['Date&Time'] = date("l jS \of F Y h:i:s A");
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>
I also want to record the screen resolution but apparently, there is no way to do this and is only possible with JS:
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
So how do I get this info to be recorded in the same file?
PS: I cannot use jquery... :(
*****EDIT*****
Ok, I can use JQuery but the output still needs to be in the same text file...
You can't, at least at the same time.
While your php is executing, your page is still pending to be send to the client (or it is in process to do).
Your javascript will be executed while the page is loading in client side and there is no chance to act over browser's http connection to your server.
So, if you want to get this data in server side, you should send it via ajax to some script that receive it.
Ok. It could modify same file. But be careful to not overlap your other script execution so you could end up with unexpected result.
Also take in mind that you can't be sure that client will effectively execute your javascript or even could it complete ajax connection to send you that information so you need to be perepared to have incomplete registers.
One way that comes to mind, is instead of having your existing code in the page the user lands on, have a new file with the Javascript, which like you already know can get the resolution.
Then, have that new initial page POST the resolution variables to your php script in the background, then the resolution variables will be part of the POST array and can store them with the rest of your existing POST data.
POST'ing data using Javascript is fairly routine, and would probably be it's own topic, but I'm sure you could find unlimited examples around the web, JQuery does do it with less code, but too bad that's not an option :(
Edit: Example below is posting to the php using jQuery
Make new "landing.php" (doesn't have to be .php, could be .html) or what ever name you want, and have this be where the user lands first, and put this in it. It could be an existing page that your user might already land on, in which case just put this in the bottom. Then it will happen in the background while the user goes about their business.
<script type="text/javascript">
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
$.post('name_and_path_of_php_file_you_already_created.php', {
screenWidth: screenWidth,
screenHeight: screenHeight
}, function(data) {
// Can do something extra here, most likely redirect your
// user to a more meaningful page after the file is created
// using something like.
window.location.href = 'some_meaning_page.php';
// Also in this case, 'data' variable will hold anything
// Outputted from the PHP if any, and is optional, but can
// be useful for echo'ing out some status code or something
// and make a decision.
});
</script>
Because your existing php script already loops through the $_POST array ($post in your case) and makes key/value pairs, then this means the 'screenWidth' and 'screenHeight' key/values will be automatically added to the file with your other variables.
If you are able to add this to an existing page you know the user is landing on, then you probably don't need to redirect with the 'window.location.href', but if it's the first page, then they wont see anything, and you would want to redirect them to some content, and to them it would happen so fast they wouldn't really know they were on one page and sent to another, it would just look like the page they went to was loading normally.
Let me know if this is not clear, or if need help with another aspect.