PhP Curl SFTP File Editing - php

I am trying to create a online editor for multiple server. I want to edit a custom file on a server and I need to get it via sftp. My current code looks like this:
<?php
$user="user";
$pass = 'pass';
$c = curl_init("sftp://$user:$pass#0.0.0.0/path/to/file/file.txt");
curl_setopt($c, CURLOPT_PORT, 3206);
curl_setopt($c, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);
//the next line is not working and from now on am I stuck
$text = file_get_contents($fh);
?>
<!-- HTML form -->
<form action="" method="post">
<textarea name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input
type="submit" />
<input type="reset" />
</form>
I want to edit this file on the website and then reupload it to the sftp server in the same directory (overweite the existing one). I do not know how to continue. Thanks for the help.

First off if it's a file containing some programming language, check ACE.js.
It's simply an incredible JS module for use as a web IDE and it has all the features any programmer looks for in an IDE, it's so good I would ALMOST consider switching to it as my primary IDE.
Then use this PHP code:
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$filename = 'sftp://user#location/file/name.js';
//Use SSH public key authentication
$handle = fopen($filename,'w') or die('Cannot open file: '.$filename);
$data = $_POST['src'];
fwrite($handle, $data);
fclose($handle);
?>
and use this JS code to call the PHP script:
<script src="../scripts/ace/ace.js" type="text/javascript"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme('<?php echo $theme; ?>');
editor.getSession().setMode("<?php echo $language; ?>");
editor.setShowPrintMargin(false);
editor.setReadOnly(true);
<?php //Save shortcut binding ?>
editor.commands.addCommand({
name: 'Save',
bindKey: {win: 'Ctrl-S', mac: 'Command-S'},
exec: function(editor) {
var xhr = new XMLHttpRequest();
xhr.open("POST", './scripts/save_file.php', true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(
JSON.stringify(
{src:editor.getValue()}
)
);
}
});
</script>

Related

Open php file, change value for one variable, save

I am trying to modify the value of a variable $denumire produs=' '; from a php file _inc.config.php through a script by this code with form from file index.php and i have some errors.
The new value of the variable will become value entered from the keyboard via the form.
Anyone can help me, please?
<?php
if (isset($_POST['modify'])) {
$str_continut_post = $_POST['modify'];
if (strlen($_POST['search']) > 0 || 1==1) {
$fisier = "ask003/inc/_inc.config.php";
$fisier = fopen($fisier,"w") or die("Unable to open file!");
while(! feof($fisier)) {
$contents = file_get_contents($fisier);
$contents = str_replace("$denumire_produs =' ';", "$denumire_produs ='$str_continut_post';", $contents);
file_put_contents($fisier, $contents);
echo $contents;
}
fclose($fisier);
die("tests");
}
}
?>
<form method="POST" action="index.php" >
<label>Modifica denumire baza de date: </label>
<input type="text" name="den">
<button type="submit" name="modify"> <center>Modifica</center></button>
</div></div>
</form>
This is an XY problem (http://xyproblem.info/).
Instead of having some sort of system that starts rewriting its own files, why not have the file with the variable you want to change load a json config file?
{
"name": "Bob",
"job": "Tea Boy"
}
Then in the script:
$json = file_get_contents('/path/to/config.json');
$config = json_decode($json, true);
$name = $config['name'];
Changing the values in the config is as simple as encoding an array and putting the json into the file.
$config['denumireProdu'] = 'something';
$json = json_encode($config);
file_put_contents('/path/to/config.json', $json);
This is far saner than getting PHP to rewrite itself!
Docs for those commands:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.file-put-contents.php

PHP - Obtain data from an external script and use it in the current form

I have created a script that will work as a plugin for Wordpress whose purpose is to get the data of the videos of a page (video title, video url, thumb url and total videos found).
My plugin works but the script is on the same page where the results are loaded so that it stays in Wordpress. But I want to externalize the script in charge of doing the search because I sincerely do not want them to be able to visualize my php source code.
So I tried to separate my script and just put the html and invoke the script using the "action" form.
But I do not know how to pass the loops of my external script to the local form nor how to pass the values of the variables. I tried to use the "return" and "Header Location" but it does not work.
Here is what I currently have:
Index.php:
<?php
if (isset($_POST['search'])){
$url = $_POST['keyword'];
$parse = "http://example1.com/?k=".$url;
$counter = 0;
$html = dlPage($parse); //dlPage is a function that uses "simple_html_dom"
include("form_results_footer.php"); // I include the header of the page with the results (this part is outside the loop because I do not want it to be repeated).
foreach ($html->find('something') as $values) {
//Here I run a series of searches on the page and get the following variables.
$counter++;
$title = //something value;
$linkvideo = //something value;
$thumburl = //something value;
include("form_results.php"); //The results of the "foreach" insert them into a separate php in "fieldsets".
}
$totalvideos = $counter;
include("form_results_footer.php"); //Close the form results
} else {
?>
<html>
<form action="" method="post">
<input id="keyword" name="keyword" type="text">
<button id="search" name="search">Search</button>
</form>
</html>
<?php
}
?>
Ok, the code above works fine but I need to outsource the part where I get the variables of the part where I will receive them, something like this:
-> http://example.com/script.php
<?php
if (isset($_POST['search'])){
$url = $_POST['keyword'];
$parse = "http://example.com/?k=".$url;
$counter = 0;
$html = dlPage($parse); //dlPage is a function that uses "simple_html_dom"
foreach ($html->find('something') as $values) {
//Here I run a series of searches on the page and get the following variables.
$counter++;
$title = //something value;
$linkvideo = //something value;
$thumburl = //something value;
}
$totalvideos = $counter;
return $title;
return $linkvideo;
return $thumburl
}
?>
index.php
<html>
<form action="http://example.com/script.php" method="post">
<input id="keyword" name="keyword" type="text">
<button id="search" name="search">Search</button>
</form>
</html>
The loop results would have to be collected on the same page in the same way as in the initial example.
I hope you let me understand, thank you in advance.
Change form action url to self page in index.php and do cURL there which calls your another domain where logic is placed. that mean http://example.com/script.php
index.php
<html>
<form action="" method="post">
<input id="keyword" name="keyword" type="text">
<button id="search" name="search">Search</button>
</form>
</html>
<?php
if (isset($_POST['search'])) {
//your URL
$url = "http://example.com/script.php?keyword=" . $_POST['keyword'];
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
}
?>
And in http://example.com/script.php you just need to change $_POST['keyword'] to $_GET['keyword'] and few more change to return data.
scrip.php (from another domain)
<?php
if (isset($_GET['keyword'])) {
$url = $_GET['keyword'];
$parse = "http://example.com/?k=" . $url;
$counter = 0;
$html = dlPage($parse); //dlPage is a function that uses "simple_html_dom"
$return = array(); //initialize return array
foreach ($html->find('something') as $values) {
//Here I run a series of searches on the page and get the following variables.
$return['video_data'][$counter]['title'] = //something value;
$return['video_data'][$counter]['linkvideo'] = //something value;
$return['video_data'][$counter]['thumburl'] = //something value;
$counter++;
}
$return['total_video'] = $counter;
echo json_encode($return); //return data
}
?>
I hope this is what you want.

Need help to make this curl script multi links

Here is the script it downloads files from url. The thing that I want is multi links like there should be three or more input url boxes in which user puts their links and the script downloads all the files. I don't want to press a button and another url box appear; that is not I want, I have already tried that. Or multi links; something like this where we can put links on each line:
<?php
class Download {
const URL_MAX_LENGTH=2000;
// clean url
protected function cleanUrl($url){
if (isset($url)){
if (!empty($url)){
if(strlen($url)< self::URL_MAX_LENGTH){
return strip_tags($url);
}
}
}
}
//is url
protected function isUrl($url){
$url=$this->cleanUrl($url);
if (isset($url)){
if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)){
return $url;
}
}
}
//return extension
protected function returnExtension($url){
if ($this->isUrl($url)){
$end = end(preg_split("/[.]+/", $url));
if (isset($end)){
return $end;
}
}
}
// file download
public function downloadFile($url){
if ($this->isUrl($url)){
$extension = $this->returnExtension($url);
if ($extension){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
curl_close($ch);
// directory where files should be downloaded
$destination = "uploads/file.$extension";
$file = fopen($destination, "w+");
fputs($file, $return);
if (fclose($file)) {
echo "Successfully Download The File";
}
}
}
}
}
$obj = new Download();
if (isset($_POST['url'])) { $url = $_POST['url'];}
?>
<form action="index.php" method="post">
<input type="text" name="url" maxlength="2000">
<input type="submit" value="Download" />
</form>
<?php if (isset($url)) { $obj->downloadFile($url); }?>
Break string into array using \n as delimiter, you will get array of URLs. check below example to use explode.
Note: Use <textarea>, if you use input and press enter then form will get submitted.
<form action="" method="post">
<textarea type="text" name="url" maxlength="2000"></textarea>
<input type="submit" value="Download" />
</form>
<?php
if(isset($_POST['url'])){
$urls = explode("\n",$_POST['url']);
}
foreach ($urls as $url) {
echo $url;
//$obj->downloadFile($url);
}
?>

