Jump to content

Recommended Posts

Hey,

sorry to keep buggin everying.

 

I have been staring at this peice of code for about the last 3 hours now and cant get my head around why its not working.

Basically im trying to upload a file with a random name to avoid having an image with the same name bein uploaded and over written.

 

here is the code im using:

<?php
if (!empty($_FILES)) {

// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER','files/');
// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', true);
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');

    // get file name (not including path)
    $filename = @basename($_FILES['filename']['tmp_name']);

    // filename of temp uploaded file
    $tmp_filename = $_FILES['filename']['tmp_name'];

    $file_ext = @strtolower(@strrchr($filename,"."));
    if (@strpos($file_ext,'.') === false) { // no dot? strange
      $errors[] = "Suspicious file name or could not determine file extension.";
      break;
    }
    $file_ext = @substr($file_ext, 1); // remove dot

    // destination filename, rename if set to
    
      $dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
    
    // append predefined string for safety
    $dest_filename = $dest_filename . APPEND_STRING;

    // get size
    $filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);

    // make sure file size is ok
    if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
      $errors[] = "File is too big (3).";
      break;
    }

    if (!@move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
      $errors[] = "Could not upload file (6).";
      break;
    }
}
echo '1';

?>

That doesnt work.

 

 

This does work:

<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);

move_uploaded_file($tempFile,$targetFile);
}

echo '1';

?>

 

Can someone help me fix this so that it will do what its meant to do.

 

Thanks

Rich

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/
Share on other sites

Remove all the @ from the code as they are hiding the error messages that would tell you why your code is not working.

 

One guess is that your form field name is 'Filedata' but in the code that does not work you are using 'filename'.

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-814173
Share on other sites

What doesn't work? Is it giving you an error? Not uploading a file? What?

It doesnt upload the file, theres no errors, nothings showing up.

 

Remove all the @ from the code as they are hiding the error messages that would tell you why your code is not working.

 

One guess is that your form field name is 'Filedata' but in the code that does not work you are using 'filename'.

its bein called from a diffirent page, its an ajax request so no errors show up anyway. With or without the @'s

 

 

Its a seperate page ebin called by an ajax request so that might not make a diffirence.

 

Thanks

Rich

Just do an if/else.

 

if ( file_exists($filename) )

{

//execute

} else {

//execute

}

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-814181
Share on other sites

well the above code is located in upload.php

it works fine with this:

<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);

move_uploaded_file($tempFile,$targetFile);
}

echo '1';

?>

but that has the possibility of 2 files with the same name bein uploaded and one being over-written.

 

this is the page that upload.php is called from:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Uploadify scriptData Sample</title>

<link rel="stylesheet" href="uploadify/uploadify.css" type="text/css" />

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.js"></script>

<script type="text/javascript">

$(document).ready(function() {
$("#fileUpload2").fileUpload({
	'uploader': 'uploadify/uploader.swf',
	'cancelImg': 'uploadify/cancel.png',
	'script': 'uploadify/upload.php',
	'folder': 'files',
	'multi': true,
	'buttonText': 'Select Files',
	'checkScript': 'uploadify/check.php',
	'displayData': 'speed',
	'simUploadLimit': 2
});

});

</script>
</head>

<body>
      <fieldset style="border: 1px solid #CDCDCD; padding: 8px; padding-bottom:0px; margin: 8px 0">
    	<p></p>
<hr width=100% size="1" color="" align="center">
	<h2>Multiple File Upload</h2>
	<p>checkScript, buttonText, simulataneous upload limit</p>
	<div id="fileUpload2">You have a problem with your javascript</div>
	<a href="javascript:$('#fileUpload2').fileUploadStart()">Start Upload</a> |  <a href="javascript:$('#fileUpload2').fileUploadClearQueue()">Clear Queue</a>
    	<p></p>
    </fieldset>
</body>
</html>

 

Thanks

Rich

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-814194
Share on other sites

Yes, use the information that has already been posted -

 

One guess is that your form field name is 'Filedata' but in the code that does not work you are using 'filename'.

