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
Related
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
I want to allow users to upload images without conflicting problems that may be caused by multiple users uploading images that potentially have the same image name. I am stumped on how to execute this and I have no idea where to start..
Here is my code:
if(isset($_POST['submitimage'])){
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$_FILES['file']['name']);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Any help would be amazing. Thank you!
My solution is to generate a random string for each uploaded file, i.e.:
<?php
if(!empty($_POST['submitimage'])){
//get file extension.
$ext = pathinfo($_FILES['file']['name'])['extension'];
//generate the new random string for filename and append extension.
$nFn = generateRandomString().".$ext";
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
}
function generateRandomString($length = 10) {
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
}
?>
PHP has a build in function to generate unique files on your server. This function is known as tempnam(). If you read the comments on that website carefully though, there is a small chance you'll get unwanted behaviour from that function if to many processes call it at the same time. So a modification to this function would be as follows:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
?>
Because the file is kept open while it's being created, it can't be accessed by another process and therefor it's impossible to ever create 2 files with the same name simply because a couple of your website visitors happened to upload pictures at the exact same moment. So to implement this in your own code:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
$uploaddir = 'pictures'; // Upload directory
$file = $_FILES['file']['name']; // Original file
$ext = pathinfo($path, PATHINFO_EXTENSION); // Get file extension
$uploadfile = tempnam_sfx($uploaddir, $ext);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".basename($uploadfile)."' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
?>
One way you could do this, is by generating a few random numbers (and possibly attaching them to current date in number format) and give the image the number sequence.
if(isset($_POST['submitimage'])){
//generate 3 sequences of random numbers,you could do more or less if you wish
$randomNumber=rand().rand().rand();
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$randomNumber."jpg");
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$randomNumber.".jpg' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Note : you could also look into generating random strings if numbers are not your thing.
I am trying to upload Excel file using PHP. I am using WAMP server and written PHP code to upload Excel file in the same folder.
I have saved an Excel file so if I upload the saved file then it works fine but if I try to upload another Excel file from different location i.e. from desktop it is showing that abc.xls is not readable.
My code is as follows:
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
require_once 'db.php';
if(isset($_POST["btnImport"]))
{
if(!empty($_FILES["excelFile"]["tmp_name"]))
{
$fileupload = $_FILES["excelFile"]["name"];
$fileName = explode(".",$_FILES["excelFile"]["name"]);
if($fileName[1]=="xls"||$fileName[1]=="xlsx")
{
$data = new Spreadsheet_Excel_Reader($fileupload);
//echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count(#$data->sheets[$i]['cells'])>0) // checking sheet not empty
{
// echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
#$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
#$data->sheets[$i]['cells'][$j][1];
#$ques = mysql_real_escape_string($data->sheets[$i]['cells'][$j][1]);
$opt1 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][2]);
$opt2 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][3]);
$opt3 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][4]);
#$opt4 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][5]);
#$correct = mysql_real_escape_string($data->sheets[$i]['cells'][$j][6]);
#$Level = mysql_real_escape_string($data->sheets[$i]['cells'][$j][7]);
#$Category = mysql_real_escape_string($data->sheets[$i]['cells'][$j][8]);
#$explain = mysql_real_escape_string($data->sheets[$i]['cells'][$j][9]);
$nithi = "INSERT INTO `question` VALUES (NULL,'".$ques."','".$opt1."','".$opt2."','".$opt3."','".$opt4."','".$correct."','".$Level."','".$Category."','".$explain."')";
if (!mysql_query($nithi,$connection))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
}
}
}}}}
if(#$result){
echo "Questions uploaded successfully";
}
?>
How can I upload Excel file from different location?
When a file is uploaded in PHP, it is put into temp folders.
In your code, there is no call for moving the uploaded file from temporary location into the desired one. Instead you are only checking $_FILES["excelFile"]["tmp_name"] and then directly using $_FILES["excelFile"]["name"] which is obviously incorrect.
Use move_uploaded_file() function to move the file, see the docs: http://php.net/move_uploaded_file
Having big time problems in displaying an image out of my mysql database
I'm storing it in a longblob type
when the image is displayed i get a broken image icon
here is code for storing image
if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
//temporary file name
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
$imageType = $_FILES['image']['type'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
VALUES
('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";
//For debugging purposes
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Your Image has been Added";
}
}
then printing the image
if(isset($_POST['usersImage'])){
//code to show images
$user = $_POST['usersImage'];
$sql = "SELECT * FROM `photos` WHERE userName = '$user'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
switch ($row['photoType']) {
case 'image/jpeg':
echo "<tr>";
echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";
echo "</tr>";
//echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
//echo '<p id="caption">'.$row['caption'].' </p>';
break;
}
}
}
as you can see my latest attempt was to use base64 encoding to print out the image
my previous try was the commented out code
When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.
<?php
$photo_bin = //binary data from query here;
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $photo_bin;
Quick example^ of a php script that can be requested by the browser from an img tag.
Validation is important. You are opening yourself up to so many security issues.
Never use $_POST / $_GET inside a sql statement. Escape them, better yet, use PDO statements. Validate that the image is actually an image, at this point, you could be entering any type of file into your table.
As you're finding, it's also far more difficult to store images in a database than on the filesystem. Usually, there are far more arguments to store the image on the filesystem than inside a table.
Having a quick look down your insertion code, I'm not quite sure why you're adding slashes to the binary data. remove the call to addslahes, and try that.
I wrote a PHP script to delete files selected in a gridview. This is the first time I've done this. The script works fine on my local development machine but I don't know if this is the proper way to do it. I'd like to find out what possible problems can I run into when deleting files and how can I modify this to prevent problems.
I was looking at this page to get the basic idea: http://www.php.net/manual/en/function.unlink.php
<?php
// get required includes
require_once(ROOT_PATH.'user/controls/snippets/error_messages.php');
require_once(ROOT_PATH.'user/controls/accordion/get_user_name.php');
// ------------------------------------------------------------
// DELETE SELECTED FILES
// ------------------------------------------------------------
if(isset($_POST['delete_file']) && isset($_POST['checked2']))
{
$checked = array_map('intval',$_POST['checked2']);
$delete_list = implode(", ", $checked);
// DB: get file names to delete
$get_file_names = mysqli_query($conn, "SELECT FileName FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
or die($dataaccess_error);
// delete files from server
while($row = mysqli_fetch_array($get_file_names))
{
$dir = DOWNLOAD_DIRECTORY;
$file_name = $row['FileName'];
$file_to_delete = $dir.$file_name;
unlink($file_to_delete);
}
// DB: delete selected file references from db
$delete_selected = mysqli_query($conn, "DELETE FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
or die($dataaccess_error);
if(mysqli_affected_rows($conn) > 0)
{
$effected_rows = mysqli_affected_rows($conn);
echo "<div class='msgBox2b noBorder'>SUCCESS: ($effected_rows) FILE(S) have been DELETED..</div>";
}
}
elseif(isset($_POST['delete_file']) && !isset($_POST['checked2']))
{
echo $msg_error;
}
?>
Thank you!
Edit: Would it be better this way?
$fh = fopen($file_to_delete, 'w') or die($failed_to_open_file);
fclose($fh);
unlink($file_to_delete);
Not all files can be unlinked because of permissions, so check the return value of that call.