PHP Uploader wont rename uploads - php

I have a PHP uploader on my Dedi server, the uploader works as it should, only after it uploads the files it dose not rename them from their temp names..
it comes out something like
2b4134a1f559b6da866c9febbc92d709.mp3
The uploader file.php
<?php
class file {
public $id;
public $fileName;
public $systemFilename;
public $fileType;
public $fileExtension;
public $systemUrl;
public $originalUrl;
public $thumbPath;
public $thumbUrl;
public $canHaveThumb;
public $ts;
public $size;
public $authorized;
public $knownExtensions;
public $mimeType;
public $filePath;
public function __construct() {
$this->setKnownExtensions();
}
// Check and save a new file on the disk and the database
public function uploadNewFile($files) {
$result = array(); // The variable we will send back when we have finished to check and save the file
$this->setFileName($files['Filedata']['name']);
if ($this->authorized) {
// Build the target path
$siteUrl = F3::get('siteUrl'); // Set in config.php
$uploadFolder = F3::get('uploadFolder'); // Set in config.php
$uploadUrl = $_SERVER['DOCUMENT_ROOT'] . '/' . $uploadFolder . '/';
// Get the temporary file
$tempFile = $_FILES['Filedata']['tmp_name'];
// Get a unique system name
$rand = rand(1, 414342);
$ts = time();
$systemName = md5($rand . $ts);
$this->systemFilename = $systemName . '.' . $this->fileExtension;
$this->ts = $ts;
// Clean the path
$targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
// Save the file on the disk
move_uploaded_file($tempFile, $targetFile);
// Save the file in the database
DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');
$this->id = F3::get('DB->pdo')->lastInsertId();
// Retrieve the template for the file list
$result['tableRow'] = $this->getTableRow();
// We create a thumbnail if it is a simple image
$this->createThumb();
}
$result['file'] = $this;
return $result;
}
public function canHaveThumb() {
if ($this->fileType == 'image') {
$this->canHaveThumb = true;
} else {
$this->canHaveThumb = false;
}
return $this->canHaveThumb;
}
public function createThumb() {
if ($this->canHaveThumb()) {
$filePath = $this->getFilePath();
if (file_exists($filePath)) {
$thumbPath = site::getThumbsPath();
$thumb = new image($filePath);
$thumb->dir($thumbPath);
$thumb->width(250);
$thumb->save();
}
}
}
public function getThumbPath() {
$thumbFolderPath = site::getThumbsPath();
$this->thumbPath = $thumbFolderPath . $this->systemFilename;
if (!file_exists($this->thumbPath)) {
$this->createThumb();
}
return $this->thumbPath;
}
public function getThumbUrl() {
$base = F3::get('BASE');
$thumbsFolder = F3::get('thumbsFolder');
$this->thumbUrl = $base . '/' . $thumbsFolder . '/' . $this->systemFilename;
return $this->thumbUrl;
}
// Delete a file
public function delete() {
$filePath = $this->getFilePath();
if (file_exists($filePath)) {
unlink($filePath); // Remove the file from the hard drive
}
if ($this->canHaveThumb()) {
$thumbPath = $this->getThumbPath();
if (file_exists($thumbPath)) {
unlink($thumbPath); // Remove the thumb from the hard drive
}
}
DB::sql('DELETE FROM hm_files WHERE id = ' . $this->id); // Remove from database
}
// Set the filename and the file extension
public function setFileName($fileName) {
$this->fileName = $fileName;
$this->fileExtension = strtolower(substr(strrchr($this->fileName, '.'), 1));
$this->checkExtension();
$this->getFileType();
}
// Check if a file has an authorized extension
public function checkExtension() {
$okExtensions = F3::get('okExtensions'); // defined in config.php
if (in_array($this->fileExtension, $okExtensions)) {
$this->authorized = true;
} else {
$this->authorized = false;
}
return $this->authorized;
}
// Define the file type (eg: image, video, ...)
// Not used in this version
public function getFileType() {
$ext = $this->fileExtension;
if (isset($this->knownExtensions[$ext])) {
$this->fileType = $this->knownExtensions[$ext];
} else {
$this->fileType = 'file';
}
return $this->fileType;
}
public function getFileSize() {
$this->size = filesize($this->getFilePath());
return $this->size;
}
// Transform the filesize in kilobytes, megabytes, ... and append the unit.
public function getReadableSize() {
$bytes = $this->getFileSize();
$decimals = 2;
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$sz[$factor];
}
// Get the HTML for the file list
public function getTableRow() {
F3::set('file', $this);
// We check if the file exist before displaying the table row
if (file_exists($this->getFilePath())) {
$tableRow = F3::render('views/table_row.php');
return $tableRow;
} else {
return '';
}
}
// Get a file path on the server harddrive
public function getFilePath() {
$path = F3::get('rootPath');
$uploadsFolder = F3::get('uploadFolder');
$this->filePath = $path . '/' . $uploadsFolder . '/' . $this->systemFilename;
return $this->filePath;
}
public function getSystemUrl() {
$base = F3::get('BASE');
$this->systemUrl = $base . '/file/' . $this->systemFilename;
return $this->systemUrl;
}
public function getOriginalUrl() {
$siteUrl = F3::get('siteUrl');
$uploadsFolder = F3::get('uploadFolder');
$this->originalUrl = $siteUrl . '/' . $uploadsFolder . '/' . $this->systemFilename;
return $this->originalUrl;
}
public function getMime() {
$filePath = $this->getFilePath();
$finfo = new finfo(FILEINFO_MIME);
$info = $finfo->file($filePath);
return $info;
}
public function gearUp($queryResult) {
$this->id = $queryResult['id'];
$this->fileName = $queryResult['fileName'];
$this->systemFilename = $queryResult['systemFilename'];
$this->fileType = $queryResult['fileType'];
$this->ts = $queryResult['time'];
$this->getSystemUrl();
$this->getOriginalUrl();
return $this;
}
// Display a single file
public static function display($systemFilename) {
$fileQuery = DB::sql('SELECT * FROM hm_files WHERE systemFilename LIKE "' . $systemFilename . '"');
if (count($fileQuery) > 0) {
$file = new file();
$file->gearUp($fileQuery[0]);
$mime = $file->getMime();
header('Content-Disposition: inline; filename="' . $file->fileName . '"');
header('Content-type: ' . $mime);
readfile($file->getOriginalUrl());
} else {
return false;
}
}
// Build a zip of files
// You can create direct download by setting $directDownload on true.
// Important : we don't use the classic ZipArchive class of PHP. When we zip large files it produces errors.
// We use the pclzip class. Doc: http://www.phpconcept.net/pclzip/
public static function serveZip($idsArray, $token, $directDownload = true) {
if (count($idsArray) > 0) {
$rootPath = F3::get('rootPath');
$zipPath = $rootPath . '/zips/archive-' . $token . '.zip';
$zipper = new pclzip($zipPath);
foreach ($idsArray as $id) {
$file = file::fetch($id);
$filePath = $file->getFilePath();
$filesArray = array(
array(PCLZIP_ATT_FILE_NAME => $filePath,
PCLZIP_ATT_FILE_NEW_FULL_NAME => $file->fileName)
);
$zipper->add($filesArray, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_ALL_PATH);
}
// We set the cookie to track the end of zipping
setcookie('multiUp', $token);
// If this is a direct download we serve the zip in the browser and then destroy the zipfile on the server
if ($directDownload) {
$zipContent = file_get_contents($zipPath);
header('Content-Disposition: attachment; filename="archive.zip"');
header('Content-type: application/zip');
echo $zipContent;
unlink($zipPath);
}
}
}
// Get info for a single file
public static function fetch($id) {
$fileQuery = DB::sql('SELECT * FROM hm_files WHERE id = ' . $id);
if (count($fileQuery) > 0) {
$file = new file();
$file->gearUp($fileQuery[0]);
return $file;
} else {
return false;
}
}
// Fetch all files in the database
public static function fetchAll() {
$files = array();
$filesId = DB::sql('SELECT id FROM hm_files ORDER BY time DESC');
foreach ($filesId as $fileId) {
$file = file::fetch($fileId['id']);
if ($file) {
$files[] = $file;
}
}
return $files;
}
// Creates families for file extensions
// Not used in this version. Might be usefull to create icons
private function setKnownExtensions() {
$fileTypes = array();
// DOCUMENTS
$fileTypes['pdf'] = 'pdf';
// PLAIN TEXT
$fileTypes['txt'] = 'text';
$fileTypes['rtf'] = 'text';
$fileTypes['as'] = 'text';
$fileTypes['xml'] = 'text';
$fileTypes['html'] = 'text';
$fileTypes['htm'] = 'text';
$fileTypes['js'] = 'text';
$fileTypes['php'] = 'text';
$fileTypes['asp'] = 'text';
$fileTypes['py'] = 'text';
$fileTypes['sql'] = 'text';
$fileTypes['css'] = 'text';
// ARCHIVES
$fileTypes['zip'] = 'archive';
$fileTypes['rar'] = 'archive';
$fileTypes['7zip'] = 'archive';
$fileTypes['gzip'] = 'archive';
$fileTypes['gz'] = 'archive';
$fileTypes['tgz'] = 'archive';
$fileTypes['ace'] = 'archive';
$fileTypes['arc'] = 'archive';
// EXCEL
$fileTypes['xls'] = 'excel';
$fileTypes['xlsx'] = 'excel';
$fileTypes['xlsm'] = 'excel';
$fileTypes['ods'] = 'excel';
$fileTypes['ots'] = 'excel';
$fileTypes['csv'] = 'excel';
$fileTypes['numbers'] = 'excel';
// WORD
$fileTypes['doc'] = 'word';
$fileTypes['docx'] = 'word';
$fileTypes['odt'] = 'word';
$fileTypes['ott'] = 'word';
$fileTypes['pages'] = 'word';
// POWERPOINT
$fileTypes['ppt'] = 'powerpoint';
$fileTypes['pptx'] = 'powerpoint';
$fileTypes['odp'] = 'powerpoint';
$fileTypes['otp'] = 'powerpoint';
$fileTypes['key'] = 'powerpoint';
// IMAGES
$fileTypes['png'] = 'image';
$fileTypes['gif'] = 'image';
$fileTypes['jpg'] = 'image';
$fileTypes['jpeg'] = 'image';
// UNCOMMON IMAGEs
$fileTypes['svg'] = 'rareimage';
$fileTypes['svgz'] = 'rareimage';
$fileTypes['jpf'] = 'rareimage';
$fileTypes['bmp'] = 'rareimage';
$fileTypes['eps'] = 'rareimage';
$fileTypes['tif'] = 'rareimage';
$fileTypes['tiff'] = 'rareimage';
$fileTypes['raw'] = 'rareimage';
$fileTypes['pbm'] = 'rareimage';
$fileTypes['tga'] = 'rareimage';
$fileTypes['cdr'] = 'rareimage';
// "WORKING" IMAGES
$fileTypes['psd'] = 'photoshop';
$fileTypes['psb'] = 'photoshop';
$fileTypes['ai'] = 'illustrator';
$fileTypes['ait'] = 'illustrator';
$fileTypes['fxg'] = 'illustrator';
$fileTypes['cgm'] = 'illustrator';
$fileTypes['indd'] = 'indesign';
$fileTypes['idml'] = 'indesign';
$fileTypes['fla'] = 'flash';
$fileTypes['swf'] = 'flash';
$fileTypes['xfl'] = 'flash';
$fileTypes['prproj'] = 'premiere';
$fileTypes['aep'] = 'aftereffect';
// 3D
$fileTypes['3ds'] = '3d';
$fileTypes['dwg'] = '3d';
$fileTypes['dxf'] = '3d';
$fileTypes['max'] = '3d';
// SOUND / MUSIC
$fileTypes['mp3'] = 'music';
$fileTypes['wav'] = 'music';
$fileTypes['flac'] = 'music';
$fileTypes['aac'] = 'music';
$fileTypes['aiff'] = 'music';
$fileTypes['aif'] = 'music';
$fileTypes['aifc'] = 'music';
$fileTypes['wma'] = 'music';
$fileTypes['au'] = 'music';
$fileTypes['snd'] = 'music';
$fileTypes['aa3'] = 'music';
$fileTypes['oma'] = 'music';
$fileTypes['at3'] = 'music';
$fileTypes['m3u'] = 'music';
$fileTypes['amr'] = 'music';
$fileTypes['cda'] = 'music';
//VIDEO
$fileTypes['avi'] = 'video';
$fileTypes['flv'] = 'video';
$fileTypes['m4v'] = 'video';
$fileTypes['mkv'] = 'video';
$fileTypes['mov'] = 'video';
$fileTypes['mpeg'] = 'video';
$fileTypes['mpg'] = 'video';
$fileTypes['mpe'] = 'video';
$fileTypes['mp4'] = 'video';
$fileTypes['3gp'] = 'video';
$fileTypes['aep'] = 'video';
$this->knownExtensions = $fileTypes;
}
}
?>
It worked fine on managed servers that have CPanel thats why i suspect my PHP.ini file? (i installed the server myself)
If it is the .ini file, what should i look for?

