php replace string and read full string - php

i am trying to achieve this. I have alot of HTMLs that looks somethinglike this (for example).
<div>
<img src="http://firstsite.com/path/to/img/main.jpg" style="width: 500px; height: 400px;" />
</div>
Now i try to make a php that automatically changes the path of the images to another website, but i also want to download the images and put them into same folder structure. So far i did this:
$input = "c:/wamp/www/primo/input12";
$output = "c:/wamp/www/primo/output12";
$handle = opendir($input);
while (($file = readdir($handle)) !== false) {
if($file != '.' && $file != '..') {
$data = file_get_contents($input . "/" . $file);
$data = str_replace("http://firstsite.com/", "http://secondsite.com", $data);
file_put_contents($output . "/" . $file, $data);
}
}
closedir($handle);
This changes the path but now i need to somehow get into a variable the full path http://firstsite.com/path/to/img/main.jpg in my example in order to download the image.
Is there a way to get the full path of the images while replacing http://firstsite.com/ which is just the begining of the path ?
Thank you in advance, Daniel!

Get only images:
$data = file_get_contents($input . "/" . $file);
preg_match_all('/\<img.*src=\"(.+?)\"/s', $data, $matches);
//go through the match array and download your files
$data = str_replace("http://firstsite.com/", "http://secondsite.com", $data);
file_put_contents($output . "/" . $file, $data);
Get all pathes:
$data = file_get_contents($input . "/" . $file);
preg_match_all('/http\:\/\/firstsite\.com([^\s]+?)/s', $data, $matches);
//go through the match array and download your files
$data = str_replace("http://firstsite.com/", "http://secondsite.com", $data);
file_put_contents($output . "/" . $file, $data);

How about:
preg_match_all('/(http:\/\/firstsite\.com\/[^\s]*)/', $data, $matches);

Related

Php copy : Invalid argument error only on inside while loop and working for last record

Reading the file for the image url and calling the copy function.
imagecopy.txt
https://server.com/2017/12/check.png
https://server.com/2017/12/contacts.png
https://server.com/2018/06/CDP.bmp
https://server.com/module-acculturation-1.png
While copying the files from the url, getting the failed to open stream: Invalid argument error only on inside while loop. but works for the last record if the file has more files.
<?php
$file=fopen("imagecopy.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
$source = fgets($file);
$imagename = explode("/", $source);
$pathname = 'uploads/' . date("Y") . '/' . date("m") . '/';
if (!is_dir($pathname))
{
mkdir($pathname, 0777, true);
}
$destination = $pathname.end($imagename);
copyimageURL($source, $destination);
}
fclose($file);
function copyimageURL($source, $destination)
{
echo $source;
echo "<br>";
echo $destination;
copy($source, $destination);
}
?>
1.Working fine with singe record
2.Copying the last image only if the file has more images list.
I'm guessing imagecopy.txt you're reading ends in a newline, which makes the last line of the file blank.
If you change
$source = fgets($file);
to
$source = trim(fgets($file));
if( empty($source) ) continue;
it should work fine
Try this:
if ($file) {
while (($name = fgets($file)) !== false) {
$imagename = basename($name);
$pathname = 'uploads/' . date("Y") . '/' . date("m") . '/';
if (!is_dir($pathname))
mkdir($pathname, 0777, true);
$destination = $pathname.$imagename;
copyimageURL(trim($name), $destination);
}
fclose($file);
}

Bulk renaming using regex in Php

