I have the following code in my index.php page:
// Write the resulting JSON to a text file
var jsontext = $('#code-output').text();
$.ajax({
url: 'writetxt.php',
type: 'POST',
data: { data: jsontext },
success: function(result) {
$('#code-output').hide().fadeIn('slow');
}
});
And this is the contents of writetxt.php:
// Generating a unique filename using the date and time plus a random 4-digit string
$filename = date("YmdHis-") . rand(1337,9001);
// Making the JSON text file
$jsontext = $_POST["data"];
$fp = fopen("jsontxt/" . $filename . ".txt","w");
fwrite($fp,$jsontext);
fclose($fp);
Basically, a new text file is created every time a change is made to the JSON text. How do I access $filename from the index.php file?
Either include the file in the other one
require_once('my_file.php');
echo $varFrom_my_file;
or set it to a session variable
session_start();
$_SESSION['foo'] = "Bar";
Then the other file
echo $_SESSION['foo'];
I'm assuming index.php has some content along with PHP variable? Using include will include that content. Use a session variable to go across pages.
PHP Sessions
Return the value of $filename as a JSON string
echo json_encode(array('filename'=>$filename);
Then pull it out of the result var
result.filename
(untested)
Related
I am trying to upload a file with Angular JS and PHP using a formdata object.
I would like to use key1 (data) value to be JSON so I can pass the filename and user info etc. to the php script
I would like to use key2 (uploadFile), value to be the file being uploaded;
I can use POSTMAN to set a key (named data) and add a value for some JSON data {"username" : "kk1"}
then set a key (named uploadFile) and a value pointing to the test file. upload_test1.txt
The PHP succeeds and the file, upload_test1.txt is uploaded and saved to the correct location.
When I run the test using Angularjs
The PHP responds and says that the index uploadFile does not exist
The only thing i can think is that the file path is set incorrectly.
See snippets below
Any help would be appreciated
KNK53
Angular username = "kk1" id="1" and filename = "C:\temp\upload_test2.txt"
...
bdy = {
"username": username, "id": id };
var fd = new FormData();
`fd.append("data", JSON.stringify(bdy));
fd.append("uploadFile", filename);
$http.post(myurl, fd, {
transformRequest: angular.identity,
headers: { "Content-Type": undefined, "processData" : false }
})
...
// the PHP echoes the json and then "from variable:kk1 " lines 1-3
// then error Notice: Undefined index: uploadFile line 5
PHP
1 $data = json_decode($_POST["data"],true);//should have a username
2 echo 'get file:' . $_POST["data"];
3 echo 'from variable:' . $data["username"];
4 echo '<br>';
5 $user = $_FILES['uploadFile']['tmp_name'];
echo 'filename:' . $user . '<br>';
echo 'dir:' . ini_get('upload_tmp_dir');
$target_dir = "../uploads/";
$target_file = $target_dir . 'gotfile.txt';
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_file)) {
echo 'move succeeded';
}
else
echo 'move failed';
I came to that conclusion as well. I am new to WEB programming but have a lot of other programming experience. The FormData object append method does not actually upload the file.
fd.append("uploadFile", filename);
Is it best to use a directive and then incorporate the FileReader object to read the file data??
OR
I see on other stack overflow threads
that some answers use a directive only to access the "FILES" property of the input element
fd.append("file", element[0].files[0]) ??? does this actually append the file data
File Upload using AngularJS
see marker 57 of this thread??
KNK53
So I redid the functions
Using:
fd.append("file", element[0].files[0]
This sends the information as $_FILE to PHP
Using a filereader and the onreadend event:
onreadend = function(tgt) {
fdata = tgt.target.result;
fd.append("file", fdata);
.
.
.
}
This approach sends the data to $_POST in PHP
KNK53
HTML:
<input type="text" ng-model="userName" />
<input type="file" your-directive ng-model="userFile" />
In your directive's link method:
element.bind('change', function(event) {
scope.userFile = event.target.files[0]; // 'scope' here reefer to the scope where the model will be used to be posted, could be for example the parent scope (scope.$parent) or the root scope..., could even emit the new value too
});
In your controller, assuming your file is posted on a form submit event linked to the controller:
$scope.submit = function() {
var formData = new FormData();
...
formData.append('userName', $scope.userName);
formData.append('userFile', $scope.userFile, $scope.userFile.name);
...
$http({
method: 'POST',
url: <apiUrl>,
data: formData,
headers: {'Content-Type': undefined} // <-- don't forget this
...
}).then...
};
PHP:
$userName = $_POST['userName'];
$userFile = $_FILES['userFile'];
Sorry for the too many editings... got distracted
What I did so far:
Okay, so i create a blob file (wav content) and it is stored under blob:http://localhost/cf6fefdc-352e-4cec-aef8-03af6d0d0ef6.
When i put this URL into my browser, it plays the file.
What i need to do
I want to convert the blob into an actual file, that i want to store on my webserver.
I'm handing the blob object over to a php file via AJAX
$.ajax ({
type: "POST",
url:"path/to/my/file.php",
data: {thefile : blob} ,
success: function(text) {
console.log(text);
},
error:function(){
console.log("Error")
}
});
That works. If I print_r the variable it returns [object Blob]
My PHP
<?php
$file = $_POST['thefile'];
print_r($file);
Can anyone tell me how I can convert and save the file to my server from there on?
In your file.php add this code
$filePath = 'uploads/' . $_POST['thefile'];
$tempName = $_FILES['thefile']['tmp_name'];
if (!move_uploaded_file($tempName, $filePath)) {
echo 'Problem saving file: '.$tempName;
die();
}
// success report
echo 'success';
I want to achieve:
in a html-form put in some data (e.g. -wahl- and -id- )
after klicking -submit- call the javascript function -machExport-
this function validates the values and passes them (-wahl- and -id-) to the php-File -makeExport.php-
the -php-Funktion gets these values, gets some data from a mysql database, creates output-data,
writes these data into a file -data.txt- and download this file instantly to the users download-folder.
Everything works quite well, but:
after creating the data, this data is stored into the file but there is no downloading.
So, what's wrong.
(If I execute the -php-file directly by passing some values to the php-function, it works quite well,
so only if there ist the javascript function between the html- and the php-function, ist doesn't work )
Part of the code within my -html- document
<form name="form" action="" method="post" onsubmit="return machExport()" onreset="abbruch()">
Javascript-Code:
function machExport(){
var wahl = $("input[name='rd1']:checked").val();
var id = $("#id").val();
// verify these values and give an error message, if necessary
...
// if everything is ok, pass values to the -php- function
var ajxFile = 'makeExport.php';
var param = wahl + "#" + id;
$.ajax({
type: "POST",
url: ajxFile,
data: param
// if I put here a -success: function -statement,
// then the data having been created within my php-function
// is not beeing written into the requested file
// but is displayed in my html-document.
}
});
return false;
}
PHP-File -makeExport.php-
<?php
// get the values for -wahl- and -id-
...
// create data to write into file
$data = ...
// write data to file and download this file instantly
$file = "data.txt";
$fOK = file_put_contents ( $file , $data );
// up to here, it works
// but the next 3 lines are not excecuted
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
?>
I try to send a variable using jquery and ajax to php script. Then I want to use that variable in creating a file name but it fails. The file name is always "0" and does not locate at the dir "redirect".
Here is the code:
Ajax:
var pageName=$('#movie').val();
$.ajax({
type: "POST",
url: "phpstuff.php",
data: { pageName: 'pageName'},
cache: false,
success: function()
{
alert(pageName);
}
});
the "pageName" variable gets the value from an input box with an id "movie"
The php file
function createPage ($newPage){
$file=fopen("redirect/"+$newPage+".php","w") or exit("Fail to create the page");
$data = "some text I want to be in a file";
fwrite ($file, $data);
fclose($file);
}
$newPage = $_POST["pageName"];
createPage($newPage);
I have searched the net for hours and still can't fix the problem.
Line
data: { pageName: 'pageName'},
should be
data: { pageName: pageName},
A print_r( $_POST["pageName"] ) would show you what is being passed, in the first version $_POST["pageName"] is 'pageName'
You could also use
data: 'pageName='+pageName,
The description on http://api.jquery.com/jQuery.ajax/ for data parameter is'nt very clear as it talks about GET and dosn't mention POST.
String concatenation should be done with .:
"redirect/" . $newPage . ".php"
Try changing this line:
$file=fopen("redirect/"+$newPage+".php","w") or exit("Fail to create the page");
to
$file=fopen("redirect/".$newPage.".php","w") or exit("Fail to create the page");
Notice the changes from + to .. In PHP + is for addition, and . is for string concatenation.
I'm not yet a JSON/AJAX master so I don't know how to do this.
I need a $_SESSION['name'] PHP variable to work with in my jQuery stuff and I don't know how to access it... consider:
// the 'who is typing' shindig
$.ajax(
{
url: "whos_typing.html",
cache: false,
success: function(whos)
{
// here I need to access $_SESSION['name'] and do stuff with it
$("#soandso").html(whos); //Insert who's typing into the #soandso
}
});
You'll need to inject it, something like this:
var sessName = '<?php echo $_SESSION['name']?>';
The file containing this script must be executed by the php interpreter (i.e. a .php file)
EDIT: Conceding to Radu's point, it would be safer execute for unsanitized data:
var sessName = <?php echo json_encode($_SESSION['name']) ?>;
You need to use $.post to retrieve the variable from the server. You would have something like this:
$.post('echoMyVar.php', {post: 1}, function(data){
myVar = data['myVar'];
});
This is very basic, you first need to check if data is not null. In echoMyVar.php, you need just need basically the following:
header('Content: application/json', 1);
$returnVal = array('myVar', $_SESSION['myVar']);
echo json_encode($returnVal);
Again this is a shell, not secure, and would not handle any errors.
var name= "<?php echo $_SESSION['user_name'];?>"
will do it . . .
Remember php is a server side script, . . .so it takes precedence and get executed first and spits html to the client (Jquery , javacript) which will be executed in your browser . . . .
So, you can use server side variables to share with client . . . but not the other way around . . .
The easiest way is probably to include your javascript code in a .php file. Then you can simply do:
var phpVar = <?php echo $_SESSION['name']; ?>
SIMILAR POST
Server side in whos_typing.php:
<?php
//...
header('Content-Type: application/json');
echo json_encode(array(
'who'=>'Bob',
'session'=>$_SESSION,
// Be sure that you're not storing any sensitive data in $_SESSION.
// Better is to create an array with the data you need on client side:
// 'session'=>array('user_id'=>$_SESSION['user_id'], /*etc.*/),
));
exit(0);
Client side:
// the 'who is typing' shindig
$.ajax({
url: "whos_typing.php",
dataType: 'json',
cache: false,
success: function(data) {
var session = data.session,
who = data.who;
console.log(session.user_id); // deal with session
$("#soandso").html(who); //Insert who's typing into the #soandso
}
});
You need to echo the session variable from PHP when you send it to the browser. I'm assuming whos_typing.html is just the URL to a PHP script.