trying to append bandname to mp3 upload using $_SESSION['bandname']; - php

Trying to append $_SESSION['bandname']; to an mp3 file upload, The concept
is when someone uploads a song it append the band name to mp3 bandname_songname.mp3 if that makes sense. here is my code so far.
the problem is with this line i think $aditionalnewFileName = $bandname.="_".$aditionofileName; this strange part is when I use the var_dump($bandname); well instead of the band name its the song I'm testing with string(88) "_police.ogg_police.ogg_police.ogg_police.ogg_police.mp3_police.mp3_police.mp3_police.wav". maybe mysqli would be more simple?
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
var_dump($_SESSION['bandname']);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution
time of this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client
//side file tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/',
'',$_FILES['song_name']['name']); // get client side file name remove
the special character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = $bandname.="_".$aditionofileName; //filename
changed with current time
if ( move_uploaded_file($aditiontmp_name,
"$uploads_dir/$aditionalnewFileName")) //Move uploadedfile
{
$uploadFile = $uploads_dir."/".$aditionalnewFileName; //Uploaded file
path
$ext = pathinfo($uploads_dir."/".$aditionalnewFileName,
PATHINFO_EXTENSION); //Get the file extesion.
$uploadFilebasename = basename($uploads_dir."/".$aditionalnewFileName,
".".$ext); //Get the basename of the file without extesion.
$exName = ".mp3";
$finalFile = $uploads_dir."/".$uploadFilebasename.$exName; //Uploaded
file name changed with extesion .mp3
$encode_cmd = "/usr/bin/ffmpeg -i $uploadFile -b:a 256000 $finalFile
2>&1"; // -i means input file -b:a means bitrate 2>&1 is use for debug
command.
exec($encode_cmd,$output); //Execute an external program.
echo "<pre>";
// will echo success , for debugging we can uncomment echo
print_r($output);
// also want to add redirect to this script to send back to profile
after upload
echo "The file was uploaded";
//echo print_r($output); // Report of command excution process.
echo "</pre>";
if($ext !== 'mp3'){ // If the uploaded file mp3 which is not remove
from uploaded directory because we need to convert in to .mp3
unlink( $uploadFile );
}
//0644 vs 0777
chmod( $finalFile, 0777 ); // Set uploaded file the permission.
}
else
{
echo "Uploading failed"; //If uploding failed.
}
?>