The script changes the file names on purpose, to guarantee they are always unique. This prevents a file from getting overwritten if someone uploads a file with the same file name. If you really want to retain the original name, you can change this line:
$targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
to this:
$targetFile = str_replace('//', '/', $uploadUrl) . $this->fileName;
Note that although the script assigns a unique name to each uploaded file, it still retains the original name in the database table as shown here:
DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');

Related

How to access a file using "file_put_contents" in PHP?

<?php
require_once(dirname(__FILE__) . '/connectionClass.php');
class webcamClass
{
public $imageFolder = "ABC";
//This function will create a new name for every image captured using the current data and time.
public function getNameWithPath()
{
$name = $this->imageFolder . date('D/M/Y') . ".jpg";
return $name;
}
//function will get the image data and save it to the provided path with the name and save it to the database
public function showImage()
{
$file = file_put_contents($this->getNameWithPath(), file_get_contents('php://input'));
if (!$file) {
return "ERROR: Failed to write data to " . $this->getNameWithPath() . ", \n";
} else {
$this->saveImageToDatabase($this->getNameWithPath()); // this line is for saving image to database
return $this->getNameWithPath();
}
}
//function for changing the image to base64
public function changeImagetoBase64($image)
{
$path = $image;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
public function saveImageToDatabase($imageurl)
{
$image = $imageurl;
// $image= $this->changeImagetoBase64($image); //if you want to go for base64 encode than enable this line
if ($image) {
$query = "Insert into snapshot (Image) values('$image')";
$result = $this->query($query);
if ($result) {
return "Image saved to database";
} else {
return "Image not saved to database";
}
}
}
}
Not able to access a file using file_put_contents.
Check your file path. For example you access to ABCSat/Jun/2017.jpg! I think you try to access ABC/Sat/Jun/2017.jpg, so add / or DIRECTORY_SEPARATOR at the end of $image_folder:
<?php
require_once(dirname(__FILE__) . '/connectionClass.php');
class webcamClass
{
public $imageFolder = "ABC" . DIRECTORY_SEPARATOR;
//This function will create a new name for every image captured using the current data and time.
public function createDirectories($file_name = ''){
$directories = explode('/', $file_name);
$dir_path = '';
for($i = 0; $i < count($directories) - 1; $i++) {
$dir_path .= $directories[$i] . DIRECTORY_SEPARATOR;
if(!file_exists($dir_path)) {
mkdir($dir_path);
}
}
}
public function getNameWithPath()
{
$name = $this->imageFolder . date('D/M/Y') . ".jpg";
$this->createDirectories($name);
return $name;
}
//function will get the image data and save it to the provided path with the name and save it to the database
public function showImage()
{
$file = file_put_contents($this->getNameWithPath(), file_get_contents('php://input'));
if (!$file) {
return "ERROR: Failed to write data to " . $this->getNameWithPath() . ", \n";
} else {
$this->saveImageToDatabase($this->getNameWithPath()); // this line is for saving image to database
return $this->getNameWithPath();
}
}
//function for changing the image to base64
public function changeImagetoBase64($image)
{
$path = $image;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
public function saveImageToDatabase($imageurl)
{
$image = $imageurl;
// $image= $this->changeImagetoBase64($image); //if you want to go for base64 encode than enable this line
if ($image) {
$query = "Insert into snapshot (Image) values('$image')";
$result = $this->query($query);
if ($result) {
return "Image saved to database";
} else {
return "Image not saved to database";
}
}
}
public function query($query) {
$dbObj = new dbObj();
$conn = $dbObj->getConnstring();
return mysqli_query($conn, $query);
}
}

Upload a file using Symfony2 and a simple form

I'm trying to upload a file in my symfony2 project by using a simple Form.
I did read the official doc of symfony but Id want only move my file to directory and update a field in a db table (called user) not create an entity for the file. I use an example I succeed to upload but in .tmp extension (ex. phpXXX.tmp). Any Ideas please.
here my code :
Document.php:
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Document
{
private $file;
private $subDir;
private $filePersistencePath;
/** #var string */
protected static $uploadDirectory = '%kernel.root_dir%/../styles/images';
static public function setUploadDirectory($dir)
{
self::$uploadDirectory = $dir;
}
static public function getUploadDirectory()
{
if (self::$uploadDirectory === null) {
throw new \RuntimeException("Trying to access upload directory for profile files");
}
return self::$uploadDirectory;
}
public function setSubDirectory($dir)
{
$this->subDir = $dir;
}
public function getSubDirectory()
{
if ($this->subDir === null) {
throw new \RuntimeException("Trying to access sub directory for profile files");
}
return $this->subDir;
}
public function setFile(File $file)
{
$this->file = $file;
}
public function getFile()
{
return new File(self::getUploadDirectory() . "/" . $this->filePersistencePath);
}
public function getOriginalFileName()
{
return $this->file->getClientOriginalName();
}
public function getFilePersistencePath()
{
return $this->filePersistencePath;
}
public function processFile()
{
if (! ($this->file instanceof UploadedFile) ) {
return false;
}
$uploadFileMover = new UploadFileMover();
$this->filePersistencePath = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDirectory(),$this->subDir);
}
}
UploadFileMover
use Symfony\Component\HttpFoundation\File\UploadedFile;
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath) {
$originalName = $file->getFilename();
// use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
// $relativePath = date('Y-m', filemtime($file->getPath()));
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i = 1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
controller :
public function uploadImgAction(Request $req) {
if ($req->getMethod() == 'POST') {
$status = 'success';
$uploadedURL = '';
$message = 'Image modifiée';
$image = $req->files->get('fileselect');
if (($image instanceof UploadedFile) && ($image->getError() == '0')) {
if ($image->getSize() < 2000000) {
$originalName = $image->getClientOriginalName();
$name_array = explode('.', $originalName);
$file_type = $name_array[sizeof($name_array) - 1];
$valid_filetypes = array('jpg', 'jpeg', 'bmp', 'png');
if (in_array(strtolower($file_type), $valid_filetypes)) {
//télécharegement du fichier
//Start Uploading File
$document = new Document();
$document->setFile($image);
$document->setSubDirectory('uploads');
$document->processFile();
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
} else {
$status = 'echoue';
$message = 'Seuls les extensions png, jpg, jpeg et bmp sont acceptées';
}
} else {
$status = 'echoue';
$message = 'La taille du fichier dépasse 2MB';
}
} else {
$status = 'echoue';
$message = 'Une erreur de télechargement';
}
return $this->render('PIRecrutementBundle:xx:xxx.html.twig');
//return new Response($uploadedUrl);
} else {
return $this->render('xxxBundle:xx:xxx.html.twig');
}
}
Exactly as Tomasz Turkowski said the solution is to change the base-name of the file by its real name using $file->getClientOriginalName( in class UploadFileMover.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath)
{
// $originalName = $file->getFilename();
$originalName = $file->getClientOriginalName();
// use filemtime() to have a more determenistic
Without changing anything like .tmp to some other extention or the original name, you can still store the same obtained path in DB. I think you can write a query to store the path in DB after this statement in your controller
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
By using the variable $uploadURL like
{
//in your methodAction
"Update [YOUR TABLE] SET [PATHcolomn]=".$uploadURL." WHERE USERid=".$user->getUid()." "
$path= "SELECT [PATHcolomN] FROM [YOUR TABLE] WHERE USERid=".$user->getUid()." "
$this->data['path']=$path;
return $this->data;
}
After Updating, you can fetch this path in the place of <img src= {{ path }} >

Image upload when exists 500 Internal Server Error

I am making image uploader and It works fine until I tryed to upload image with same name. I did recursive method in class, maybe that is problem.
I got this error:
500 Internal Server Error
Image is not big, and it works when does not exists.
Here is my upload.php file:
$upload = new Upload("post", $_FILES['file']);
$upload->upload();
And here is my Uploader.php class file:
class Upload {
protected $_type = null,
$_file = null,
$_file_name = null,
$_file_tmp = null,
$_slug = null,
$_path = null;
public function __construct($type, $file, $slug = null) {
$this->_file = $file;
$this->_file_tmp = $file['tmp_name'];
$this->_file_name = $file['name'];
$this->_slug = $slug;
if($type == "post") {
$this->_type = "post";
$config1 = '/admin/posts/images'; // Relative to domain name
$config = $_SERVER['DOCUMENT_ROOT'] . $config1; // Physical path. [Usually works fine like this]
$this->_path = $config . "/";
} else if($type == "gallery") {
$this->_type = "gallery";
$config1 = '/admin/galeries/images'; // Relative to domain name
$config = $_SERVER['DOCUMENT_ROOT'] . $config1; // Physical path. [Usually works fine like this]
$this->_path = $config . "/";
}
}
public function upload() {
$new_name = "";
if($this->_slug == null) {
$new_name = $this->_file_name;
} else {
$new_name = $this->_slug . "-" . $this->_file_name;
}
if (file_exists($this->_path.$new_name)) {
if($this->_slug != null)
$new_name = $this->_slug . "-" . rand(00,99) . "-" . $this->_file_name;
else
$new_name = rand(0000,9999) . "-" . $new_name;
// MAYBE HERE IS PROBLEM...
$this->upload();
} else {
move_uploaded_file($this->_file_tmp, $this->_path.$new_name);
return true;
}
}
As you can see my method upload() is called recursively. I am wondering if these protected variables are gone after that call.
I had to add $this->_file_name = $new_name; above $this->upload();

Read .eml file using php

I have the php script as shown below. I want to ask that using this script how can i read normal .eml file as we read in gmail or yahoo? how can i get attachments from it ?
<?php
/**
*
* This code has been written by Alexis Ulrich (http://alx2002.free.fr)
* This code is in the public domain.
*
*/
define(EML_FILE_PATH,'');
define(PICTURE_DIRECTORY_PATH,'img/');
// gets parameters
$images = substr($_GET['images'],0,5);
$filename = substr($_GET['filename'],0,50);
if ($filename == '') $filename = 'toto.eml';
$eml_file = EML_FILE_PATH.$filename;
// opens file
if (!($content = fread(fopen(EML_FILE_PATH.$filename, 'r'), filesize(EML_FILE_PATH.$filename))))
die('File not found ('.EML_FILE_PATH.$filename.')');
// two kinds of separators
if (strpos($content,'------_') !== false) $separator = '------_';
else $separator = '------=_';
$aContent = explode($separator,$content);
$aImages = array();
foreach($aContent as $thisContent) {
if (strpos($thisContent,'Content-Type: text/html') !== false) {
// email HTML body
$thisContent = substr($thisContent,strpos($thisContent,'<!DOCTYPE'));
$thisHTMLContent = quoted_printable_decode($thisContent);
//echo "<hr>$thisHTMLContent<hr>\n\n";
}
if (strpos($thisContent,'Content-Type: image/gif;') !== false) {
// base64 gif picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.gif"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.gif'));
$searched = 'Content-Location: ' . $img_location . '.gif';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'gif', 'base64'=>$img_base64);
//print_r($aThisImage);
$aImages[] = $aThisImage;
}
if (strpos($thisContent,'Content-Type: image/jpeg;') !== false) {
// base64 jpg picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.jpg"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.jpg'));
$searched = 'Content-Location: ' . $img_location . '.jpg';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'jpg', 'base64'=>$img_base64);
$aImages[] = $aThisImage;
}
}
//print_r($aImages);
foreach($aImages as $image) {
if ($images == 'filed') {
// image file creation
if (!file_exists(PICTURE_DIRECTORY_PATH."$image[location].$image[type]")) {
if (!$handle = fopen (PICTURE_DIRECTORY_PATH."$image[location].$image[type]", "wb"))
die("Cannot open file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
if (!fwrite($handle, base64_decode($image[base64])))
die("Cannot write into file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
fclose($handle);
}
$thisHTMLContent = str_replace('cid:'.$image['id'],PICTURE_DIRECTORY_PATH."$image[location].$image[type]",$thisHTMLContent);
}
else {
// images to be created on the fly
$imageLocation = urlencode($image[location]);
$file = urlencode($eml_file);
$thisHTMLContent = str_replace('cid:'.$image['id'],"viewImage.php?imageLocation=$imageLocation&file=$file",$thisHTMLContent);
}
$thisHTMLContent = preg_replace("/<IMG HEIGHT=(\d*)/i","<img ",$thisHTMLContent);
// no base href referring to local file
$thisHTMLContent = preg_replace("/href=\"file(.*)\"/i","",$thisHTMLContent);
}
echo $thisHTMLContent;
?>
Thanks in advance and would hope to receive reply soon.

jQuery and PHP Remote Upload

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().

Categories