I am trying to move an existing image file from a temp folder to a proper location with a proper filename, for some reason it always fails.
function move_temp_image($article_id)
{
global $db, $config;
if (($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.jpg", 'r+')) && ($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.png", 'r+')) && ($image_load = !#fopen($_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.gif", 'r+')))
{
$this->error_message = "Could not find temp image to load?";
return false;
}
else
{
$image_info = getimagesize($image_load);
$image_type = $image_info[2];
$file_ext = '';
if( $image_type == IMAGETYPE_JPEG )
{
$file_ext = 'jpg';
}
else if( $image_type == IMAGETYPE_GIF )
{
$file_ext = 'gif';
}
else if( $image_type == IMAGETYPE_PNG )
{
$file_ext = 'png';
}
// give the image a random file name
$imagename = rand() . 'id' . $article_id . 'gol.' . $file_ext;
// the actual image
$source = $image_load;
// where to upload to
$target = $_SERVER['DOCUMENT_ROOT'] . "/uploads/articles/topimages/" . $imagename;
if (rename($source, $target))
{
// remove old temp image
if ($image['article_top_image'] == 1)
{
unlink($_SERVER['DOCUMENT_ROOT'] . '/uploads/temp/' . $image_load);
}
unset($_SESSION['temp_tagline']);
$db->sqlquery("UPDATE `articles` SET `article_top_image` = 1, `article_top_image_filename` = ? WHERE `article_id` = ?", array($imagename, $article_id));
return true;
}
else
{
$this->error_message = 'Could not move temp file to tagline uploads folder!';
return false;
}
}
}
I am not sure what I am doing wrong, I read rename is the way to do this, but I am obviously overlooking something.
You don't have the filename in $source - In your code, $source contains a file resource...
rename doesn't work only with file names, so you have to change your code.
i.e. replace your condition with the following code
$types = array('jpg', 'png', 'gif');
$file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/temp/{$_SESSION['username']}_article_tagline.";
$image_load = false;
foreach ($types as $type) {
if (file_exists($file . $type)) {
$image_load = $file . $type;
break;
}
}
if (!file_exists($image_load))
Related
This is my controller code:
if ($files != '0') {
//echo "1";
if (isset($is_anonymous)) {
$is_anonymous = $is_anonymous;
} else {
$is_anonymous = "0";
}
$file_ary = $this->Jayesh($_FILES['files']);
$post_Id = $this->post_m->add_new_post($is_anonymous, $college_id, $writepost, $post, $article, $askq, $user_id, curr_date(), $v_id, $art_title, $art_image, $art_domain, $art_url, $article);
foreach ($file_ary as $file) {
$srt = explode('.', $file['name']);
$ext = $this->getExtension($file['name']);
$fiel_name = uniqid() . date("YmdHis") . "." . $ext;
$mime = $file['type'];
if (strstr($mime, "video/") || strstr($mime, "application/")) {
$filetype = "video";
$sourcePath = $file['tmp_name'];
$targetPath = "images/medical_college_images/video/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
} else if (strstr($mime, "image/")) {
$filetype = "image";
$sourcePath = $file['tmp_name'];
$targetPath = "images/medical_college_images/image/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
} else if (strstr($mime, "audio/")) {
$filetype = "audio";
}
if (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
if (!empty($user_id)) {
$user = $this->post_m->check_user_exist_timeline($user_id);
if (!empty($user)) {
if ($filetype == 'video') {
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/video/" . $fiel_name);
$image_width = '0';
$image_height = '0';
$video_width = '300';
$video_height = '160';
}
if ($filetype == 'image') {
//echo "https://d2c8oti4is0ms3.cloudfront.net/images/healthwall_media/image/".$fiel_name;
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/image/" . $fiel_name);
$image_width = $image_info[0];
$image_height = $image_info[1];
$video_width = '300';
$video_height = '160';
}
//exit();
/* $last_user_id = $this->post_m->insert_image_post_into_media($fiel_name, $filetype,curr_date());
if (!empty($last_user_id))
{ */
$result = $this->post_m->insert_image_post_into_post_media($post_Id, curr_date(), $image_width, $image_height, $video_height, $video_width, $fiel_name, $filetype);
//}
}
}
}
}
Model code:
public function insert_image_post_into_post_media($post_Id, $cdate, $image_width, $image_height, $video_height, $video_width, $fiel_name, $filetype) {
$sql = "INSERT INTO college_post_media( `post_id`,`type`, `source`, `img_height`, `img_width`, `video_height`, `video_width`, `created_at`, `updated_at`, `deleted_at`)
VALUES ('$post_Id','$filetype','$fiel_name','$image_height', '$image_width','$video_height', '$video_width', '$cdate','$cdate','$cdate')";
return $result = $this->db->query($sql);
}
I'm facing an issue when inserting img_height and img_width in to the table. It is going in empty.
Try getting the image size while it is still on your domain:
Excerpt:
} else if (strstr($mime, "image/")) {
$filetype = "image";
$sourcePath = $file['tmp_name'];
list($image_width, $image_height) = getimagesize($file['tmp_name']);
$targetPath = "images/medical_college_images/image/" . $fiel_name;
//move_uploaded_file($sourcePath, $targetPath);
$s3->putObjectFile($sourcePath, $bucket, $targetPath, S3::ACL_PUBLIC_READ);
}
Assuming that $file['tmp_name'] is a fully qualified path.
Then you can remove:
$image_info = getimagesize("https://medicalwale.s3.amazonaws.com/images/medical_college_images/image/" . $fiel_name);
$image_width = $image_info[0];
$image_height = $image_info[1];
So i have more than one image to upload, each one being a new line in my mysql table:
I use this code for file input with name="profile"
if (isset($_FILES['profile']) === true) {
if (empty($_FILES['profile']['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png')
$file_name = $_FILES['profile']['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $_FILES['profile']['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, 1, $file_temp, $file_extn);
header('Location: galery.php');
exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
(change_image) function makes this MySql query
$sql = "UPDATE `art_$id` SET `path` = \"" . $file_path . "\" WHERE `row` = " . (int)$row;
But i want to repeat this code for profil1, profil2... and change accordingly the row (example : profil4 would change row 4 ), without having to repeat this code for each file='name'.
How would i go about that?
Irrespective of your form have "how many fields as of file and what they are named??" . Following code will upload them one by one ..Check it
$rowid=1;
foreach($_FILES as $key=>$image_uploaded)
{
if (isset($image_uploaded[$key]) === true) {
if (empty($image_uploaded[$key]['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png')
$file_name = $image_uploaded[$key]['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $image_uploaded[$key]['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, $rowid++, $file_temp, $file_extn);
//change as you need
header('Location: galery.php');
exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
}
Thanks for your answer, as i have a specific submit button for each form and don't wont to validate all forms at once i used this code :
for ($row = 1; $row <= 9; $row++) {
if (isset($_FILES["profile" . $row]) === true) {
if (empty($_FILES["profile" . $row]['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png');
$file_name = $_FILES["profile" . $row]['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $_FILES["profile" . $row]['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, $row, $file_temp, $file_extn);
//header('Location: galery.php');
//exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
}
}
}
}
And for file input i use name="profile1",name="profile2",....,name="profile9"(for this case).
Here is the the code which will add 1,2,3 at end of the image file name
Bellow function will check the file exist in dir or not and return new file name now you can use the function before change_image function call and get new file name and pass new name in change_image for save.
function getFileName($fileName, $file_extn){
$fileNameWithoutExt = pathinfo($fileName, PATHINFO_FILENAME);
$i = 1;
while(!file_exists('image/art/' . $fileName)){
$fileName = $fileNameWithoutExt . $i . "." . $file_extn;
$i++;
}
return $fileName;
}
This is my code:
function secure_img_upload($file, $path, $options = array()){
// HANDLE OPTIONS
$validExtensions = isset($options['validExtensions']) ? $options['validExtensions'] : array('jpg', 'jpeg', 'png');
$surfix = isset($options['surfix']) ? $options['surfix'] : '';
// HANDLES FILES
$tempFile = $file['tmp_name'];
$fileName = $file['name'];
$extension = explode(".", $fileName);
$extension = strtolower(end($extension));
$imageName = sha1($fileName.uniqid());
$destination = rtrim($path, '/').'/'.$imageName.$surfix.'.'.$extension;
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
// Run getImageSize function to check that we're really getting an image
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile, $destination)) {
return $destination;
}else{
return array('s'=>'ko', 'm'=>T("Invalid path."));
}
}else{
return array('s'=>'ko', 'm'=>T("Invalid extension."));
}
}
My problem is that in this way, Images are uploaded in a random way.
But I need that images are uploaded in the order I select them. Any tips? Thank you
My script is not working properly. If i upload a php file instead of jpg file then it should not upload php files to upload folder, i want to allow only image files. Please correct my script.
Here is my code Thanks !
<?php
include "inc.php";
ob_start();
if(!isset($_SESSION['ocer']) && trim($_SESSION['ocer'])!=''){
header("Location: admin.php?l=1");
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$title=addslashes(mysql_real_escape_string($_REQUEST['title']));
$des=addslashes(mysql_real_escape_string($_REQUEST['des']));
$location=addslashes(mysql_real_escape_string($_REQUEST['location']));
$state=addslashes(mysql_real_escape_string($_REQUEST['state']));
$status=mysql_real_escape_string($_REQUEST['status']);
$userid=mysql_real_escape_string($_REQUEST['userid']);
$date1=mysql_real_escape_string($_REQUEST['date1']);
chmod('upload', 0777);
if($_FILES['file_name1']['name']!="")
{
$file_name1=$_FILES['file_name1']['name'];
$ext=getExtension($file_name1);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name1=mktime().'thumb1'.'.'.$ext;
copy($_FILES['file_name1']['tmp_name'],"upload/".$file_name1);
}
}
if($_FILES['file_name2']['name']!="")
{
$file_name2=$_FILES['file_name2']['name'];
$ext=getExtension($file_name2);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name2=mktime().'thumb2'.'.'.$ext;
copy($_FILES['file_name2']['tmp_name'],"upload/".$file_name2);
}
}
if($_FILES['file_name3']['name']!="")
{
$file_name3=$_FILES['file_name3']['name'];
$ext=getExtension($file_name3);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name3=mktime().'thumb3'.'.'.$ext;
copy($_FILES['file_name3']['tmp_name'],"upload/".$file_name3);
}
}
if($_FILES['file_name4']['name']!="")
{
$file_name4=$_FILES['file_name4']['name'];
$ext=getExtension($file_name4);
if(trim($ext)=='jpeg' || trim($ext)=='jpg' || trim($ext)=='gif' || trim($ext)=='png' || trim($ext)=='tiff')
{
$file_name4=mktime().'thumb4'.'.'.$ext;
copy($_FILES['file_name4']['tmp_name'],"upload/".$file_name4);
}
}
if(trim($title)!="" && trim($des)!=""){
$sql_ins="insert into `jobs` set title='$title',des='$des',location='$location',state='$state',date1='$date1',userid='$userid',status='$status',newsimg='$file_name1',newsimg2='$file_name2',newsimg3='$file_name3',newsimg4='$file_name4'";
$rs=mysql_query($sql_ins) or die(mysql_error());
$lid=mysql_insert_id();
$notice="job";
}
header("location: admin.php?done=1");
?>
try the following lines
$ext = pathinfo($_FILES["file_name3"]["name"], PATHINFO_EXTENSION);
if($ext...)// your if else condition
{}
else
{}
Part 1 :
$valid_mime_types = array(
"image/gif",
"image/png",
"image/jpeg",
"image/pjpeg",
);
if (in_array($_FILES["file"]["type"], $valid_mime_types)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 2 :
$valid_file_extensions = array(".jpg", ".jpeg", ".gif", ".png");
$file_extension = strrchr($_FILES["file"]["name"], ".");
// Check that the uploaded file is actually an image
// and move it to the right folder if is.
if (in_array($file_extension, $valid_file_extensions)) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
Part 3 :
if (#getimagesize($_FILES["file"]["tmp_name"]) !== false) {
$destination = "uploads/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $destination);
}
I need help with a Remote Upload Script that has a page named 'uploadHandler.php'. I need to create a Remote Upload Script with jQuery PHP File Upload (jQuery File Upload). I would like to upload through this script a file that comes from a different server by entering only the URL. How can this be done?
Let me explain. I have a form that sends a request to uploadHandler.php when a user uploads a file from his computer. The problem is that the type is 'multipart/form-data' so I cannot upload via URL. I tried to put a URL but the system returns
[{"name":"","size":0,"type":null,"error":"File received has zero size."}]
So, what should I do to make sure that the file is processed by uploadHandler.php and then stored correctly? I had thought to download the file from the server and then upload it to do so treated. But how? I enclose the contents of uploadHandler.php for those who want to read it. Thank you in advance for your help, and I apologize for the grammar and vocabulary wrong: I'm not English.
class uploadHandler
{
private $options;
function __construct($options = null)
{
// get accepted file types
$acceptedFileTypes = getAcceptedFileTypes();
$this->options = array(
'script_url' => $_SERVER['PHP_SELF'],
'upload_dir' => _CONFIG_FILE_STORAGE_PATH,
'upload_url' => dirname($_SERVER['PHP_SELF']) . '/files/',
'param_name' => 'files',
'delete_hash' => '',
// The php.ini settings upload_max_filesize and post_max_size
// take precedence over the following max_file_size setting:
'max_file_size' => $this->get_max_upload_size(),
'min_file_size' => 1,
'accept_file_types' => COUNT($acceptedFileTypes) ? ('/(\.|\/)(' . str_replace(".", "", implode("|", $acceptedFileTypes)) . ')$/i') : '/.+$/i',
'max_number_of_files' => null,
'discard_aborted_uploads' => true,
'image_versions' => array(
'thumbnail' => array(
'upload_dir' => dirname(__FILE__) . '/thumbnails/',
'upload_url' => dirname($_SERVER['PHP_SELF']) . '/thumbnails/',
'max_width' => 80,
'max_height' => 80
)
)
);
if ($options)
{
$this->options = array_replace_recursive($this->options, $options);
}
}
private function get_max_upload_size()
{
// Initialize current user
$Auth = Auth::getAuth();
// max allowed upload size
$maxUploadSize = SITE_CONFIG_FREE_USER_MAX_UPLOAD_FILESIZE;
if ($Auth->loggedIn())
{
// check if user is a premium/paid user
if ($Auth->level != 'free user')
{
$maxUploadSize = SITE_CONFIG_PREMIUM_USER_MAX_UPLOAD_FILESIZE;
}
}
// if php restrictions are lower than permitted, override
$phpMaxSize = getPHPMaxUpload();
if ($phpMaxSize < $maxUploadSize)
{
$maxUploadSize = $phpMaxSize;
}
return $maxUploadSize;
}
private function get_file_object($file_name)
{
$file_path = $this->options['upload_dir'] . $file_name;
if (is_file($file_path) && $file_name[0] !== '.')
{
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->options['upload_url'] . rawurlencode($file->name);
foreach ($this->options['image_versions'] as $version => $options)
{
if (is_file($options['upload_dir'] . $file_name))
{
$file->{$version . '_url'} = $options['upload_url']
. rawurlencode($file->name);
}
}
$file->delete_url = '~d?' . $this->options['delete_hash'];
$file->info_url = '~i?' . $this->options['delete_hash'];
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
private function get_file_objects()
{
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->options['upload_dir'])
)));
}
private function create_scaled_image($file_name, $options)
{
$file_path = $this->options['upload_dir'] . $file_name;
$new_file_path = $options['upload_dir'] . $file_name;
list($img_width, $img_height) = #getimagesize($file_path);
if (!$img_width || !$img_height)
{
return false;
}
$scale = min(
$options['max_width'] / $img_width, $options['max_height'] / $img_height
);
if ($scale > 1)
{
$scale = 1;
}
$new_width = $img_width * $scale;
$new_height = $img_height * $scale;
$new_img = #imagecreatetruecolor($new_width, $new_height);
switch (strtolower(substr(strrchr($file_name, '.'), 1)))
{
case 'jpg':
case 'jpeg':
$src_img = #imagecreatefromjpeg($file_path);
$write_image = 'imagejpeg';
break;
case 'gif':
$src_img = #imagecreatefromgif($file_path);
$write_image = 'imagegif';
break;
case 'png':
$src_img = #imagecreatefrompng($file_path);
$write_image = 'imagepng';
break;
default:
$src_img = $image_method = null;
}
$success = $src_img && #imagecopyresampled(
$new_img, $src_img, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height
) && $write_image($new_img, $new_file_path);
// Free up memory (imagedestroy does not delete files):
#imagedestroy($src_img);
#imagedestroy($new_img);
return $success;
}
private function has_error($uploaded_file, $file, $error)
{
if ($error)
{
return $error;
}
if (!preg_match($this->options['accept_file_types'], $file->name))
{
return 'acceptFileTypes';
}
if ($uploaded_file && is_uploaded_file($uploaded_file))
{
$file_size = filesize($uploaded_file);
} else
{
$file_size = $_SERVER['CONTENT_LENGTH'];
}
if ($this->options['max_file_size'] && (
$file_size > $this->options['max_file_size'] ||
$file->size > $this->options['max_file_size'])
)
{
return 'maxFileSize';
}
if ($this->options['min_file_size'] &&
$file_size < $this->options['min_file_size'])
{
return 'minFileSize';
}
if (is_int($this->options['max_number_of_files']) && (
count($this->get_file_objects()) >= $this->options['max_number_of_files'])
)
{
return 'maxNumberOfFiles';
}
return $error;
}
private function handle_file_upload($uploaded_file, $name, $size, $type, $error)
{
$fileUpload = new stdClass();
$fileUpload->name = basename(stripslashes($name));
$fileUpload->size = intval($size);
$fileUpload->type = $type;
$fileUpload->error = null;
$extension = end(explode(".", $fileUpload->name));
$fileUpload->error = $this->has_error($uploaded_file, $fileUpload, $error);
if (!$fileUpload->error)
{
if (strlen(trim($fileUpload->name)) == 0)
{
$fileUpload->error = 'Filename not found.';
}
}
elseif (intval($size) == 0)
{
$fileUpload->error = 'File received has zero size.';
}
elseif (intval($size) > $this->options['max_file_size'])
{
$fileUpload->error = 'File received is larger than permitted.';
}
if (!$fileUpload->error && $fileUpload->name)
{
if ($fileUpload->name[0] === '.')
{
$fileUpload->name = substr($fileUpload->name, 1);
}
$newFilename = MD5(microtime());
// figure out upload type
$file_size = 0;
// select server from pool
$uploadServerId = getAvailableServerId();
$db = Database::getDatabase(true);
$uploadServerDetails = $db->getRow('SELECT * FROM file_server WHERE id = ' . $db->quote($uploadServerId));
// override storage path
if(strlen($uploadServerDetails['storagePath']))
{
$this->options['upload_dir'] = $uploadServerDetails['storagePath'];
if (substr($this->options['upload_dir'], strlen($this->options['upload_dir']) - 1, 1) == '/')
{
$this->options['upload_dir'] = substr($this->options['upload_dir'], 0, strlen($this->options['upload_dir']) - 1);
}
$this->options['upload_dir'] .= '/';
}
// move remotely via ftp
if($uploadServerDetails['serverType'] == 'remote')
{
// connect ftp
$conn_id = ftp_connect($uploadServerDetails['ipAddress'], $uploadServerDetails['ftpPort'], 30);
if($conn_id === false)
{
$fileUpload->error = 'Could not connect to file server '.$uploadServerDetails['ipAddress'];
}
// authenticate
if(!$fileUpload->error)
{
$login_result = ftp_login($conn_id, $uploadServerDetails['ftpUsername'], $uploadServerDetails['ftpPassword']);
if($login_result === false)
{
$fileUpload->error = 'Could not authenticate with file server '.$uploadServerDetails['ipAddress'];
}
}
// create the upload folder
if(!$fileUpload->error)
{
$uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
if(!ftp_mkdir($conn_id, $uploadPathDir))
{
// Error reporting removed for now as it causes issues with existing folders. Need to add a check in before here
// to see if the folder exists, then create if not.
// $fileUpload->error = 'There was a problem creating the storage folder on '.$uploadServerDetails['ipAddress'];
}
}
// upload via ftp
if(!$fileUpload->error)
{
$file_path = $uploadPathDir . '/' . $newFilename;
clearstatcache();
if ($uploaded_file && is_uploaded_file($uploaded_file))
{
// initiate ftp
$ret = ftp_nb_put($conn_id, $file_path, $uploaded_file,
FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA)
{
// continue uploading
$ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED)
{
$fileUpload->error = 'There was a problem uploading the file to '.$uploadServerDetails['ipAddress'];
}
else
{
$file_size = filesize($uploaded_file);
#unlink($uploaded_file);
}
}
}
// close ftp connection
ftp_close($conn_id);
}
// move into local storage
else
{
// create the upload folder
$uploadPathDir = $this->options['upload_dir'] . substr($newFilename, 0, 2);
#mkdir($uploadPathDir);
$file_path = $uploadPathDir . '/' . $newFilename;
clearstatcache();
if ($uploaded_file && is_uploaded_file($uploaded_file))
{
move_uploaded_file($uploaded_file, $file_path);
}
$file_size = filesize($file_path);
}
// check filesize uploaded matches tmp uploaded
if ($file_size === $fileUpload->size)
{
$fileUpload->url = $this->options['upload_url'] . rawurlencode($fileUpload->name);
// insert into the db
$fileUpload->size = $file_size;
$fileUpload->delete_url = '~d?' . $this->options['delete_hash'];
$fileUpload->info_url = '~i?' . $this->options['delete_hash'];
$fileUpload->delete_type = 'DELETE';
// create delete hash, make sure it's unique
$deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime());
$existingFile = file::loadByDeleteHash($deleteHash);
while ($existingFile != false)
{
$deleteHash = md5($fileUpload->name . getUsersIPAddress() . microtime());
$existingFile = file::loadByDeleteHash($deleteHash);
}
// store in db
$db = Database::getDatabase(true);
$dbInsert = new DBObject("file", array("originalFilename", "shortUrl", "fileType", "extension", "fileSize", "localFilePath", "userId", "totalDownload", "uploadedIP", "uploadedDate", "statusId", "deleteHash", "serverId"));
$dbInsert->originalFilename = $fileUpload->name;
$dbInsert->shortUrl = 'temp';
$dbInsert->fileType = $fileUpload->type;
$dbInsert->extension = $extension;
$dbInsert->fileSize = $fileUpload->size;
$dbInsert->localFilePath = str_replace($this->options['upload_dir'], "", $file_path);
// add user id if user is logged in
$dbInsert->userId = NULL;
$Auth = Auth::getAuth();
if ($Auth->loggedIn())
{
$dbInsert->userId = (int) $Auth->id;
}
$dbInsert->totalDownload = 0;
$dbInsert->uploadedIP = getUsersIPAddress();
$dbInsert->uploadedDate = sqlDateTime();
$dbInsert->statusId = 1;
$dbInsert->deleteHash = $deleteHash;
$dbInsert->serverId = $uploadServerId;
if (!$dbInsert->insert())
{
$fileUpload->error = 'abort';
}
// create short url
$tracker = 1;
$shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
$fileTmp = file::loadByShortUrl($shortUrl);
while ($fileTmp)
{
$shortUrl = file::createShortUrlPart($tracker . $dbInsert->id);
$fileTmp = file::loadByShortUrl($shortUrl);
$tracker++;
}
// update short url
file::updateShortUrl($dbInsert->id, $shortUrl);
// update fileUpload with file location
$file = file::loadByShortUrl($shortUrl);
$fileUpload->url = $file->getFullShortUrl();
$fileUpload->delete_url = $file->getDeleteUrl();
$fileUpload->info_url = $file->getInfoUrl();
$fileUpload->stats_url = $file->getStatisticsUrl();
$fileUpload->short_url = $shortUrl;
}
else if ($this->options['discard_aborted_uploads'])
{
//#TODO - made ftp compatible
#unlink($file_path);
#unlink($uploaded_file);
if(!isset($fileUpload->error))
{
$fileUpload->error = 'maxFileSize';
}
}
}
return $fileUpload;
}
public function get()
{
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name)
{
$info = $this->get_file_object($file_name);
} else
{
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
public function post()
{
$upload = isset($_FILES[$this->options['param_name']]) ?
$_FILES[$this->options['param_name']] : array(
'tmp_name' => null,
'name' => null,
'size' => null,
'type' => null,
'error' => null
);
$info = array();
if (is_array($upload['tmp_name']))
{
foreach ($upload['tmp_name'] as $index => $value)
{
$info[] = $this->handle_file_upload($upload['tmp_name'][$index],
isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
$upload['error'][$index]
);
}
} else
{
$info[] = $this->handle_file_upload($upload['tmp_name'],
isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'],
isset($_SERVER['HTTP_X_FILE_SIZE']) ? $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'],
isset($_SERVER['HTTP_X_FILE_TYPE']) ? $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'],
$upload['error']
);
}
header('Vary: Accept');
if (isset($_SERVER['HTTP_ACCEPT']) &&
(strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false))
{
header('Content-type: application/json');
} else
{
header('Content-type: text/plain');
}
echo json_encode($info);
}
}
$upload_handler = new uploadHandler();
header('Pragma: no-cache');
header('Cache-Control: private, no-cache');
header('Content-Disposition: inline; filename="files.json"');
// check we are receiving the request from this script
if (!checkReferrer())
{
// exit
header('HTTP/1.0 400 Bad Request');
exit();
}
switch ($_SERVER['REQUEST_METHOD'])
{
case 'HEAD':
case 'GET':
$upload_handler->get();
break;
case 'POST':
$upload_handler->post();
break;
default:
header('HTTP/1.0 405 Method Not Allowed');
}
You need downloader. Not uploader. You want to download a file to your server from another server. To achieve that from PHP, you can use cUrl or file_get_contents. In the form, just take the URL and when the form is submitted, download the file from that URL to your server using cUrl or file_get_contents().