how do i copy a file on button click? - php

I want to build a one page utility/prototype that will do the following:
provide the admin user with a drop down box. when they select an option and then click on a submit button, i want to be able to COPY a file from /var/www/mysite/abc.txt to /var/www/mysecondsite/abc.txt
I've written the php / html to display the form, but can I use jquery/ajax to call a function on the same php file?
Here's my code:
<?php
$listofcountries='';
echo "<h2>Select a site</h2>";
echo " <script src='http://myserver/myapp/assets/js/jquery-1.8.1.min.js'></script>";
if ($handle = opendir(dirname(__FILE__)."/secrets/")) {
echo "<input type=text list=site >";
echo "<datalist id=site >";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
//ignore temporary files, and directories.
if ( (strpos($entry, "~") === false) && !(trim($entry)==".") && !( $entry=="..") ){
//echo "$entry\n<BR>";
$country=getCountryName($entry);
echo "<option>".$country;
}
}
}
closedir($handle);
echo "</datalist>";
echo "<input type=submit id='changert'><BR>";
echo "<script>";
echo "$(document).ready(function(){";
echo " $('#changert').live('click', function() {";
echo " alert('in the changert function'); ";
echo " });";
echo " }); "; //end document ready
echo "</script> "; //end javascript
function getCountryName($fileame)
{
$pattern = '/([a-z]*).([a-z]*).([a-z]*).php/i';
preg_match_all($pattern, $fileame, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
return $match[1];
}
}
in the real version, this solution will be part of a codeigniter solution... so i'll have a proper MVC.
But for now, I'd like to be able to contain all the logic in one file.
Can you tell me how i can do this?

jQuery is just JavaScript so it's all on the client. Any server-side file copying would still need to be handled by your PHP. Simplest solution is just to make an AJAX request on button click which hits your PHP API and passes a token or something so non-session users aren't copying files maliciously.
$('#myButton').on('click', function(e) {
$.ajax({
url : '/copyFile.php',
data : {
fileName : $('#mySelectMenu').val(),
token : someTokenYourPHPInjectedIntoYourJS
},
type : 'POST',
success : function (data) {
// yay
}
});
});

You should check PHP Documentation at: http://mx2.php.net/manual/en/function.copy.php
There's an exaple to copy a file.
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
Remember this directories must exists and be visible to each other (inside the same web server)

Add an Ajax call on your user interface,
$.ajax({
url: 'copy.php',
success: function(data) {
if(data == 'true'){
alert('The file has been copied');
}
}
});
Create a second php file to handle the file copy on request
/* copy.php */
<?php
$result = copy('/dir1', '/dir2');
echo $result?'true':'false';
Of curse, this is over-simplified, you have to do some error-handling input-checking and security improvements, but I just wanted to illustrate the way to go.

Related

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

attach a file from directory and send to email with codeigniter

