PHP File Upload - php

I'm looking to change my normal PHP file upload into a multiple file upload.
I have this as my single file input:
<input name="sliderfile" id="sliderfile" type="file" />
And this is the PHP I'm using to upload to my server/place in folder and register it into my databases:
if($_POST[sliderurl]){
$path= "uploads/".$HTTP_POST_FILES['sliderfile']['name'];
if($ufile !=none){
if(copy($HTTP_POST_FILES['sliderfile']['tmp_name'], $path)){
date_default_timezone_set('Europe/London');
$added = date("F j, Y");
$query = mysql_query("INSERT INTO `slider` (`imgurl`, `url`, `title`, `description`, `added`) VALUES ('$path', '$_POST[sliderurl]', '$_POST[slidertitle]', '$_POST[sliderdesc]', '$added')");
?>
<div id="fademessage" style="margin-top: 13px;">
<p class="message_greenadmin">Your slide has been successfully created and added to the homepage, Thank you.</p>
</div>
<?php
}else{
?>
<div id="fademessage" style="margin-top: 13px;">
<p class="message_redadmin">Something seems to have gone wrong. Try renaming the photos file name.</p>
</div>
<?php
}
}
}else{
}
?>
Any help would be appreciated,
Thanks!

you need use move_uploaded_file() for save uploaded file. And
foreach ($_FILES['sliderfile'] as $example) {
UploadFile($example);
}

Off the top of my head, I think this may work. Name each input the same with brackets (sliderfile[]) and then loop through them.
foreach ($_FILES['sliderfile'] AS $file) {
UploadFile($file);
}

Use function to upload file
function uploadImage($fileName,$filePath,$allowedList,$errorLocation){
$img = $_FILES[$fileName];
$imgName =$_FILES[$fileName]['name'];
$imgTempName = $_FILES[$fileName]['tmp_name'];
$imgSize = $_FILES[$fileName]['size'];
$imgError= $_FILES[$fileName]['error'];
$fileExt = explode(".",$imgName);
$fileActualExt = strtolower(end($fileExt));
$allowed = $allowedList;
if(in_array($fileActualExt, $allowed)){
if($imgError == 0){
foreach ($imgTempName as $example) {
$GLOBALS['fileNameNew']='yourname'.uniqid('',true).".".$fileActualExt;
$fileDestination = $filePath.$GLOBALS['fileNameNew'];
$resultsImage = move_uploaded_file($example,$fileDestination);
}
}
else{
header('location:'.$errorLocation.'&imgerror');
exit();
}
}
else{
header('location:'.$errorLocation.'&extensionError&'.$fileActualExt);
exit();
}
}

Related

Improve an image upload script

I' m not a PHP specialist and I'd like to set up an image hosting service.
Currently, all the images in the folder are displayed to all visitors, I would like to add a condition that only allows the user who hosted his images to find them. I thought about using the Internet user's IP address but I don't know how to make such a system work?
Could you show me a functional example so I can apply it to the existing script?
Thank you in advance for your help!
Here is the current PHP script:
<?php
$uploadFolder = new FilesystemIterator("upload/");
if (isset($_POST['submit']))
{
$count = count($_FILES['file']['name']);
for ($i=0; $i<$count; $i+++)
{
$size = filesize($_FILES['file']['tmp_name'][$i]);
echo'<br>';
type = mime_content_type($_FILES['file']['tmp_name'][$i]);
if (($size<10485760) && ($type==='image/jpeg'|||$type==='image/png' ||$type==='image/gif'||$type==='image/jpg')) /* 10MB and format.jpeg,.jpg,.png and.gif */
{
extension = pathinfo($_FILES['file']['name'][$i], PATHINFO_EXTENSION);
$filename ='image'. uniqid() .'...'. $extension;
$uploadDir ='upload/';
$uploadFile = $uploadDir . $filename;
move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadFile);
}
else
{
echo '<p class="text-danger">Thank you for selecting one or more images of 10MB maximum and in one of the accepted formats:.jpeg,.jpg,.png or.gif.</p>';
}
}
}
foreach ($_POST as $key => $value)
{
$path= strtr($key,' _', '...');
if ($value ===='Delete this image')
{
if (file_exists($path))
{
unlink($path);
}
}
}
?>
and the display of hosted images:
<?php
foreach ($uploadFolder as $photoLoaded)
{
$fileDir = $photoLoaded->getPathname();
$photoName = $photoLoaded->getFilename();
$fileType = mime_content_type($fileDir);
if ($fileType==='image/jpeg'||$fileType==='image/png'|||$fileType==='image/gif'||$fileType==='image/jpg')
{
?>
<div class="card col-md-4">
<b><?php echo $photoName ?></b><br />
<img class="card-img-top img-thumbnail" src="<?php echo $fileDir; ?>" alt="">
<div class="card-body">
View this image in real size
</div>
</div>
<?php
}
}
?>
there are many solutions can implemented for this verification.
one of them(not the best) is to add users ids to images names then in display process split image name to get its user id.compare user id(from db) with user id(from image name) if equal then this photo belongs to user otherwise skip it.

