i'm just trying to get username from database table and upload the file into the folder named with username but it gives me an error. this is the error : Parse error: syntax error, unexpected T_STRING in /home/u381071273/public_html/upload/upload.php on line 18but i can't find it. i want to get username from database table and display it where i put &username
code:
require("models/db-settings.php");
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT user_name FROM upl_users");
// This will move the internal pointer and skip the first row, we don't want that.
//$row = mysql_fetch_assoc($result);
//echo $row['user_name'];
while ( $row = $result->fetch_assoc() ) {
echo $row['user_name'];}
$dir = "uploads/".$row['user_name']."/";
if (file_exists($UploadedDirectory)) {
mkdir('uploads/".$row['user_name']."/', 0777, true);
}
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
############ Edit settings ##############
$UploadDirectory = 'uplaods/".$row['user_name']."/'; //specify upload directory ends with / (slash)
##########################################
/*
Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini".
Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit
and set them adequately, also check "post_max_size".
*/
//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
//Is file size is less than allowed size.
if ($_FILES["FileInput"]["size"] > 5242880) {
die("File size is too big!");
}
//allowed file type Server side check
switch(strtolower($_FILES['FileInput']['type']))
{
//allowed file types
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
case 'text/plain':
case 'text/html': //html file
case 'application/x-zip-compressed':
case 'application/pdf':
case 'application/msword':
case 'application/vnd.ms-excel':
case 'video/mp4':
case 'audio/mp3';
break;
default:
die('Unsupported File!'); //output error
}
$File_Name = strtolower($_FILES['FileInput']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention
$Random_Number = uniqid(); //Random number to be added to name.
$NewFileName = $Random_Number.$File_Ext; //new file name
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
die('Success! File Uploaded.');
}else{
die('error uploading File!');
}
}
else
{
die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
}
mkdir('uploads/".$row['user_name']."/', 0777, true);
Should be:
mkdir('uploads/'.$row['user_name'].'/', 0777, true);
(You used different string anchors when doing the concatenation - started string with ' but tried to close it with ")
use this line:( you can use single quotes or double quotes dont mix)
mkdir("uploads/".$row['user_name']."/", 0777, true);
Related
I have been going round in circles with this image upload where when I submit with file selected it uploads and posts directory as expected to database,
but of course if I submit without image selected then I get an error.
So I then would would do a check so see if file input is empty however it then stops the upload even when a file is selected and if I remove it I get this error
Warning: getimagesize(): Filename cannot be empty in ....
On searching this issue and see different peoples solutions, they suggest to increase the Upload max file etc... on the wamp php.ini which I did so, and restarted and still the same issue. However there is no issue with the file size as 5.83kb and php.ini is 25mb nor is there an issue with the file type because it does upload if I remove my error check.
Either way I have been scratching my head as I can not get to confirm when empty and echo out the error that I have set and then when file is selected to post. It just gives me the above error when checking.
Below is a working version which posts as expected but displays the error if empty. I don't want it to display this error, I want to display my own error.
Any suggestions? It's driving me up the wall :(
<?php
//UPLOAD IMAGE
if(isset($_POST["UploadImage"])) {
if(is_array($_FILES)) {
$file = $_FILES['file']['tmp_name'];
$sourceProperties = getimagesize($file);
$fileNewName = time();
$folderPath = "../userImages/";
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$imageType = $sourceProperties[2];
$resized = "_resized";
$line = "_";
$original = "_original";
switch ($imageType) {
case IMAGETYPE_PNG:
$imageResourceId = imagecreatefrompng($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagepng($targetLayer,$folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
break;
case IMAGETYPE_GIF:
$imageResourceId = imagecreatefromgif($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagegif($targetLayer,$folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
break;
case IMAGETYPE_JPEG:
$imageResourceId = imagecreatefromjpeg($file);
$targetLayer = imageResize($imageResourceId,$sourceProperties[0],$sourceProperties[1]);
imagejpeg($targetLayer,$folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
break;
default:
$msg = "<div class=\"alert alert-danger\">Wrong File Format - Only JPG, PNG or GIF - Max 2 MB</div>";
exit;
break;
}
$file = #imagecreatefromjpeg($folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext);
if (!$file)
{
$file= imagecreatefromstring(file_get_contents($folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext));
}
echo "";
//If I want the Orignal image upload also then remove below comment
//move_uploaded_file($file, $folderPath.$RegID.$line.$fileNewName.$original. ".".$ext);
//POST TO DATABASE
$RegID;
$RegPhoto = $folderPath.$RegID.$line.$fileNewName.$resized. ".".$ext;
$sql = "UPDATE registered SET RegID = ?, RegPhoto = ? WHERE RegID = '$RegID'";
$stmt = $connect->prepare($sql);
$stmt->bind_param('is', $RegID, $RegPhoto );
$stmt->execute();
$msg = "<div class=\"alert alert-success\">Updated Profile Successfully</div>";
}
}
function imageResize($imageResourceId,$width,$height) {
$targetWidth =220;
$targetHeight =200;
$targetLayer=imagecreatetruecolor($targetWidth,$targetHeight);
imagecopyresampled($targetLayer,$imageResourceId,0,0,0,0,$targetWidth,$targetHeight, $width,$height);
return $targetLayer;
}
?>
file_exists is not working!! But when the url ($img in code) is given in the browser, image is displayed. I know file_exists() takes only harddrive path but i could understand, help please ..
include_once("../inc/inc_constants.php");
include_once("database/db.php");
include_once("includes/global.php");
ini_set('max_execution_time',300);
$sql="select plan_image_name from mp_new_project_images
where project_code in
(select project_code from mp_new_project
where project_status='Active' ) ";
$sql_result=mysql_query($sql) or die(mysql_error());
while($sqlrow=mysql_fetch_array($sql_result))
{
//HOME is "http://ip address/"
$img = HOME."images/properties/thumbs_400/".$sqlrow['plan_image_name']." ";
if(file_exists($img))
{
$dest =HOME."images/properties/thumbs_400/compress_50/".$sqlrow['plan_image_name']." ";
$dest1=HOME."images/properties/thumbs_400/compress_20/".$sqlrow['plan_image_name']." ";
$dest2=HOME."images/properties/thumbs_400/compress_10/".$sqlrow['plan_image_name']." ";
$size = getimagesize($img);
switch($size['mime']) {
case 'image/jpeg':
$im=imagecreatefromjpeg($img);
imagejpeg($im,$dest,50);
imagejpeg($im,$dest1,20);
imagejpeg($im,$dest2,10);
break;
case 'image/png':
$im = imagecreatefrompng($img);
imagepng($im,$dest,50);
imagepng($im,$dest1,20);
imagepng($im,$dest2,10);
break;
case 'image/gif':
$im = imagecreatefromgif($img);
imagegif($im,$dest,50);
imagegif($im,$dest1,20);
imagegif($im,$dest2,10);
break;
default:
return false;
break;
}
}
}
file name should be Path to the file or directory not IP Address
'HOME' constant should be /var/www/html not ('http://url') for example
$img = HOME."images/properties/thumbs_400/".$sqlrow['plan_image_name']." ";
if(file_exists($img)) {
}
This code you have:
//HOME is "http://ip address/"
$img = HOME."images/properties/thumbs_400/".$sqlrow['plan_image_name']." ";
if(file_exists($img))
{
Will not work. The function file_exists() is expecting a local directory path. You can use fopen() for a remote path.
$handle = fopen("http://www.example.com/", "r");
if (!$handle)
{
//no file
}
else
{
// file exists
}
http://php.net/manual/en/function.fopen.php
I believe it works with IP addresses, but be careful as IP addresses are quite often shared.
in file_exisits function instead of HOME use physical path. physical path is something like this "/var/www/public_html/"
use phpinfo() function to know the physical path
OR
use
dirname(__FILE__) . DIRECTORY_SEPARATOR
PROPERLY to get the physical path dynamically.
I have an upload script that I found online and modified a little. I need a way to make sure that every file that is uploaded has a unique name; something short at first and as the number of files increase, the length of the name can increase too. My script I've used is...
<?php
// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER','../uploads/');
// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 10240);
// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','my info');
// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array('jpg', 'jpeg', 'png', 'gif');
// 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', '');
// Need uploads log? Logs would be saved in the MySql database.
define('DO_LOG', true);
// MySql data (in case you want to save uploads log)
define('DB_HOST','my info'); // host, usually localhost
define('DB_DATABASE','my info'); // database name
define('DB_USERNAME','my info'); // username
define('DB_PASSWORD','my info'); // password
/*CREATE TABLE uploads_log (
log_id int(11) unsigned NOT NULL auto_increment,
log_filename varchar(128) default '',
log_size int(10) default 0,
log_ip varchar(24) default '',
log_date timestamp,
PRIMARY KEY (log_id),
KEY (log_filename)
);*/
####################################################################
### END OF SETTINGS. DO NOT CHANGE BELOW
####################################################################
// Allow script to work long enough to upload big files (in seconds, 2 days by default)
#set_time_limit(172800);
// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");
function showUploadForm($message='') {
$max_file_size_tag = '';
if (MAX_FILE_SIZE > 0) {
// convert to bytes
$max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
}
// Load form template
include ('index.php');
}
// errors list
$errors = array();
$message = '';
// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
if (strpos($ini_maxsize, 'M') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024;
elseif (strpos($ini_maxsize, 'K') !== false)
$ini_maxsize = intval($ini_maxsize)*1024;
elseif (strpos($ini_maxsize, 'G') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}
// show upload form
if (!isset($_POST['submit'])) {
showUploadForm(join('',$errors));
}
// process file upload
else {
while(true) {
// make sure destination folder exists
if (!#file_exists(DESTINATION_FOLDER)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
break;
}
// check for upload errors
$error_code = $_FILES['filename']['error'];
if ($error_code != UPLOAD_ERR_OK) {
switch($error_code) {
case UPLOAD_ERR_INI_SIZE:
// uploaded file exceeds the upload_max_filesize directive in php.ini
$errors[] = "File is too big (1).";
break;
case UPLOAD_ERR_FORM_SIZE:
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
$errors[] = "File is too big (2).";
break;
case UPLOAD_ERR_PARTIAL:
// uploaded file was only partially uploaded.
$errors[] = "Could not upload file (1).";
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
$errors[] = "Could not upload file (2).";
break;
case UPLOAD_ERR_NO_TMP_DIR:
// Missing a temporary folder
$errors[] = "Could not upload file (3).";
break;
case UPLOAD_ERR_CANT_WRITE:
// Failed to write file to disk
$errors[] = "Could not upload file (4).";
break;
case 8:
// File upload stopped by extension
$errors[] = "Could not upload file (5).";
break;
} // switch
// leave the while loop
break;
}
// get file name (not including path)
$filename = #basename($_FILES['filename']['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
// check file type if needed
if (count($exts)) { /// some day maybe check also $_FILES['user_file']['type']
if (!#in_array($file_ext, $exts)) {
$errors[] = "Files of this type are not allowed for upload.";
break;
}
}
// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
$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;
}
if (DO_LOG) {
// Establish DB connection
$link = #mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
if (!$link) {
$errors[] = "Could not connect to mysql.";
break;
}
$res = #mysql_select_db(DB_DATABASE, $link);
if (!$res) {
$errors[] = "Could not select database.";
break;
}
/*$m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$m_size = $filesize;
$m_fname = mysql_real_escape_string($dest_filename);
$sql = "insert into _uploads_log (log_filename,log_size,log_ip) values ('$m_fname','$m_size','$m_ip')";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}*/
#mysql_free_result($res);
#mysql_close($link);
} // if (DO_LOG)
// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();
break;
} // while(true)
// Errors. Show upload form.
$message = join('',$errors);
showUploadForm($message);
}
?>
Plus, what other security procedures should I use? If you know any, could you please implement them into my code and re-post them? Thank you!!!
The code you've posted already includes the lines:
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
This is a perfectly good way to generate a random unique file name in PHP. The string returned by md5() will be 32 characters long; you could safely truncate it a bit, but if you go much below 16 characters or so, you start risking collisions.
Of course, if you want to make sure there are no collisions, you could always just check whether the file exist and retry if it does. This would even allow you to use shorter filenames:
if (RENAME_FILE) {
do {
$dest_filename = substr(md5(uniqid(rand(), true)), 0, 8) . ".$file_ext";
} while (file_exists(DESTINATION_FOLDER . $dest_filename . APPEND_STRING));
}
This should give you a unique 8-character (+ extension) filename. Of course, this will start slowing down after about 231 ≈ 2 billion uploaded files, and will fail completely at 232 ≈ 4 billion.
I'm (a newbie in php) still working on a time off project and another problem came up, for which I can't find a solution. Therefore I hope u guys can help me! Worked great the last time I posted something on here! I really appreciate your help...thx ahead!
My problem:
I want users to be able to upload pictures when they are logged in. They got several little buttons on their profile with images on them...and they should be able to change them...
I want to have it like this -> When a user uploads an image, the script shall create a new folder on the server. This shall happen in the "user_images" folder (that exists already). So a user with e.g. "id=55" creates a folder "55" in "user_images" when he uploads images. I tried and tried and tried and tried...with different syntax in line -> "$upload_dir =" but without any success :-/ I just don't get it to work...
Here is the part of the script:
<?php
include 'dbconfig.php';
page_protect();
$rs_settings = mysql_query("select * from user where id='$_SESSION[user_id]'");
while ($row_settings = mysql_fetch_array($rs_settings));
error_reporting (E_ALL ^ E_NOTICE);
session_start();
//only assign a new timestamp if the session variable is empty
if (!isset($_SESSION['user_id']) || strlen($_SESSION['user_id'])==0){
$_SESSION['user_id'] = mysql_query("select * from user where id='$_SESSION[user_id]'");
//assign the timestamp to the session variable
$_SESSION['user_file_ext']= "";
}
$upload_dir = "user_images/";
$upload_path = $upload_dir;
$large_image_prefix = "Large_";
$thumb_image_prefix = "button_";
$large_image_name = $large_image_prefix.$_SESSION['user_id'];
image (append the timestamp to the filename)
$thumb_image_name = $thumb_image_prefix.$_SESSION['user_id'];
image (append the timestamp to the filename)
$max_file = "1"; // Maximum file size in MB
$max_width = ""; // Max width allowed for the large image
$thumb_width = "87"; // Width of thumbnail image
$thumb_height = "35"; // Height of thumbnail image
// Only one of these image types should be allowed for upload
$allowed_image_types =
array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",
'image/x-png'=>"png",'image/gif'=>"gif");
$allowed_image_ext = array_unique($allowed_image_types); // do not change this
$image_ext = ""; // initialise variable, do not change this.
foreach ($allowed_image_ext as $mime_type => $ext) {
$image_ext.= strtoupper($ext)." ";
}
function resizeImage($image,$width,$height,$scale) {
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,
$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}
chmod($image, 0777);
return $image;
}
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width,
$start_height, $scale){
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,
$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
function getHeight($image) {
$size = getimagesize($image);
$height = $size[1];
return $height;
}
function getWidth($image) {
$size = getimagesize($image);
$width = $size[0];
return $width;
}
$large_image_location = $upload_path.$large_image_name.$_SESSION['user_file_ext'];
$thumb_image_location = $upload_path.$thumb_image_name.$_SESSION['user_file_ext'];
if(!is_dir($upload_dir)){
mkdir($upload_dir, 0777);
chmod($upload_dir, 0777);
}
if (file_exists($large_image_location)){
if(file_exists($thumb_image_location)){
$thumb_photo_exists = "<img
src=\"".$upload_path.$thumb_image_name.$_SESSION['user_file_ext']."\" alt=\"Thumbnail
Image\"/>";
}else{
$thumb_photo_exists = "";
}
$large_photo_exists = "<img
src=\"".$upload_path.$large_image_name.$_SESSION['user_file_ext']."\" alt=\"Large
Image\"/>";
} else {
$large_photo_exists = "";
$thumb_photo_exists = "";
}
if (isset($_POST["upload"])) {
//Get the file information
$userfile_name = $_FILES['image']['name'];
$userfile_tmp = $_FILES['image']['tmp_name'];
$userfile_size = $_FILES['image']['size'];
$userfile_type = $_FILES['image']['type'];
$filename = basename($_FILES['image']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
//Only process if the file is a JPG, PNG or GIF and below the allowed limit
if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
foreach ($allowed_image_types as $mime_type => $ext) {
//loop through the specified image types and if they match the
extension then break out
//everything is ok so go and check file size
if($file_ext==$ext && $userfile_type==$mime_type){
$error = "";
break;
}else{
$error = "Only <strong>".$image_ext."</strong> images accepted for upload<br />";
}
}
//check if the file size is above the allowed limit
if ($userfile_size > ($max_file*1048576)) {
$error.= "Images must be under ".$max_file."MB in size";
}
}else{
$error= "Select an image for upload";
}
//Everything is ok, so we can upload the image.
if (strlen($error)==0){
if (isset($_FILES['image']['name'])){
//this file could now has an unknown file extension (we hope it's one of the ones set above!)
$large_image_location = $large_image_location.".".$file_ext;
$thumb_image_location = $thumb_image_location.".".$file_ext;
//put the file ext in the session so we know what file to look for once its uploaded
$_SESSION['user_file_ext']=".".$file_ext;
move_uploaded_file($userfile_tmp, $large_image_location);
chmod($large_image_location, 0777);
$width = getWidth($large_image_location);
$height = getHeight($large_image_location);
//Scale the image if it is greater than the width set above
if ($width > $max_width){
$scale = $max_width/$width;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}else{
$scale = 1;
$uploaded = resizeImage($large_image_location,$width,$height,$scale);
}
//Delete the thumbnail file so the user can create a new one
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
}
}
//Refresh the page to show the new uploaded image
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
?>
It would be really cool if someone could help me to fix these problems...you may know how hard it is, when you're just a rookie! If there's more weird syntax in there...let me know, I'm just a beginner (like we all have been at the beginning) and trying to get better :)
Thank you guys!
Keeping in mind that allowing any user to upload content to your server creates a security hole that requires special attention, this is a bit of code I've used in the past for an internal-use application:
$folderPath = "/uploads/" . $folderName;
$exist = is_dir($folderPath);
if(!$exist) {
mkdir("$folderPath");
chmod("$folderPath", 0755);
}
else { echo "Folder already exists"; }
You can also chmod right from mkdir but was having issues with doing that on this particular server config.
http://php.net/manual/en/function.mkdir.php
UPDATED with more complete example:
// Define path where file will be uploaded to
// User ID is set as directory name
$folderPath = "/uploads/$userID";
// Check to see if directory already exists
$exist = is_dir($folderPath);
// If directory doesn't exist, create directory
if(!$exist) {
mkdir("$folderPath");
chmod("$folderPath", 0755);
}
else { echo "Folder already exists"; }
// PROCESS FILE UPLOAD
// Set initial/temporary upload location
// temp_uploads must have proper read/write permissions (755 or 777)
$target_path = "/uploads/temp_uploads/";
// Append the name of the uploaded file to the temp directory
$target_path .= basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$filename = basename( $_FILES['uploadedfile']['name']);
// Location where temporary file is being stored
$temp_location = '/uploads/temp_uploads/' . basename( $_FILES['uploadedfile']['name']);
// Final destination where file will be located
$destination = "/uploads/$folderPath/$filename";
rename($temp_location, $destination);
}
You are assigning a mysql query resource to the $_SESSION["user_id"]
$_SESSION['user_id'] = mysql_query("select * from user where id='$_SESSION[user_id]'");
I think you want to get the user id out of that query
Also if your code produces any errors it would be great if you included them in your question
ps. don't use mysql_* functions, they are deprecated and create unwanted security holes if not used properly, learn dibi, pdo, or any other newer database layer
$file_name=basename($_FILES['uploadedfile']['name']);
mkdir("upload/".$username,0777);
$target_path = "upload/$username/". $file_name;
Please could someone show me where i need to change the code so that the image uploaded is renamed to "freddy" for e.g.
But still carries the correct existing extension i.e jpg, png, gif.
Thanks In Advance
<?php
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 1024 * 50);
if (array_key_exists('upload', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', '/home/richard/public_html/testing/editable-images/');
// replace any spaces in original filename with underscores
$file = str_replace(' ', '_', $_FILES['image']['name']);
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg',
'image/png');
// upload if file is OK
if (in_array($_FILES['image']['type'], $permitted)
&& $_FILES['image']['size'] > 0
&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
switch($_FILES['image']['error']) {
case 0:
// check if a file of the same name has been uploaded
// Uncomment to stop overwritten files >>>> if (!file_exists(UPLOAD_DIR . $file)) {
// move the file to the upload folder and rename it
$success =
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR .
$file);
// Uncomment to stop overwritten files >>>> } else {
// Uncomment to stop overwritten files >>>> $result = 'A file of the same name already exists.';
// Uncomment to stop overwritten files >>>>> }
if ($success) {
$result = "$file uploaded successfully.";
} else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
case 6:
case 7:
case 8:
$result = "Error uploading $file. Please try again.";
break;
case 4:
$result = "You didn't select a file to be uploaded.";
}
} else {
$result = "$file is either too big or not an image.";
}
}
?>
// get file extension
$ext = end(explode($_FILES['image']['name']));
// name your file and preserve file extension
$file = "freddy.".$ext;
// create an array of permitted MIME types
....
Check description of method move_uploaded_file here