I have a folder in a server with a lot of images and I would like to rename some images. Images that contain (1 example:
112345(1.jpg to 112345.jpg. How can I do this using regex in PHP? I have to mention that my knowledge of PHP is very limited and it's the only language that can effectively do the scripting.
preg_match('/\(1/', $entry) will help you.
Also, you need to pay attention to "what if the file has a duplicate after the rename".
$directory = "/path/to/images";
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != '.' && $entry != '..') {
// Check "(1"
if (preg_match('/\(1/', $entry)) {
// Rename file
$old = $directory . '/' . $entry;
$new = str_replace('(1', '', $old);
// Check duplicate
if (file_exists($new)) {
$extension = strrpos($new, '.');
$new = substr($new, 0, $extension) . rand() . substr($new, $extension); // Basic rand()
}
rename($old, $new);
}
}
}
closedir($handle);
}
If you want only remove some substring from images names you can do this without regex. Use str_replace function to replace substring to empty string.
As example:
$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
You can use scandir and preg_grep to filter out the files that needs to be renamed.
$allfiles = scandir("folder"); // replace with folder with jpg files
$filesToRename = preg_grep("/\(1\.jpg/i", $allfiles);
Foreach($filesToRename as $file){
Echo $file . " " . Var_export(rename($file, str_replace("(1.", ".", $file));
}
This is untested code and in theory it should echo the filename and true/false if the rename worked or not.
Only use regex for this if you need to assert the position of the substring, e.g. if you have filenames like Copy (1)(1.23(1.jpg a simple string replacement will go wrong.
$re = '/^(.+)\(1(\.[^\\\\]+)$/';
$subst = '$1$2';
$directory = '/my/root/folder';
if ($handle = opendir($directory )) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace($re, $subst, $fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
The regular expression used searches for the part before and after the file extension, put the pieces into capturing groups, and glue them together again in the preg_replace without the (1.

Adding an image to a JSON WebService -PHP

Is there any way that I can send images via my JSON Webservice?
Here is my code which looks for new images in a specific folder and return some data including (path, id which is the name of image file and the creation time of the file):
function getAllNewPhotos($lastCHK) {
$dirPath = 'c:\my_images';
$files1 = scandir($dirPath);
$files = array_diff($files1, array('.', '..'));
$newFiles = array();
foreach ($files as $file) {
$createTime = filectime($dirPath . '/' . $file);
$path_data = pathinfo($dirPath . '/' . $file);
if ($createTime > $lastCHK) {
$newFiles[] = array(
'path' => $dirPath . '\\' . $file,
'ID' => $path_data['filename'],
'dateImagAdded' => date('Y-m-d H:i:s', $createTime),
);
}
}
return ($newFiles);
}
Is there any way to send the real image along with the other data which I have already passed?
If you need more clarification, please let me know which part you need more clarification.
Thanks
You can use base64 to encode your image
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

How to get all files containing substring

Can somebody help me? I have many pictures with current name like : "black_abc","black_bcd","black_cde","white_abc". How can I get only file with filename contains "Black"?
glob will help you find all files containing "Black" in their filename:
$folder = "images"; //the folder containing all your images
$pattern = "*Black*"; //the word you are looking for
$files = glob($folder. '/' . $pattern, GLOB_BRACE);
foreach($files as $filename) {
//Display all pictures
echo "<img src='"$folder . "/" . $filename . "' />";
}
strpos($filename, 'black') !== false
Something like this [Make use of stripos() [Case-Insensitive]
<?php
$files=array("black_1","white_2","black_3");
for($i=0;$i<count($files);$i++)
{
if(stripos($files[i],'black'))
{
echo "Filename is $files[$i]";
}
}

PHP copy image from url to server and echo the final url

I am trying to write a code that will copy an image from URL to a relative path on my server with a random file name and echo back the final url.
I have 2 problems:
It doesn't work with relative path. If I don't declare the path, the function works but the image is being saved on the same folder of the PHP file. If I do specify the folder, it doesn't return any error but I don't see the image on my server.
The echo function always return an empty string.
I am a client side programer so PHP is not my thing... I would appreciate any help.
Here is the code:
<?php
$url = $_POST['url'];
$dir = 'facebook/';
$newUrl;
copy($url, $dir . get_file_name($url));
echo $dir . $newUrl;
function get_file_name($copyurl) {
$ext = pathinfo($copyurl, PATHINFO_EXTENSION);
$newName = substr(md5(rand()), 0, 10) . '.' . $ext;
$newUrl = $newName;
return $newName;
}
EDIT:
Here is the fixed code if anyone is interested:
<?php
$url = $_POST['url'];
$dir = 'facebook/';
$newUrl = "";
$newUrl = $dir . generate_file_name($url);
$content = file_get_contents($url);
$fp = fopen($newUrl, "w");
fwrite($fp, $content);
fclose($fp);
echo $newUrl;
function generate_file_name($copyurl) {
$ext = pathinfo($copyurl, PATHINFO_EXTENSION);
$newName = substr(md5(rand()), 0, 10) . '.' . $ext;
return $newName;
}
Answer Here
Either Use
copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.jpeg');
or
//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
You should use file_get_contents or curl to download the file. Also note that $newUrl inside your function is local and this assignment doesn't alter the value of global $newUrl variable, so you can't see it outside your function. And the statement $newUrl; in 3rd line doesn't make any sense.

Categories