Hi I have created a script to download images and to rename from a url. The links and name are stored in a database. The database looks like this:-
id name url
1 abcd http://www.abcd.com/a.jpeg
I am running a following script to download and renaming the images.:-
$sql = "SELECT * FROM data";
$results = $gtl->query($sql);
while($row = $results->fetch_assoc()) {
$n = $row['name'];
$url = $row['url'];
$name = $n.'.jpeg';
$path = "images/";
if ($url != NULL) {
$get_image = file_get_contents($url);
if ($http_response_header != NULL) {
$get_file = $path . $name;
file_put_contents($get_file, $get_image);
}
}
The following code works well but consumes a lot of time. I have tried using cURL but it has similar speed. Since there are over 300 images that needs to be downloaded. It would be a great if anyone can suggest a way to fasten the process. Any help is highly appreciated.
Related
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 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
I'm working on a mobile application, and I'm handling database and APIs.
Android developer is sending me images and I'm using file function to get its data.
I have written this code:
public function addalbum($baseurl)
{
$images = array();
if(isset($_FILES['image'])){
//echo "hellow";exit;
//$pathToUpload = '../media/gallary/';
$count = count($_FILES['image']['name']);
//echo $count;exit;
$imagepaths = '';
$imagetepaths = '';
$images = '';
for($i=0;$i<$count;$i++){
$imageurls[$i] = $baseurl."../media/gallary/".$_FILES['image']['name'];
$imagepaths = '../media/gallary/'.$_FILES['image']['name'][$i];
$images[$i] = $_FILES['image']['name'][$i];
$imagetepaths = $_FILES['image']['tmp_name'][$i];
move_uploaded_file($imagetepaths , $imagepaths);
}
}
$data=array(
'image' => ($images != '') ? implode(',',$imageurls) : '',
'email'=>$this->input->post('email'),
'name'=>$this->input->post('name'),
'type'=>$this->input->post('type')
);
//print_r($data);exit;
$this->db->insert('album',$data);
}
But from the bunch of images, only the last one is being inserted in the database.
any help will be very much appreciated.
Thanks
$_FILES['image'] is the field name of 1 uploaded file. If multiple files should be posted you would require different names for each field. Just think how will you upload multiple files from an html form.
For example: $_FILES['image1'], $_FILES['image2'], $_FILES['image3']
You could use something like this:
if(is_array($_FILES)) {
foreach($_FILES as $fileKey => $fileVal){
if($fileVal[name]) {
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$target_path.$fileVal[name]);
}
}
}
Checkout this example where a maximum of 3 files are uploaded from android using php.
I have a folder directory set up like this in my htdocs:
claas2/TractorPics\5484474\Received\ => and then a bunch of images inside
im using php to put the picture from MySQL database where the file path is stored rather than all the pictures and so that they can be changed easily.
php:
if ( $_REQUEST['rec_pic'] ) {
$order_id = $_POST['rec_pic'];
$sql = "SELECT * FROM `orders` WHERE `active` = '1' AND `order_id` = '$order_id'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$dir = $row['rec_pic'];
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo "<div>";
echo "<a href='#'><img src='".$file."' /></a>";
echo "</div>";
}
closedir($handle);
}
}
}
When i echo this out i get an error saying that that file directory does not exist but if i were to do src it in an image it works just fine. What am i doing wrong here?
the php file that get getting the request is in the directory
claas2\db\ajax
Pretty messy path you have:
claas2/TractorPics\5484474\Recieved\
Try:
claas2\TractorPics\5484474\Recieved\
or
claas2/TractorPics/5484474/Recieved/
but do not mix separators.
EDIT
You are mixing path with URL. And it works because you are using \ as path segment separator, which your browser converts to / while sending request to webserver and your server is now Windows based I guess, therefore \ is invalid as path separator for file system on server. Do
$path = str_replace('\\', `/`, $pathFromDb);
and use result instead of data from db as you use now.
having a big trouble trying to make this blob saved to a file and load it as an image.
Using SQLite Manager (Firefox Add-on) I was able to "Save As" a file with the content of my image BLOB. The result is a strange (for me) code.
Since I can´t post the "source of the file", I'm attaching one png with the example.
In my Mac, the saved file has no extention but I can view the image it produces as thumbnail.
So I'm trying to achieve the same result saving one file, but all I get is a 16 bytes document I can't read...
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'w');
fwrite($pic, base64_encode($theFile));
fclose($pic);
* EDIT *
$theFile = shell_exec("sqlite3 AddressBookImages.sqlitedb 'select data from ABThumbnailImage where record_id = ".$id."'");
if($theFile != '') {
file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $theFile);
}
Try to use (b for binary)
$pic = fopen('pics/thumbnails/pic_'.$id.'', 'wb');
I find a solution to this, but its very slow, I'm posting a new question to ask help for improve this.
$sql2 = shell_exec("sqlite3 ".$endereco_iphone."".$db_pics." 'select hex(data) from ABThumbnailImage where record_id = ".$id."'");
//
if($sql2 !='' && $sql2 != 'NULL') {
$img = '';
foreach(explode("\n",trim(chunk_split($sql2,2))) as $h) {
$img .= chr(hexdec($h));
}
if(file_put_contents('pics/thumbnails/pic_'.$id.'.jpg', $img)) {
$cnt .= "<img class='pics' src='pics/thumbnails/pic_".$id.".jpg' width='30px' height='30px'></img>";
}
} else {
$cnt .= "<div class='pics'></div>";
}