Pass PHP variable to javascript src [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Okay, so I have a php variable which stores:
http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback
This is working fine and i want to do the following:
<script type="text/javascript" src="<?php echo $string; ?>"></script>
But it doesn't seem to be working
Thanks for any help
EDIT:
Here is my code, tried all 3 answers below but didn't work:
http://pastebin.com/xYKW8TTd
This seems to work as expected:
<?php
$string="http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback";
?>
<script type="text/javascript" src="<?php echo $string; ?>"></script>
with the output of:
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
Edit: in your source code on pastebin, you seem to have:
$string = "http://gdata.youtube.com/feeds/api/videos/" . $id ."?v=2&alt=json-in-script&callback=youtubeFeedCallback";
which contains & in the place of & which would stop the link working. Was this somethign that pastebin did or was it in your original code?
You can't send HTML codes to the URL window and expect it to work the same way as if it was in a HTML body.
The following code (just edited $id as I am not putting anything in GET and modified & symbols gave:
<html>
<head>
<?php
//$id = $_GET['id'];
$id=0;
$string = "http://gdata.youtube.com/feeds/api/videos/" . $id ."?v=2&alt=json-in-script&callback=youtubeFeedCallback";
?>
<title></title>
</head>
<body>
<?php echo $string; ?><br>
<script type="text/javascript" src="<?php echo $string; ?>"></script>
Had the output of:
<title></title>
</head>
<body>
http://gdata.youtube.com/feeds/api/videos/0?v=2&alt=json-in-script&callback=youtubeFeedCallback<br>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/0?v=2&alt=json-in-script&callback=youtubeFeedCallback"></script>
Try this:-
<?php
$str = 'http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback';
?>
<script type="text/javascript" src="<?php echo $str; ?>"></script>
<?php
$string = 'http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback';
?>
<script type="text/javascript" src="<?=$string;?>"></script>
Try this:
echo "<script type=\"text/javascript\" src=\"".$string"\"></script>\n";
If this "does not work", you have some error in string constant which cause javascript error.
Please provide more info, like generated source or exact browser error.
UPDATE:
#user1641732 : As of Mahan's comment. You are including JSON object, not javascript.What you are try to achieve? Did you understand difference between JSON object and javscript code?
Why are you trying to do this? Surly the best way to retrieve data from YouTube would be to do a php cUrl request and decode the json data their, or alternatively, if you really have to you can save the contents to a file with file_put_contents or fopen.
Here is a cUrl example, add your own $url variable:
// get the data via curl
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_ENCODING, "" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
$rsp = json_decode(curl_exec($ch));
curl_close($ch);
<?php
$string = "http://gdata.youtube.com/feeds/api/videos/gzDS-Kfd5XQ?v=2&alt=json-in-script&callback=youtubeFeedCallback";
?>
<script type="text/javascript" src="<?php echo $string; ?>"></script>

javascript return function's data as a file

I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.

Categories