so after a while, I decided to go about it a different way. I used mysqli,i quarried the user name and bandname, then used the while loop used var_dump noticed bandname after staring at my code i saw i was editing the wrong line so i change $aditionofileName = preg_replace('/[^A-Za-z0-9-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); and change the line i thought was the problem to $aditionalnewFileName = "_".$aditionofileName; revmoed variable and removed the .
new code below.
<?php
session_start();
if (isset ($_SESSION ['band_id' ]))
{
$band_id = $_SESSION ['band_id' ];
$bandname = $_SESSION ['bandname' ];
$username = $_SESSION ['username' ];
}
if (isset ($_GET ['band_id']))
{ // Yes
$showband = $_GET ['band_id'];
}
else
{ // No
echo "ID not set"; // Just show the member
}
include 'connect.php';
$sql = "SELECT * from members WHERE band_id=$showband";
$result = mysqli_query ($dbhandle, $sql);
while ($row = mysqli_fetch_array ($result))
{
$username = $row ["username" ];
$bandname = $row ["bandname" ];
}
var_dump($bandname);
ini_set( "max_execution_time", "3600" ); // sets the maximum execution time of
this script to 1 hour.
$uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/mp3';
$aditiontmp_name = $_FILES['song_name']['tmp_name']; // get client side file
tmp_name
// '/[^A-Za-z0-9\-_\'.]/', '' //$_FILES['song_name']['name']);
$aditionofileName = preg_replace('/[^A-Za-z0-9\-_\'.]/', '',$bandname .
$_FILES['song_name']['name']); // get client side file name remove the special
character with preg_replace function.
// remove time() to edit name of mp3
$aditionalnewFileName = "_".$aditionofileName; //filename changed with current
time

Related

Cannot find file path (invalid url)

I have problem to find file path. I have a form that can insert file or image.
Below code shows how the file or images save
if($_FILES["lampiran"]["name"][$i] != "")
{
$my_folder = "./files";
$location = $my_folder.'/'.$pname;
$imageFileType = pathinfo($tname,PATHINFO_EXTENSION);
move_uploaded_file($tname,$location);
$query2 = "INSERT into list_lampiran (id_aduan, folder, lampiran, nama_asal, type, size, time_create) VALUES ('$id_aduan', '$my_folder', '$location', '$pname', '$file_type', '$file_size', '$time_create')";
mysqli_query($con, $query2);
$id_lampiran=mysqli_insert_id($con);
if($query2){
$myfile_rename = $id_lampiran.'_'.$pname;
rename($location, './files/'.$myfile_rename);
$query3 ="UPDATE list_lampiran SET lampiran = '$myfile_rename' WHERE id = '$id_lampiran'";
mysqli_query($con,$query3);
}
}
Then the file or image will sent through an email and appear as a link. But the link have invalid URL
Code to display the file or image in email
if(mysqli_num_rows($resultlampiran) > 0){
$rowlampiran = mysqli_fetch_array($resultlampiran,
MYSQLI_ASSOC);
$folder_name = $rowlampiran['folder'];
$lampiran = $rowlampiran['lampiran'];
$lampiran1 = $folder_name.'/'.$lampiran;
$nama_asal = $rowlampiran['nama_asal'];
$file = "<ul><li><a href='".$lampiran1."'>".$nama_asal."</a></li></ul>"; }
Redirect notice
You missed to include the URL of your website in the file link. You need to update the file path in your email template or so as:
$website = "https://example.com/";
$file = "<ul><li><a href='".$website.$lampiran1."'>".$nama_asal."</a></li</ul>";
and you're good to go :)
Also, you have coded without caring about the security of your application. Anyone could easy upload backdoor or any other PHP
scripts and destroy all the data and files on your server. You must
validate file extension and then save to your database
Example:
$validExt = array("jpg", "png", "pdf", "txt"); // valid extensions that should only be allowed.
// and then check if upload file's extension matches in our valid list
if(in_array(strtolower($imageFileType), $validExt) === false) {
// some other file extension found, show error message
} else {
// upload your file here and save to database
}
This is your file url
$location = "www.sitename.com/". $my_folder.'/'.$pname;
echo $location;

Using move_uploaded_file To Rename File BEFORE Being Placed In uploads/ Folder

I've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;

Make all uploaded files force download in php

I found a simple script on internet on how to upload files in php.
<?php
require 'config.php';
if (isset ( $_SERVER ['REQUEST_METHOD'] ) == 'POST') {
// when submit button is clicked
if (isset ( $_POST ['submit'] )) {
// get user's data
$name = $_POST ['name'];
$email = $_POST ['email'];
$images = "";
// check if user has added images
if(strlen(($_FILES ['upload'] ['tmp_name'] [0])) != 0){
$upload_dir = "images/";
// move all uploaded images in directory
for ($i = 0; $i < count($_FILES['upload']['name']); $i++) {
$ext = substr(strrchr($_FILES['upload']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
$images .= $fPath.";";
$result = move_uploaded_file($_FILES['upload']['tmp_name'][$i], $upload_dir . $fPath);
}
}else {
// if user doesn't have any images, add default value
$images .= "no images";
}
// write the user's data in database
// prepare the query
$query = "INSERT INTO users(name, email,images) VALUES
('$name', '$email','$images')";
// TODO check if the user's informations are successfully added
// in the database
$result = mysql_query ( $query );
}
}
?>
This script does a really good job overall but the only problem is that when I upload image files or pdf they open up in a new tab, they do not download. How do I make the uploaded image files automatically download when the download link is clicked on? Thanks in advance.
Add the download link as follows
<a href="link/to/your/download/image" download>Download link</a>
Add the following code in apache config
<Location "/images">
<Files *.*>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
</Location>

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

PHP - Renaming a file to disallow duplicates

So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help

Categories