How to Link PHP Script with JavaScript and Bootstrap - javascript

I am trying to take a CSV file from the client side and read it in order to create arrays that can then be used in my original html file, that contains javascript, to create a dynamic table. My PHP code for parsing into arrays is:
<php?
$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
print_r($array);
?>
And my HTML (a simple file upload) is:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload CSV" name="submit">
but I am unsure as to how I should connect these pieces? Can the PHP script be in the same document as the HTML(which contains the JS to construct the table), or should it be called through a form?

Save your php script in a file eg. upload.php.
Then use the following code in your html:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload">
<input type="submit" value="Upload CSV" name="submit">
</form>

The easiest way to output the csv based on Reagan Gallant's suggestion above, is to print the data directly from upload.php. You can also add a header saying that you're serving csv, and let the browser decide what to do (save as file, display in browser):
header('Content-Type: text/csv');
print $csv;
Or you can use a javascript library such as JQuery to upload the file and return the result using ajax. This requires a little bit extra coding, but depending on your goal it might be worthwhile.

Related

How to send a file from localhost to website

I want to send a preselected file (/tmp/test.txt) to a website (upload site) and get the response (shows a link to the uploaded file).
I have googled so much and didnt get it to work.
the following easy html form is working.
<html>
<body>
<form action="http://upload-site/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="testfile" value="select file" >
<input type="submit" value="Submit">
</form>
</body>
</html>
so i all need to send is the enctype und the file with info "testfile=test.txt" i guess ??
the form ofc wants me to select a file...what i dont want.
it has to be preselected since i want to automate the upload procedure and work with the response that gives me the link to the file.
how do i do that in php/curl/js ?
You have to use different approach to send your file to another website. You're transferring file over the server(technically over two machine). You could do it by FTP. Fortunately, PHP provides you functionality for this.
<?php
$file = 'somefile.txt'; // Path of the file on your local server. should be ABSPATH
$remote_file = 'somefile.txt'; // Path of the server where you want to upload file should be ABSPATH.
// set up basic connection
$conn_id = ftp_connect($ftp_server); // $ftp_server can be name of website or host or ip of the website.
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
I've never tried from localhost to website (Server). Give it try and let me know your feedback for this.
Without seeing your upload.php its hard to help you, but if you want to copy the selected uploaded file to a destination on your server and then display it in the browser you need to do something like this in the file upload.php which is your forms action.
//Get the file name
$file_name = $_FILES["testfile"]["name"];
//Create destination path
$dest = "/path/to/where/you/want/the/file/" . $file_name;
//Move the file
move_uploaded_file($_FILES["testfile"]["tmp_name"], $dest)
//View the file
echo "<script> location.href='http://someip/$dest'; </script>";
I think you need to change this
<input type="file" name="testfile" value="select file">
To this
<input type="file" name="testfile" id="testfile" value="select file">
You will notice im using JavaScript to redirect the browser to the newly uploaded file, you can also just send a new HTTP header using native PHP.
header("Location: http://example.com/thefile.txt") or die("Failed!");
You can read about what you think is the best approach for the redirect here.
I hope this helps?

Upload (not read) a .xlsx file from HTML and send it (any way) to a PHP file

I have an .xlsx file and a html file with an < input type="file">. I just need upload it and send it to a php file (with js or any other way).
The php file expects an .xlsx file (for this reason I dont parse the .xlsx.) if I load it direct in the php file, works perfectly but I need to upload through an user interface, in this case an html view.
Regards.
Update:
Now the .html looks like this:
<div class="MainContainerPrice">
<form action="php/excel_to_mysql.php" method="POST">
<input type="file" name="excel" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
<input type="submit">
</form>
</div>
And the .php looks like this:
<?php
include 'simplexlsx.class.php';
$file = $_FILES['excel'];
$xlsx = new SimpleXLSX('pricesExcel.xlsx'); //the file directly uploaded that I need to send from html.
...
?>
But now I have the next error:
Undefined index: excel in ...\excel_to_mysql.php on line 2.
Why doesn't recognize the name?
You need a bit of tweaking in the html and in the PHP part
<div class="MainContainerPrice">
<form action="php/excel_to_mysql.php" method="POST" enctype="multipart/form-data">
<input type="file" name="excel" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
<input type="submit">
</form>
</div>
Note the enctype="multipart/form-data". That's needed to actually send the file.
The in the PHP file
<?php
include 'simplexlsx.class.php';
$file = $_FILES['excel']['tmp_name'];
$xlsx = new SimpleXLSX($file); //the file directly uploaded that I need to send from html.
...
?>
$_FILES['excel']['tmp_name'] contains the full path to the uploaded file, note that you can't rely on the name having the '.xlsx' extension, cause the file gets a random name for security purposes.
I strongly suggest you to use the file from within the temporary directory, and to delete it after use.
If the SimpleXLSXclass needs the '.xlsx' extension to work properly, you can try to add it to the temp file
rename($_FILES['excel']['tmp_name'],$_FILES['excel']['tmp_name'].'.xlsx');

