Please assist me. See code below. I am adding data to my phpword document, using a template processor, and creating a new document. I have just resolved the adding text issue, as the data in the clone block was being duplicated throughout. But now I am having the same issue with images.
My observations.
My file path is media\123456789.jpg (as an example), but I notice to troubleshoot I instead said setvalue instead of setimage, to see if it gets the file name correct. But it adds media3456789.jpg. So it leaves out the backslash and the following 2 characters. But I don't think this is the root cause. My point below describes why.
It adds the first clone block/ loop interaction images fine.....so I don't think the file name is a problem....by the way. If I setvalue the file name, it displays the correct name in the word document, although the name is truncated, the ending of the file name is correct, so why question why isn't it populating the block with the correct image instead of duplicating the first set of images.
$group_key=1;
do {
//echo "";
$repeatgroup = $id."/"."trailer_repeat_group"."[".$group_key."]";
//echo "repeatgroup before query___ ".$repeatgroup;
//echo "";
// inserting data from trailer table
$trailer_repeat_grouping = mysqli_query($connect, "SELECT * FROM trailer_repeat_group LEFT JOIN odkmain on trailer_repeat_group.PARENT_KEY = odkmain.metainstanceID WHERE trailer_repeat_group.KEY_id = '$repeatgroup'");
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
while ($row1 = mysqli_fetch_array($trailer_repeat_grouping))
{
$templateProcessor->setValue("Left_trailer_tyre_condition",$row1['Left_trailer_tyre_condition'],2);
$templateProcessor->insertImage("img:right_handtrailer_tyres_image",$row1['right_handtrailer_tyres_image'],2);
$templateProcessor->setValue("right_trailer_tyre_condition",$row1['right_trailer_tyre_condition'],2);
$templateProcessor->insertImage("img:left_handtrailer_tyres_image",$row1['left_handtrailer_tyres_image'],2);
}
//echo mysqli_num_rows($trailer_repeat_grouping);
// endwhile;
$group_key++;
} while ($group_key <= $trailer_count)
Related
I have a directory full of images (40,000 +) that I need sorted. I have designed a script to sort them into knew proper directories, however, I am having issues with the file name.
The images urls with the id they belong to are stored in a database, and I am using the database in conjunction with the script to sort the images.
My Problem:
The image url's in the database are shortened. An example of such corresponding images are like this:
dsc_0107-367.jpg
dsc_0107-367-5478-2354-0014.jpg
The first part of the filenames are the same, but the actual file contains more info. I'd like a way to move the file from the database with the known part of the file name.
I have a basic code:
<?php
$sfiles = mysqli_query($dbconn, "SELECT * FROM files WHERE gal_id = '$_GET[id']");
while($file = mysqli_fetch_assoc($sfiles)){
$folder = $file['gal_id'];
$fileToMove = $file['filename'];
$origDir = "mypath/to/dir";
$newDir = "mypath/to/new/dir/$file['gal_id']";
mkdir "$newDir";
mv "$fileToMove" "$newDir";
}
Im just confused on how to select the file based on the small part from the database.
NOTE: It's not as simple as changing the number of chars in the db, because the db was given to me from an external site thats been deleted. So this is all the data I have.
PHP can open files using the function glob() . Glob searches your server, or specified directory, for any files containing a "match" to a pattern you specify.
Using glob() like this will pull your images from a partial name.
Run this query separate from the second:
$update = mysqli($dbconn, "UPDATE files
SET filename = REPLACE(filename, '.info', ''));
filename should be the column in your database that contains the list of images. The reason we are removing the .jpg from the db columns is if your names are partial, the .jpg may not match with the given name in your directory. With it removed, we can search solely for the pattern of the name.
Build the query to select and move the folders:
$sfiles = mysqli_query($dbconn, "SELECT * FROM files");
while($file = mysqli_fetch_assoc($sfiles)){
$fileToMove = $file['filename'];
// because glob outputs the result set into an array,
// we will use foreach to run each result from the array individually.
foreach(glob("$fileToMove*") as filename){
echo "$filename <br>";
// I'm echoing this out to see that the results are being run
// one line at a time and to confirm the photo's are
// matching the pattern.
$folder = $file['gal_id'];
// pulling the id from the db of the gallery the photo belongs to.
// This will specify which folder to move the pic to.
// Replace gal_id with the name of your column.
$newDir = $_SERVER['DOCUMENT_ROOT']."/admin/wysiwyg/kcfinder/upload/images/gallery/old/".$folder;
copy($filename,$newDir."/".$filename);
// I would recommend copy rather than move.
// This will leave the original photo in its place.
// This measure is to ensure the photo made it to the new directory so you don't lose it.
// You could go back and delete the photos after if you'd prefer.
}
}
Your MySQL query is ripe for SQL Injection, and your GET statement needs to be sanitized, if I went to your page with something similar to :
pagename.php?id=' DROP TABLE; #--
this is going to end extremely badly for you.
So;
OVerall it's much better to use Prepared Statements. THere's LOTS and LOTS of data about how to use them all over SO and the wider internet. What I show below is only a stopgap measure.
$id = (int)$_GET['id'] //This forces the id value to be numeric.
$sfiles = mysqli_query($dbconn, "SELECT * FROM files WHERE gal_id = ".$id);
Also keep note of closing your ' and " quotes as your original doesn't close the array key wrapper quotes.
I never used mysqli_fetch_assoc and always used mysqli_fetch_array so will use that as it fits the same syntax :
while($file = mysqli_fetch_array($sfiles)){
$folder = $id //same thing.
$fileToMove = $file['filename'];
$origDir = "mypath/to/dir/".$fileToMove;
//This directory shold always start with Server['DOCUMENT_ROOT'].
//Please read the manual for it.
$newDir = $_SERVER['DOCUMENT_ROOT']."/mypath/to/new/dir/".$folder;
if(!is_dir($newDir)){
mkdir $newDir;
}
// Now the magic happens, copies the file to the new directory.
// Then (optionally) delete the original.
copy($origDir,$newDir."/".$fileToMove);
unlink($origDir); //removes original.
// Add a flag to your Database to know that this file has been copied,
// ideally you should resave the filepath to the correct new one.
//MySQL update saving the new filepath.
}
Read up on PHP Copy and PHP unlink.
And; please use Prepared Statements for PHP and Database interactions.!
I have code where I upload 6 images in one part of my site, that code worked fine, now, I need to update or change any image that was uploaded, I mean I need to change the image number 3 and 6, for example, so I wrote this code
$i=0;
while ($i<=5){
if (!empty($_FILES['ufile']['name'][$i]) and ($_FILES['ufile']['name'][$i]<>"")){
$path[$i] = "../slider_new/".$_FILES['ufile']['name'][$i];
$path[$i] = str_replace(' ', '_',$path[$i]);
copy($_FILES['ufile']['tmp_name'][$i], $path[$i]);
echo "Ruta :".$path[$i]."<BR/>";
echo "File Name :".$_FILES['ufile']['name'][$i]."<BR/>";
echo "este es $i ",$i;
$sql="UPDATE accommo_main_images SET name='".$_FILES['ufile']['name'][$i]."',ruta='".$path[$i]."' where num='$num'";
$res=mysqli_query($cnx,$sql);
}
$i=$i+1;
}
The idea is that check the name and when it is different to "" so..... update the image, that is the idea but I don´t know why the code update all the 6 images with the image that I selected.
What cam be the problem ?
Thank you for you help
where num='$num'";
You use a SQL statement WHERE NUM=$num. Yet, you did not set $num anywhere in the code you gave us here. Most likely you never set the value of $num. You probally ment $i.
I'm guessing you also possibly made the same mistake in your upload code (initial upload) and therefor all images have number=0.
You are now updating images which have number 0, or empty string (depending on database field type) which would match every image you have in there.
Try running this code and check the table entries.
$res = mysqli_query($cnx,"SELECT num,name FROM accommo_main_images");
var_dump(mysqli_fetch_all($res,MYSQLI_ASSOC));
I have a simple php code which loads an external XML file and loads the pictures URL's into my database.
Then I take the URL's and display them on my site.
The problem is that I end up loading pictures from other websites on my site, which affect loading time - loading 20 pictures per page now.
So I am thinking, Is there a way to store the image completely into my database, instead of just the URL?
Here is the code:
$myfeed = 'xmlfeed.xml';
$myfeed_xml = simplexml_load_file($myfeed);
foreach($myfeed_xml->info as $myinfo){
$pic0 = $myinfo->picture_url[0];
$pic1 = $myinfo->picture_url[1];
$pic2 = $myinfo->picture_url[2];
$pic3 = $myinfo->picture_url[3];
$pic4 = $myinfo->picture_url[4];
if($pic0 != ''){
mysql_query("INSERT INTO ".$table." (pic0, pic1, pic2, pic3, pic4) VALUES ('$pic0', '$pic1', '$pic2', '$pic3', '$pic4')", $dbh);
}
}
Thank you!
Why not download them all on your server, and update the DB with the links from your server? As long as copyright policie(s) are okay with it...
// do your DB fetching here
//loop through all current db links
foreach($sqlResult as $result)
{
// build up file path to store newly downloaded image
$fPath="someFolder/pictures/";
// get/generate a name for the pics (I'll just use a radom number here, but you should avoid doing so if you are working with lots of urls as dups may happen)
$iName=mt_rand();
//join path and url together
$pAndURL=$fPath.$iName;
// get and put data
file_put_contents($pAndURL,file_get_contents($result['collumnWhereURLIsStored']);
//now update your DB with the new link ($pAndURL)
}//end of foreach
So what the code above does is simply goes through all the 3rd party links in your DB and downloads their content (images) to your server. Then you can simply update the DB with your own link to the specific image. Simple. But as I previously mentioned, check copyright licenses first as I'm sure you don't want to be getting into trouble now, hm?
I use a form where i have listed the data from database like title, date etc. from the database and using checkboxes i use the multiple delete operation
For example my code look like this
<form method="post" action="action.php">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['id']; ?>"/>
<input name="delete" type="submit" id="delete" value="Delete"/>
and in the action.php the code is like this
$checkbox = $_POST['checkbox'];
//count the number of selected checkboxes in an array
$count = count($checkbox);
//Create a for loop to delete
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM news WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
Now the table i want to delete actually have 5 table entities like title, timestamp,pic_title,pic_brief,pic_detail the last three entities i.e pic_title, pic_brief and pic_detail is actually storing the path of the image for example the value stored in one of the 3 entity would look like this upload/file/pic_title1.jpg
My problem is when i run my first for loop it successfully deletes the table without any problem but the file which exist in the file directory remains intact. i want to delete that file too, to remove that file i thought of adding another for loop which i did something like this
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT news.pic_title, news.pic_brief, news.pic_detail FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_detail']);
}
The above code is unable to delete the requested file, my Query string is perfectly working fine i tested it by removing the unlink function and printing the values, it prints all the selected value , but it is refusing to delete the file and when i try to run the loop it shows error in the last three line, while i am pretty sure that, $row['pic_title'], $row['pic_brief'], $row['pic_brief'], have the full path of the image.
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_brief']);
where i am going wrong?
P.S: There is nothing wrong with file permission because when i individually try to run the function unlink it deletes the file from the same directory.
EDIT : This is the error message i get
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 580
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 581
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 582
To be more precise i tested this function individually in php and it is working perfectly fine
$target = 'upload/file/file1.jpg';
unlink($target);
and for this reason i dont think the file permission is causing the error, i guess i am going wrong somewhere with the logic.
#Lekensteyn got me the solution, thank you Lekensteyn.
actually i had to first hold the value in a variable and then unlink the file. the working code looks like this.
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT * FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic_title = $row['pic_title'];
$pic_brief = $row['pic_brief'];
$pic_detail = $row['pic_detail'];
unlink($pic_title);
unlink($pic_brief);
unlink($pic_detail);
}
It could be file permissions. You need to be the owner of the file in order to delete it.
Some hosters run the website under the user 'apache' (or similar), but the files are owned by the ftpuser (accountxxxx for example).
Check the current working dir too, with echo getcwd() if the paths not absolute.
Your script is vulnerable to SQL injection too, a post request with checkbox[]='||1||' deletes everything.
Add
error_reporting(E_ALL);
at the top of your script.
Your problem is program flow related and can be found only by using debugging.
Start from displaying ALL errors occurred and repair them. This will most likely lead you to the reason you could not delete your files.
Probably your path to upload is the problem. In your test script:
$target = 'upload/file/file1.jpg';
unlink($target);
I bet you ran that from a directory right below 'upload/' right?
And this delete script, it's probably not in the same directory?
I recommend using the full path to the 'upload/file/' directory; this will vary depending on your configuration, but probably looks like /www/htdocs/upload/file or /var/www/public_html/upload/file.
To make the script more transportable, you can use the PHP constant FILE to figure out the directory. I usually set this app/site wide in a bootstrap or universal configuration file, along the lines of
define('PATH', dirname(__FILE__)); # sets PATH with the directory name of the bootstrap file where this code lives
I sometimes key on something in my path I can rely on, say my app name. Say my bootstrap is here:
/www/apps/golf-scorecard/bootstrap.php
I might split on 'golf-scorecard'.
list($path,) = explode('golf-scorecard',dirname(__FILE__)); # $path should be /www/apps/
define('PATH', $path.'golf-scorecard'); # since I split on it, I have to add it back in
This means if I move the app/site to another server, or clone it from a repository onto a machine where the document root is, say /home/username/apps/golf-scorecard/htdocs/, then it won't matter. It does couple the app name but I am okay with that.
first thing is you need to check the file permissions .you need to give 777 permission to the folder.and then follow below code
$target = 'upload/file/file1.jpg';
unlink($target);
I think I know the answer for this question allready, but just as curious I am, I'll ask it anyways.
I'm running a webshop which products come with a csv file. I can import all the objectsng without any trouble, the only thing is that images and thumbnail locations are not exported with the the database dump. (it's never perfect heh) You might say, do it manually then, that's what I did in the first place, but after 200 products and RSI, I gave it up and looked for a better more efficient way to do this.
I have asked my distributer and I can use their images for my own goals without any having copyright problems.
When I look at the location of the images, the url looks like this:
../img/i.php?type=i&file=1250757780.jpg
Does anyone have a idea how this problem can be tackled?
For scraping a website, I found this code:
<?php
function save_image($pageID) {
$base = 'http://www.gistron.com';
//use cURL functions to "open" page
//load $page as source code for target page
//Find catalog/ images on this page
preg_match_all('~catalog/([a-z0-9\.\_\-]+(\.gif|\.png|\.jpe?g))~i', $page, $matches);
/*
$matches[0] => array of image paths (as in source code)
$matches[1] => array of file names
$matches[2] => array of extensions
*/
for($i=0; $i < count($matches[0]); $i++) {
$source = $base . $matches[0][$i];
$tgt = $pageID . $matches[2][$i]; //NEW file name. ID + extension
if(copy($source, $tgt)) $success = true;
else $success = false;
}
return $success; //Rough validation. Only reports last image from source
}
//Download image from each page
for($i=1; $i<=6000; $i++) {
if(!save_image($i)) echo "Error with page $i<br>";
}
?>
For some reason it throws this error: Error with page 1, Error with page 2, etc
Well, you can either make the distributer to give you the image names in the CSV file and then you can construct the URLs directly, or you will have to scrap their website via a script and fetch the images (I'd ask them for permission before doing this).
That URL doesn't really tell you where the picture is located - only that a script i.php will be called and the file name is passed in as a parameter file on the query string.
Where the i.php script goes to actually find the image cannot be deduced from just the info you present here. You'd have to inspect the script to find out that information, me thinks.