file uploading with php xml

i have some problem with this code.
The problem is about the upload part of the script, when the user save the information, the file won't be uploaded by the script. Maybe i've made some errors?
The xml file work correctly, and any new inserted information are saved. i have two file input to separate the files.. i think the issue is related to this..?
<?php
if(isset($_POST['savetrack'])){
$errors= array();
foreach($_FILES['audio_file']['tmp_name'] as $key => $tmp_name ){
$Audiofile_name = $key.$_FILES['audio_file']['name'][$key];
$Audiofile_size =$_FILES['audio_file']['size'][$key];
$Audiofile_tmp =$_FILES['audio_file']['tmp_name'][$key];
$Audiofile_type=$_FILES['audio_file']['type'][$key];
$audioextensions = array("mp3");
$Audiofile_ext=explode('.',$_FILES['audio_file']['name'][$key]) ;
$Audiofile_ext=end($Audiofile_ext);
$Audiofile_ext=strtolower(end(explode('.',$_FILES['audio_file']['name'][$key])));
if(in_array($Audiofile_ext,$audioextensions ) === false){
$errors[]="extension not allowed";
}
if($file_size > 50097152){
$errors[]='File size must be less than 50 MB';
}
$desired_dir="mp3";
if(empty($errors)==true){
if(is_dir("$desired_dir/".$Audiofile_name)==false){
move_uploaded_file($Audiofile_tmp,"mp3/".$Audiofile_name);
}else{ //rename the file if another one exist
$new_dir="mp3/".$Audiofile_name.time();
rename($Audiofile_tmp,$new_dir) ;
}
}else{
print_r($errors);
}
}
// Cover upload
foreach($_FILES['cover_file']['tmp_name'] as $key => $tmp_name ){
$Imgfile_name = $key.$_FILES['cover_file']['name'][$key];
$Imgfile_size =$_FILES['cover_file']['size'][$key];
$Imgfile_tmp =$_FILES['cover_file']['tmp_name'][$key];
$Imgfile_type=$_FILES['cover_file']['type'][$key];
$imgextensions = array("jpeg","jpg","png");
$Imagefile_ext=explode('.',$_FILES['cover_file']['name'][$key]) ;
$Imagefile_ext=end($Imgfile_ext);
$Imagefile_ext=strtolower(end(explode('.',$_FILES['cover_file']['name'][$key])));
if(in_array($Imgfile_ext,$imgextensions ) === false){
$errors[]="extension not allowed";
}
if($Imgfile_size > 50097152){
$errors[]='File size must be less than 50 MB';
}
$desired_imgdir="img";
if(empty($errors)==true){
if(is_dir("$desired_imgdir/".$Imgfile_name)==false){
move_uploaded_file($Imgfile_tmp,"img/".$Imgfile_name);
}else{ //rename the file if another one exist
$imgnew_dir="img/".$Imgfile_name.time();
rename($Imgfile_tmp,$imgnew_dir) ;
}
}else{
print_r($errors);
}
}
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->load('tracks.xml');
$filenameAudio = $_FILES['audio_file']['name'];
$element = $xml->getElementsByTagName('track')->item(0);
$artistname = $element->getElementsByTagName('artist')->item(0);
$tracktitle = $element->getElementsByTagName('title')->item(0);
$relyear = $element->getElementsByTagName('year')->item(0);
$relabel = $element->getElementsByTagName('label')->item(0);
$cover = $element->getElementsByTagName('cover')->item(0);
$audio = $element->getElementsByTagName('audio')->item(0);
$newItem = $xml->createElement('track');
$newItem->appendChild($xml->createElement('artist', $_POST['artist_name']));
$newItem->appendChild($xml->createElement('title', $_POST['track_title']));
$newItem->appendChild($xml->createElement('year', $_POST['year']));
$newItem->appendChild($xml->createElement('label', $_POST['record_label']));
$newItem->appendChild($xml->createElement('cover',$Imgfile_name));
$newItem->appendChild($xml->createElement('audio',$Audiofile_name));
$xml->getElementsByTagName('releases')->item(0)->appendChild($newItem);
$xml->save('tracks.xml');
?>
I've found a solution by using an upload class and it seems to work. Now the issue is to load the uploaded audio file where i need, the consolle give me the following errors:
Uncaught (in promise) DOMException: Unable to decode audio data
GET http://localhost:8810/mixtape/mp3/audiofile 404 (Not Found)
I don't know if this issue is because the file name is loaded from a tag saved into the xml or if there is another type of problem. If i insert the file location manually it will work, but i need to load it from the xml.
here is the html code where i need to load the mp3 file, i've inserted the path where uploaded mp3 are hosted, but unsuccessfully.
<ul class="grid">
<?php
try{
$xml=simplexml_load_file("tracks.xml") or die("Error: Cannot create object");
}catch (Exception $e){
echo $e;
}
foreach($xml as $child)
{
$artistname = $child->artist;
$tracktitle = $child->title;
$relyear = $child->year;
$label = $child->label;
$audiofile = $child->audio;
$coverfile = $child->cover;
?>
<li class="grid__item">
<a class="grid__link" href="#album" data-playlist-1="mp3/<?php echo $audiofile ?>" data-playlist-2="mp3/<?php echo $audiofile ?>">
<div class="img-wrap img-wrap--grid">
<svg class="lp lp--grid">
<use xlink:href="#icon-lp-mini"></use>
</svg>
<img class="img img--grid" src="img/<?php echo $coverfile ?>" alt="album cover" />
</div>
<span class="year"><?php echo $relyear ?></span>
<h2 class="artist"><?php echo $artistname ?></h2>
<h3 class="title"><?php echo $tracktitle ?></h3>
</a>
</li>
<?php } ?>
</ul>

File uploading with PHP: Need it to retain extension

I have written a script to upload a file and store the path in a database table so it be downloaded. I have the following code:
<?php require("includes.php");
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if(isset($_FILES["upload"])==TRUE)
{
$errors = array();
$excluded = array("exe", "zip", "js", "msi");
/* If the contents of the file are to be held in the database then checking the extension is somewhat unneccessary but, hey, lets get rid of the files we know we don't want and then check the mime type. */
$name = $_FILES["upload"]["name"];
$size = $_FILES["upload"]["size"];
$type = $_FILES["upload"]["type"];
$temp = $_FILES["upload"]["tmp_name"];
$extension = explode(".", $name);
$extension = end($extension);
if(in_array($extension, $excluded)==TRUE)
{
$errors[] ="This file may not be uploaded";
}
if(empty($errors)==FALSE)
{
foreach($errors as $error)
{
echo "<p>{$error}</p>\n";
}
}
else
{
$year = date("Y");
$month = date("m");
$day = date("d");
$name = strtolower(str_replace(" ", "_", $name));
$path = "uploads/{$day}-{$month}-{$year}";
if(file_exists($path)==FALSE)
{
mkdir($path);
}
elseif(file_exists("{$path}/{$name}")==FALSE)
{
move_uploaded_file($temp, "{$path}/{$name}");
$add = add_file_to_database($connection, "{$path}/{$name}");
if($add[0]==TRUE)
{
$url = "http://example.com/uploads.php?id={$add[1]}";
echo "<p>This file has been uploaded, it can be found at: {$url}</p>";
}
else
{
echo "<p>I'm sorry but an error happened</p>";
}
}
}
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<label for="upload">Upload a file: </label><input type="file" name="upload" id="upload"><br>
<input type="submit" value="Upload" name="submit">
</form>
</body>
</html>
The code in uploads.php is:
<?php require("includes.php");
$file = get_uploaded_file($connection, $_GET["id"]);
header("Content-Type:{$file[0]}");
echo file_get_contents($file[1]);
?>
If I upload a jpeg file, a PDF or txt file then it displays in the browser as I want it to do but if I upload a word file or a MP3 then I want it to download as the normal file instead of being uploads.php
Not sure how I am going to achieve this. Can you give me some ideas as to how I do this so if I upload "demo.mp3" and I get an ID of 1 then I want it to download a file entitled "demo.mp3". Just thinking that MS Word doesn't recognise its own MIME type

Escap XSS attack and face deformation when uploading file in php

I have a form that users can upload files like html, css, php, java, js, txt, javascript and other files which i included
But my problem is how can i prevent xss attack or face deformation after successful upload
Example when user upload files like this
<input type='text'> //This will show input instead of in plain text
body{display:none!important;} // My document body off
So i tried to make this php script, it worked very fine while viewing in my site but when i try to open the file in my notepadd++ i don't like the look can anyone suggest me how i can do this better outside my code or fix mine
<?php
session_start();
if(!class_exists('DBController')){ require_once("../../_inc/dbcontroller.php"); }
if(isset($_FILES['fileuploader'])){
include_once('../fileextension.php');
$test = true;
$FileName = $_FILES['fileuploader']['name'];
$tmp_name = $_FILES['fileuploader']['tmp_name'];
$uploadPath = __DIR__ . '/'.$FileName;
$currentBas = '';
$defaultProjecName = '';
$exetype = pathinfo($FileName, PATHINFO_EXTENSION);
$extension = strtolower($exetype);
if(in_array($extension,$afile)){
$FTypeof = 'file';
}
else if(in_array($extension,$aimg)){
$FTypeof = 'image';
}
else{
$FTypeof = 'unknown';
}
$FDiscripT = 'No available '.($FTypeof == 'unknown') ? '' : $FTypeof.' discription';
//Here i move the selected file in a directory
$moveResult = move_uploaded_file($tmp_name, $uploadPath);
if ($moveResult != true) {
unlink($uploadPath);
}else{
// If file was moved then open file and get the content
if(file_exists($uploadPath)){
$fileUploadname = $uploadPath;
$filechecker = fopen($fileUploadname, "a+");
$mesure = filesize($fileUploadname);
if($mesure == 0){
$sizechecker = 1;
}
else{
$sizechecker = filesize($fileUploadname);
}
$get_content_file = fread($filechecker, $sizechecker);
fclose($filechecker);
//Then here i use htmlentities to encote the file content
if(!empty($get_content_file)){
$sanitize_file = htmlentities($get_content_file);
$sanitize_file_status = true;
}
if($sanitize_file_status == true){
//Now i put the content back the the file
try{
$openForWrite = fopen($uploadPath, 'w');
$recreateNewfile = fwrite($openForWrite, $sanitize_file);
fclose($openForWrite);
if($recreateNewfile){
//Then insert the other information to database
if($test == false){
$makefile_db = new DBController();
$makefile_db->prepare("INSERT INTO jailorgchild(jailowner,jailchildbasname,prodefault,jailchillink,jailchilddate,filediscription,contentType)
VALUES(:jailowner,:jailchildbasname,:SubDif,:jailchillink,:jailchilddate,:FDiscripT,:contentType)");
$makefile_db->bind(':jailchildbasname', $currentBas);
$makefile_db->bind(':SubDif', $defaultProjecName);
$makefile_db->bind(':jailchillink', $FileName);
$makefile_db->bind(':jailowner', $_SESSION['username']);
$makefile_db->bind(':jailchilddate', date('Y-m-d H:i:s'));
$makefile_db->bind(':FDiscripT', $FDiscripT);
$makefile_db->bind(':contentType', $FTypeof);
$makefile_db->execute();
$filewasmake = $makefile_db->rowCount();
$makefile_db->free();
}
echo '<pre>';
echo $sanitize_file;
//echo 'Unclean Content <br/>'. $get_content_file;
}
}catch(PDOException $e){
echo "Error:" . $e->getMessage();
}
}else{
unlink($uploadPath);
}
}
}
}
?>
HTML FORM
<form method="post" action="testuploader.php" enctype="multipart/form-data">
<input type="file" name="fileuploader">
<input type="submit" value="load">
</form>
OUTPUT IN NOTEPAD++
<?php if(isset($_GET['postid'])){ echo '<h5 style="color:
#2f2f2f;">Related Articles</h5><br/>'; <?php } }?>
So if another user download it and the file look like that i don't think is good please i need help

Append URL to filename before uploading to database in PHP

I am trying to add a URL to a image file name before uploading it to database. It seems that nothing worked out. Have searched Google and Stackoverflow. I guess I am missing something. Here's my code, please find the comment 'here is the issue'
I have a variable $value which pulls latest ID from database.
All I have to achieve is add path to the variable: "http://example.com/location/something/"
Desired Output : the image should be renamed as http://example.com/location/something/1.jpg
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$title = $_POST['title'];
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$folder="uploads/";
function execute_scalar($sql,$def="") {
$rs = mysql_query($sql) or die("bad query");
if (mysql_num_rows($rs)) {
$r = mysql_fetch_row($rs);
mysql_free_result($rs);
return $r[0];
mysql_free_result($rs);
}
return $def;
}
$value = execute_scalar("select max(ID)+1 from tablename");
$newname = "$value.".$ext; // Here is the issue.
$newname = "http://example.com/location/something/"."$value.".$ext; //did not work
$newname = "http://example.com/location/something/ $value.".$ext; //did not work
// even tried assingning url to variable still did not worked
if(move_uploaded_file($file_loc,$folder.$newname))
{
$sql="INSERT INTO tablename(id,title,image)VALUES('$value','$title','$newname')";
mysql_query($sql);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
is it something with URL?
Try moving your quotes like below:
$newname = "http://example.com/location/something/". $value ."." . $ext;
The problem is that you are not allowed to use / (slash) in your file name, because it acts as directory path.
I found a solution :
$newname = "http:\\//www.example.com\/location\/something\/\/$value.".$ext;
It is working :D

Categories