The upload code you are using sets $_FILES['Filedata'] by default unless you specify a value for fileDataName, so the code using $_FILES['filename'] would never work.

 

You need to recreate the scenario so you know what the error is. Try doing the same thing without ajax so you know the file upload is working before you go to that step. All you should have to do is make a regular file upload form instead of ajax.

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-814592
Share on other sites

Yes, use the information that has already been posted -

 

One guess is that your form field name is 'Filedata' but in the code that does not work you are using 'filename'.

The upload code you are using sets $_FILES['Filedata'] by default unless you specify a value for fileDataName, so the code using $_FILES['filename'] would never work.

 

You need to recreate the scenario so you know what the error is. Try doing the same thing without ajax so you know the file upload is working before you go to that step. All you should have to do is make a regular file upload form instead of ajax.

 

As stated before, the upload works fine, its just when i try to randomly generate a name to avoid havin 2 with the same filename being uploaded.

 

its only the random generate bit that doesnt work, if that worked the file would upload normally.

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-814600
Share on other sites

if it works fine with certain code try this....

<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . time() . $_FILES['Filedata']['name'];

// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);

move_uploaded_file($tempFile,$targetFile);
}

echo '1';

?>

 

i time() to the file name which will always be different, since its seconds elapsed since the "beginning of time".

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-814666
Share on other sites

Hey all,

 

I have the upload script just as its meant to thanks to darsuperhero,

but now for some reason the mysql qont add it to the database,

so im asking for a fresh pair of eyes on this code.

 

<?php
if (!empty($_FILES)) {

include("data.php");
mysql_connect($server,$anvandare, $losen);
mysql_select_db($databas);
$query = mysql_query("SELECT * from richspri_social.users WHERE username = '".$_COOKIE["twusername"]."'") or die ('Error: '.mysql_error ());
while ($r = mysql_fetch_array($query)) {
$myid = $r['id'];
$id = $r['id'];
}
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_GET['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . time() . $_FILES['Filedata']['name'];

// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
  $m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
      //$m_size = $filesize;
      $m_fname = mysql_real_escape_string($targetFile);
      //$sql = "insert into richspri_social._uploads_log (log_filename,log_size,log_ip) values ('$m_fname','$m_size','$m_ip')";
      //$res = @mysql_query($sql);
      $sql1 = "insert into userimg (id,ownerid,file_name,filetype,description,albumid,display,imgtype,approved) values ('','$m_user','$m_fname','$file_ext','','','no','$file_type','no')";
      $res1 = mysql_query($sql1);
      if (!$res) {
        $errors[] = "Could not run query.";
        break;
      }
      mysql_free_result($res);
      mysql_free_result($res1);
      mysql_close($link);
      
move_uploaded_file($tempFile,$targetFile);

}

echo '1';

?>

IT all worked fine on another upload script, but that was single files only, i need this to work for multiple files.

 

Can someone help me debug this please.

 

Thanks

Rich

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-815887
Share on other sites

      if (!is_resource($res1)) { // should be $res1 added the is_resource check
        $errors[] = "Could not run query.";
        //break; // not sure why break is in here, as the if statement will exit either way. Maybe you wanted die() or exit ???
      }
      // Not sure where $res comes from //mysql_free_result($res);
      mysql_free_result($res1);
      // not needed // mysql_close($link);

 

Not sure where $res is coming from. Also used the is_resource test. The free result is not really needed, but ok.

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-816048
Share on other sites

Are you just testing this using AJAX at the moment? If you are I would really create a form that mimics the ajax but actually does a page reload. This way you can see any errors coming out and once you get that script working with a regular form allow the AJAX to use it. Otherwise it is a pain in the butt to debug.

 

I am not sure what is causing it to fail, but I would add this in and test it:

 

      $res1 = mysql_query($sql1) or die("SQL WAS: {$sql}<Br />Error was: " . mysql_error());

 

And see if the insert has an error or issue with it.

Link to comment
https://forums.phpfreaks.com/topic/154810-i-need-help-please/#findComment-816062
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.