Submit button with POST instead of using HTML form

I have a form inside a form and this makes the top form unresponsive. When I take off the second form (which is inside the first form), the first form works. This is the second form I have:
<form action="imgupload.php" method="post" enctype="multipart/form-data">
<h3>Upload a new image:</h3>
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup">
</form>
Since this makes the first form not work, I was wondering if I can take off the form fields and then the submit button can send the form data to the imgupload.php like this.
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup" action="imgupload.php" method="post" enctype="multipart/form-data">
This does not work now. Is there a way I can get this working? If not, what's an alternative way to send this data to the other php?
Since you are uploading files, have a look at Ravi Kusuma's Hayageek jQuery File Upload plugin. It's simple, it's a Swiss Army Knife, and it works.
Study the examples.
http://hayageek.com/docs/jquery-upload-file.php
Ravi breaks down the process into three simple steps, that basically look like this:
<head>
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet"> // (1)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2)
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3)
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final step is to have the PHP file specified in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename specified in the jQuery code block.
Don't forget to check out the server-side code from the Server Side tab -- you need both parts (js and php).
Looking at your question again, you will probably want to use this functionality as well:
dynamicFormData: function()
{
var data ={ location:"INDIA"}
return data;
}
or
dynamicFormData: function(){
return {
newID: $("#newNID").val(),
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
formRole: $('#formRole').val()
};
These will appear on the PHP side, thus:
$newID = $_POST['newID'];
$subj = $_POST['newSubj'];
etc
As with any plugin, resist the temptation to just plop it into your code. Do a couple of quick-and-dirty tests with it first. Kick its tires. Fifteen minutes will save you two hours.
And don't forget to verify what was uploaded. You never know when a developing country black hat might be trying to get a new account.

Create a local file from user input and list existing files

I need to use the input from a user to create a filename.html on the server they are attached to. The program normally takes the input and writes it TO an existing html file. In this one case, I need to add the ability to create the file they are writing to before they begin writing to it.
While I am wishing :) I would like to start out by showing the user a directory of the html files are already there in case someone else has already created it.
The logic of the input would be to use the data input to create the file IF the file does not already exist. If it does exist, then they would open to the pre-existing file by that name.
This is an adaptation of "Microchat" php script which normally writes to msg.html.
It works fine as-is but this one project needs the added ability of creating multiple Name.html files and then letting the user continue as normal except they will be writing to the filename they chose or created rather than the using the generic msg.html. I have been working on the assumption that I will have to create a variable of their input to use for creating the file.
The entire script for Microchat is only 144 lines. But too long to post in its entirety
It can be viewed at www.phptoys.com. The area I need help with is this:
function createForm () {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table align="center">
<tr><td colspan="2">Please eneter a nickname to login!</td></tr>
<tr><td>Your name: </td>
<td><input class="text" type="text" name="name" /></td></tr>
<tr><td colspan="2" align="center">
<input class="text" type="submit" name="submitBtn" value="Login" />
</td></tr>
</table>
</form>
<?php
This is normally used to create the users login. I have tried a few variations on the input to achieve a variable for creating a file but sadly, I know my limits. I doubt I will find a way without help.
I am not sure what you are trying to make. Possibly you can use database for the purpose but purpose is not clear to me so I don't know. By the way you can use following approach. Then you can do customization as per your requirements.
<?php
$fileName = "newHTMLFileName";
$path= "../yourFolder/".$fileName.".html";
if (!file_exists ($path))
{
$code = "<!DOCTYPE html><html><body><h1>Information</h1></body></html>";
$handle = fopen ($path, "w");
$write = fwrite ($handle,$code);
fclose($handle);
echo "created";
}
else
{
echo "already created";
}
?>

sending information into an IP through Html

I'm using making a web based microcontroller and now I want to send some sort of data to my microcontroller through a Html page .
can I do that in a raw Html file or I should use other programs like javascript or perhaps php
can every one give me some simple source code
Easiest way i could imagine is making a button, with a PHP script attached, and that PHP Execute a compiled binary that does something in your microcontroller.
Example:
index.html
<html>
<body>
<Form Name ="form1" Method ="POST" ACTION = "send.php">
First name: <input type="text" name="fname"><br>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</body>
</html>
send.php:
<?php
echo "<html><body>";
echo "The microcontroller say:"+exec('microcontrollerbinary $_POST['fname']');
echo "</body></html>";
?>
Your microcontroller should have a binary who read first argument from command line 'fname' and printout something

Categories

Resources