I'm trying to upload an image to the server using a PHP script. It works fine, till I want to change the filename using a variable in the name.
I want to rename the file to the logged in users username_filename.extension, but it just skips the username variable so the name becomes: _filename.extension.
<?php
session_start();
include "./global.php";
$res = mysql_query("SELECT * FROM users WHERE id='".$_SESSION['uid']."'");
$row = mysql_fetch_assoc($res);
$username = $row['username'];
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$ext = explode('.',$_FILES['Filedata']['name']);
$extension = $ext[1];
$newname = '/var/www/picturebox/albums/' . $username . '_' . $ext[0] . '.' . $ext[1];
move_uploaded_file($tempFile,$newname);
}
?>
And the filename becomes _filename.extension
Anyone knows what to do?
Just found out that it works fine in IE, but now in Chrome. Any suggestions on a solution?
Related
I am trying to upload image files to a server and creating a random name when doing so. The issue I am having is that sometimes (far too often) it creates the same file name but for files with a different extension.
My code for the upload is below, what I want to do is add a check to make sure the name is not in use but with a different extension.
Example -
da4fb5c6e93e74d3df8527599fa62642.jpg & da4fb5c6e93e74d3df8527599fa62642.JPG
if ($_FILES['file']['name']) {if (!$_FILES['file']['error']){
$name = md5(mt_rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = $_SERVER['DOCUMENT_ROOT'] . '/images/infopages/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/infopages/' . $filename;
}else{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Any help is appreciated.
You can use PHP uniqid & rand functions combinedly. In this way you will never get duplicate values.
$filename = uniqid (rand(1000000,9999999), true) '.' . $ext[1];
I'm trying to create a file upload only my current script doesn't seem to work as I believe it should.
I've managed to get the data saved in the MySQL table okay but I can't seem to get the file into the 'uploads' directory?
if(isset($_POST['new']) && $_POST['new']==1){
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
$trn_date = date("Y-m-d H:i:s");
$brand =$_REQUEST['brand'];
$user =$_SESSION["username"];
$model = $_REQUEST['model'];
$serial =$_REQUEST['serial'];
$purchasedate = $_REQUEST['purchasedate'];
$img1 =$_REQUEST['image1'];
$ins_query="insert into table
(`user`,`trn_date`,`brand`,`model`,`serial`,`purchasedate`,`image1`)values
('$user','$trn_date','$brand','$model','$serial','$purchasedate','$img1')";
mysqli_query($con,$ins_query)
or die(mysql_error());
$status = "added successfully.
</br></br><a href='home.php'>home</a>";
}
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
What if trying directly what the doc said ;)
$uploads_dir = '/uploads';//try over 'uploads' too or create a 'uploads' folder in you app_root
foreach ($_FILES["image1"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image1"]["tmp_name"][$key];
$name = $_FILES["image1"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Possible Link
I have found an issue in your code.
$folder = "uploads/";
$upload_image = $folder . basename($_FILES["image1"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image);
In this case the file does not have the extension
$folder = "uploads/";
$ext = explode('.', basename( $_FILES['image1']['name']));
$upload_image = $folder . basename($_FILES["image1"]["name"].$ext);
move_uploaded_file($_FILES["image1"]["tmp_name"], $upload_image);
The uploads folder is in the same directory that is the php script?
You also can verify if the file was correctly moved doing the following test
if (file_exists($upload_image)){
echo "true";
}
Provide a file upload validation before uploading into server it will prevent server from malicious files
How to give file validation in php : Link
I am new to PHP. here is my code to save results of form to database and uploaded file name.I am using uploadify to upload files.
Here i have 2 problems.
file saves on its location in mozila but do not works for chrome.
coded goes here.
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$picAd= $_FILES ['Filedata']['name'];
// to change same file name
$picAd=rand(0,1000)."_".rand(0,1000)."_".$picAd;
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
// this line works ok for all browsers
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
this line not works for chrome
// $targetFile = str_replace('//','/',$targetPath) . $picAd; <<Error for chrome
if( move_uploaded_file($tempFile,$targetFile)){ // 4
echo true;
}else{
echo false;
}
saving results to database .
static $picAd;
if(isset($_POST['submit'])){
// varibles
$uname=$_REQUEST['userName'];
$pw=$_REQUEST["pw"];
$email= $_REQUEST["email"];
$twit= $_REQUEST["twit"];
$user="user";
if($picAd != ""){
$q="insert into users values(Null,'$user','$uname','$pw','$email','$twit','$picAd')";
mysql_query($q);
mysql_close($dbc); }
}
Here i am not getting the value of $picAd in database its value goes NUll.
<?php
require '../config.php';
// Edit upload location here
$result = 0;
$name = mysql_real_escape_string($_FILES['myfile']['name']);
$path = csv;
$ext = 'csv';
$md5 = md5($name);
$target_path = $path . '\\' . $md5 . '.' . $ext;
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
It won't upload any files such as with the file names that contain brackets, etc.
Don't do:
$name = mysql_real_escape_string($_FILES['myfile']['name']);
Do:
$name = $_FILES['myfile']['name'];
you are getting the MD5 of $name so no reason to clean it as it will produce a 32-char hex string which will not contain any special characters regardless. If a filename contains special chars and you escape using the above the MD5 will completely change.
The error is likely here:
$path = csv;
Here PHP is looking for a constant with name csv unless you have defined that, it is going to return null, so your $target_path is not being built correctly.
Just one more thing to try is use the pre defined DIRECTORY_SEPERATOR constant while building your $target path so...
$target_path = $path . DIRECTORY_SEPERATOR . $md5 . '.' . $ext;
I am using Uploadify for my script.
The main page:
<?php
session_start();
var_dump($_SESSION);
$uploaded_files = $_SESSION['uploaded_files'];
?>
//Uploadify, HTML forms and more (not related, No PHP in this section)
uploadify.php:
<?php
session_start();
require_once('includes/functions.php');
// Define a destination
$targetFolder = 'uploads/temp'; // Relative to the root
if (!empty($_FILES)) {
$fileParts = pathinfo($_FILES['Filedata']['name']);
$file_hash = GenRndStr(20) . '.' . $fileParts['extension'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $file_hash;
// Validate the file type
$fileTypes = array(); // File extensions
move_uploaded_file($tempFile, $targetFile);
$_SESSION['uploaded_files'][] = $file_hash;
echo '1';
}
?>
I'm sure it gets to the $_SESSION['uploaded_files'][] = $file_hash; part, since the actual file is uploaded to the directory. My problem is that the var_dump of $_SESSION['uploaded_files'] returns null.
The files are in the same directory level.
Thanks in advance.
I found the solution. The problem is that Uploadify's flash version is treated as a different client for the server, therefore the server creates a new session id for it.
I followed this topic: http://www.uploadify.com/forum/#/discussion/43
Hope it'll help others.