I am a newbie with codeigniter and I want to build a website using codeigniter framework. From first, it look fine I can use database, validation, email, session and then I try to attach a file and send with email :
$this->email->attach('/path/ofyour/constan/file.anything');
thats work too.
since that is a website I want my client to choose file they want to upload.
I try many method, and many of them tell to upload a file to server root and get the file_data, use file_data[file_patch]
$this->email->attach('file_data[file_path]');
the problem is:
since code igniter cant upload multiple data I must use plugin. I tried and its PAIN
I thing its not effective, upload data to server root and then to email?
it better to just get file_path of upload file and send them to email, how?
I build it with jquery mobile, what must I do?
Update
ok i decide to use uploadify i search every website and then i found here and my code is
uploadify.php
<?php
/*
* Functions taken from CI_Upload Class
*
*/
function set_filename($path, $filename, $file_ext, $encrypt_name = FALSE)
{
if ($encrypt_name == TRUE)
{
mt_srand();
$filename = md5(uniqid(mt_rand())).$file_ext;
}
if ( ! file_exists($path.$filename))
{
return $filename;
}
$filename = str_replace($file_ext, '', $filename);
$new_filename = '';
for ($i = 1; $i < 100; $i++)
{
if ( ! file_exists($path.$filename.$i.$file_ext))
{
$new_filename = $filename.$i.$file_ext;
break;
}
}
if ($new_filename == '')
{
return FALSE;
}
else
{
return $new_filename;
}
}
function prep_filename($filename) {
if (strpos($filename, '.') === FALSE) {
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part) {
$filename .= '.'.$part;
}
$filename .= '.'.$ext;
return $filename;
}
function get_extension($filename) {
$x = explode('.', $filename);
return '.'.end($x);
}
// Uploadify v1.6.2
// Copyright (C) 2009 by Ronnie Garcia
// Co-developed by Travis Nickels
if (!empty($_FILES)) {
$path = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
//$client_id = $_GET['client_id'];
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = prep_filename($_FILES['Filedata']['name']);
$file_ext = get_extension($_FILES['Filedata']['name']);
$real_name = $file_name;
$newf_name = set_filename($path, $file_name, $file_ext);
$file_size = round($_FILES['Filedata']['size']/1024, 2);
$file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES['Filedata']['type']);
$file_type = strtolower($file_type);
$targetFile = str_replace('//','/',$path) . $newf_name;
move_uploaded_file($file_temp,$targetFile);
$filearray = array();
$filearray['file_name'] = $newf_name;
$filearray['real_name'] = $real_name;
$filearray['file_ext'] = $file_ext;
$filearray['file_size'] = $file_size;
$filearray['file_path'] = $targetFile;
$filearray['file_temp'] = $file_temp;
//$filearray['client_id'] = $client_id;
$json_array = json_encode($filearray);
echo $json_array;
}else{
echo "1";
}
i dont relly know what is going on here, like i said i am a newbie but i know something that $json_array, that array hold my data $filearray, that is data file uploaded. mission one complete
now my controller: upload.php
<?php
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
/*
* Display upload form
*/
function index()
{
$this->load->view('view');
}
/*
* Handles JSON returned from /js/uploadify/upload.php
*/
function uploadify()
{
//Decode JSON returned by /js/uploadify/upload.php
$file = $this->input->post('filearray');
$data['json'] = json_decode($file);
$this->load->view('uploadify',$data);
}
}
/* End of File /application/controllers/upload.php */
my plan is send the data in onComplete function
my view :view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<<head>
<meta charset="UTF-8">
<title>Uploadify and Codeigniter Tutorial</title>
<?php
$this->load->helper('html');
echo link_tag('http://uploadify_tutorial/uploadify/uploadify.css');
echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/swfobject.js" type="text/javascript"></script>';
echo '<script src="http://localhost/uploadify_tutorial/uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>';
$uploadpath="";
$uploadpath=str_ireplace($_SERVER['DOCUMENT_ROOT'],"", realpath($_SERVER['SCRIPT_FILENAME']));
$uploadpath=str_ireplace("index.php","",$uploadpath);
?>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#upload").uploadify({
uploader: '<?php echo base_url();?>uploadify/uploadify.swf',
script: '<?php echo base_url();?>uploadify/uploadify.php',
cancelImg: '<?php echo base_url();?>uploadify/cancel.png',
folder: '/uploads',
scriptAccess: 'always',
multi: true,
'onError' : function (a, b, c, d) {
if (d.status == 404)
alert('Could not find upload script.');
else if (d.type === "HTTP")
alert('error '+d.type+": "+d.status);
else if (d.type ==="File Size")
alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
else
alert('error '+d.type+": "+d.text);
},
'onComplete' : function (event, queueID, fileObj, response, data) {
//Post response back to controller
$.post('<?php echo site_url('upload/uploadify');?>',{filearray: response},function(info){
$("#target").append(info); //Add response returned by controller
});
}
});
});
</script>
</head>
<body>
<h1>Uploadify Example</h1>
<?php echo form_open_multipart('upload/index');?>
<p>
<label for="Filedata">Choose a File</label><br/>
<?php echo form_upload(array('name' => 'Filedata', 'id' => 'upload'));?>
Upload File(s)
</p>
<?php echo form_close();?>
<div id="target">
</div>
</body>
</html>
my view : uploadify
<html>
<ul>
<li>Extension: <?php echo $json->{'file_ext'};?></li>
<li>File Size: <?php echo $json->{'file_size'};?></li>
<li>File Path: <?php echo $json->{'file_path'};?></li>
</ul>
</html>
and then parsing that json_array variable to my view, that is the plans, but in reality that code doesn work the data is undefined
an error Trying to get property of non-object i use this code here, I suppose the problem is with json
i just want to use the data file uploaded if anyone can solve that problem please share it or send me CI+uploadify program to my email, if anyone expert about CI and Uploadify plugin please make the tutorial step by step how to use it, step by step, i think it would be great help for newbie like me
thanks....
my email :saya.dean#gmail.com
I'm not really clear on where you are running into a problem. 'that variable' will be the files you uploaded, yes? Create an array of the filepaths as they get uploaded and when the upload is done cycle through each for email attachment.
Have you checked other answers on the site? Maybe take a look here. But CI's documentation clearly states that you can use:
$this->email->attach('/path/to/that_file.jpg');
multiple times.
Update:
You can either try using the onUploadSuccess function in uploadify to append each file name to something that you can use later...
'onUploadSuccess' : function(file, data, response) {
alert('The file name is ' + file.name);
...
OR from within uploadify.php. From there you can store what you need for attaching after.
In your case I'd stick with modifying the uploadify.php. You'll have to give it a shot and post some code if you are stuck, but there are plenty of places to get some ideas like here and here

Using jQuery .load() to pass a parameter to and call a php function

This is the jQuery .load function I have. What I want to do is run the php function with a passed value from the jQuery. I think I just don't understand how to pass values with jQuery to the server. Do I perhaps need to use .get or .post? Please advise.
$(document).ready(function(){
$("#scotland").click(function() {
$("#Main").load('thumbs.php #Main', $path=./scotland);
});
});
php div that the jQuery script targets.
<div id="main">
<?php
function thumbnailload($path)
{
$dir_handle = #opendir($path) or die("Unable to open folder");
while (false !== ($file = readdir($dir_handle))) {
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file)){
echo "<a href='$path/$file'><img class='thumbnail' src='$path/thumbs/thumb_$file' alt='$file'></a>";
}
}
closedir($dir_handle);
}
thumbnailload($path);
?>
</div>
It is usually in early to have this kind of problem, not knowing how to interact with a client-side language (JavaScript) to a server-side (PHP). But let's go!
For the page "thumbs.php" receives a parameter, you must send the data via GET or POST.
Javascript:
$(document).ready(function(){
$("#scotland").click(function() {
$("#Main").load('thumbs.php', {'path': 'scotland'});
});
});
thumbs.php
<div id="main">
<?php
if(!empty($_REQUEST['path'])) { // i used $_REQUEST because it receives the data from POST or GET.
$path = $_REQUEST['path'];
$dir_handle = #opendir($path) or die("Unable to open folder");
while (false !== ($file = readdir($dir_handle))) {
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file)) {
echo "<a href='$path/$file'><img class='thumbnail' src='$path/thumbs/thumb_$file' alt='$file'></a>";
}
}
closedir($dir_handle);
}
?>
</div>
The method .load() in jquery uses a GET request type if the data is not passed. In our case, I am passing data ( {'path': 'scotland'} ), so the request is of type POST.
Useful links:
jQuery .load()
PHP.net - Variables From External Sources
I hope I was helpful =]
change you jQuery script to:
$(document).ready(function(){
$("#scotland").click(function() {
$("#Main").load('thumbs.php #Main', {'func': 'thumbnailload', 'path': './scotland'});
});
});
and change PHP code to:
<div id="main">
<?php
$func = $_GET['func'];
switch($func){
case 'thumbnailload':
thumbnailload($_GET['path']);
break;
}
function thumbnailload($path)
{
$dir_handle = #opendir($path) or die("Unable to open folder");
while (false !== ($file = readdir($dir_handle))) {
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file)){
echo "<a href='$path/$file'><img class='thumbnail' src='$path/thumbs/thumb_$file' alt='$file'></a>";
}
}
closedir($dir_handle);
}
thumbnailload($path);
?>
</div>
for ref: http://api.jquery.com/load/

Send/receive data via jQuery to/from PHP

I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>
There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.
The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/
Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Categories