Recently, we had a client who needed to upload hundreds of records at a time to his site via a csv file. These records would have 12 columns each. Some columns would come directly from the columns in the csv file while others had to be derived. Not that complicated really, things like google lat/lon for example would be derived from the, address, city, country, etc columns.

To The point

These records, for some reason we won’t discuss here, has an image url as one of its columns. This brings up a fairly simple situation, or so i thought. We needed the following:

  • Download the file to server
  • Upload to wordpress
  • attach to  wordpress media gallery
  • get local image url and attach it to record for saving

Now this should be incredibly easy when you consider how versatile wordpress is. Unfortunately, we found out quite quickly that the wordpress function wp_insert_attachment($attachment, $filename, $parent_post_id ) isn’t a one liner function. Actually its more like the following

$attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  );
  $attach_id = wp_insert_attachment( $attachment, $filename, 37 );

More importantly, the $filename variable “MUST be on the uploads directory.” according to the function reference.

The Search Was On

So what did we do? The same thing we do every day, run to google. Turns out, no one could give me a straight forward

answer regarding how to fix this. Not even those shady little forums … you know those you have never heard of before, never use, but hey if they have the info…. you know, kinda like this one….  (: -)~

Well, we here at Beyond Programs like to go brute force when things get tough. Make a curl script. Yup! How simple was that…. UMM, unfortunately not easy enough. Maybe you out there on the world wide intertubes would have better luck than I BUT… Oh the BUT

Turns out, for me at least, that getting the image via curl returns the files contents. What am i going to do with this other than stick it into a file? You know

if($out = fopen($local_file, ‘c’))
fwrite($out, trim($content));

Again another wall. Since i’m, knee deep in a plugin,  i’m surrounded by a place where the header has long been launched.

Technicalities

Lets take a closer look at the patient.  Since the headers have long been launched, i cant use this nifty trick i learnt where i simply create an image header. Yeah you know it, image header, stuff file with funky code, save file and voila.

header(‘Content-Type: image/jpeg’);
header(‘Content-Disposition: attachment; filename=’ . urlencode($filename));

Well nice little write up for nothing, seeing that again, i’m knee deep in a plugin so that’s not happening. Did i mention that we here at Beyond Programs like to go brute force when the stupid thing won’t work?

Remember earlier I mentioned creating a curl script? Well we did, tested it, and all that stuff i mentions actually works if you aren’t knee deep in wordpress. So for those of you as desperate as I for a solution, and ready to bend over backwards for a solution, i have something.

SHHHHhhhhhh

Curl to the curl script. Yeah I said it. Curl knee deep in wordpress to another place on your site (login protected ofcourse) and have that script do all the image saving etc. Boooyaaaa, i said brute force and um, may I add, it works flawlessly.

Send whatever you want to the script. Most importantly, send the file it needs to go get.

$url = … “?local_file=”.trim($local_file).”&remote_file=”.$remote_url;

$ch = curl_init(trim($check_url));

curl_exec($ch);

Your standalone script should handle the entire fetching and saving process. Your main script will finish the attachment to the wordpress gallery then get the url for the record column.

What about

What about file_get_contents you say? That would cut half this trash out. Well did I add that some of the links in the csv wern’t real? They FORWARDED to somewhere else. Also, i don’t believe it was working even without this issue, you try and let me know. Ultimately, when the stupid code stops working we get to Brute Forcing.

Conclusion

If someone asks you to get an image from some other domain and upload it to theirs, run. Bad joke maybe, but in my case, the images were all part of an advertising and listings agreement. A major network was supplying the info and the customer didn’t want to go the api route.

If you have a legit reason for fetching images and uploading them to your server/wordpress then its possible. You must hack at it but it’s possible.

I’ll have to add some actual files to this at some point seeing that it takes several lines to do all of this. However, for those of you really going down such a road, with whats explained here, you already have the code. Ok, enough jedi, at least a few lines
……………………………………………………………………………………………………………………

Main File

$remote_url = addslashes(strip_tags($arr[11]));
$raw_file = explode(“/”,$remote_url);
$filename = $uploads[‘path’].”/”.$raw_file[sizeof($raw_file)-1];//get filename
if(http_get_file($remote_url, $filename)){//if succesfully downloaded then attach to gallery

……………………………………………………………………………………………………………………

Curl to curl

function http_get_file($remote_url, $local_file)    {

$check_url = “whatever.php?local_file=”.trim($local_file).”&remote_file=”.$remote_url;

$ch = curl_init(trim($check_url));
curl_exec($ch);
……………………………………………………………………………………………………………………

Standalone

$local_file = $_GET[“local_file”];
$remote_file = $_GET[“remote_file”];
$raw_file = explode(“/”,$remote_file);
$filename = $raw_file[sizeof($raw_file)-1];
header(‘Content-Type: image/jpeg’);
header(‘Content-Disposition: attachment; filename=’ . urlencode($filename));
require(“../../../wp-load.php”);
if (is_admin()) {

Recientemente, tuvimos un cliente que necesita para cargar cientos de registros a la vez a su sitio a través de un archivo csv. Estos registros tendría 12 columnas. Algunas columnas que provienen directamente de las columnas en el archivo csv mientras que otros tuvieron que ser derivados. No es que realmente, complica las cosas, como por ejemplo google lat/lon que se deriva de la, dirección, ciudad, país, etc. de las columnas.
Hasta el punto
Estos registros, por alguna razón no comentaremos aquí, tiene una dirección url de la imagen como una de sus columnas. Esto lleva a una situación bastante simple, o por lo que pensé.Necesitamos lo siguiente:
  • Descargue el archivo en el servidor
  • Subir a wordpress
  • adjuntar a la Galería de medios de wordpress
  • obtener url de imagen local y adjuntarlo a grabar para guardar
Ahora deben ser increíblemente fácil cuando se considera cómo versátil wordpress es.Lamentablemente, descubrimos rápidamente que la wp_insert_attachment de función de wordpress ($adjunto, $nombre_archivo, $parent_post_id ) no es una función de un Botin. En realidad sus más parecido a lo siguiente
$attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  );
  $attach_id = wp_insert_attachment( $attachment, $filename, 37 );
Más importante aún, la variable $filename “debe ser en el directorio de cargas.” segun la referencia de función.
La búsqueda fue en
¿Así que lo que hacemos? Lo mismo que hacemos todos los días, ejecutar a google. Se vuelve, nadie pudo darme una respuesta directa acerca de cómo solucionar este problema. Ni esos sombríos poco foros… saben aquellos que nunca ha escuchado antes, nunca uso, pero bueno que si tienen la info…. ustedes saben, un poco como esta…. (: -)~
Bien, aquí más allá de programas queremos ir fuerza bruta cuando las cosas se ponen difíciles.Hacer un script de rizo. Yup! Cuán simple era… UMM, lamentablemente no es bastante fácil. Tal vez por ahí en los intertubes de todo el mundo tendría mejor suerte que yo, pero… Ah el pero
Resulta que, para mí al menos, que obtener la imagen a través de rizo devuelve el contenido de los archivos. ¿Qué me voy a hacerlo con esto distinto palo en un archivo? Sabes
Si ($ salida = fopen ($local_file, ‘c’))
fwrite ($salida, trim($content));
Nuevamente otra pared. La rodilla ya que soy, profundo en un plugin, me estoy rodeado de un lugar donde la cabecera durante mucho tiempo se ha iniciado.
Detalles técnicos
Permite acercarse al paciente. Ya desde hace tiempo se han lanzado los encabezados, no puedo usar este truco nifty aprendí donde simplemente de crear un encabezado de imagen. Sí saben, encabezado de imagen, archivo de cosas con código funky, guardar el archivo y listo.
header (“Content-Type: image/jpeg”);
header (“Content-Disposition: attachment; filename =’. urlencode($filename));
Escritura poco bien agradable hasta para nada, viendo que otra vez, estoy rodilla en un plugin para que no la pasa. ¿te comento que nosotros aquí en programas más allá de como ir fuerza bruta cuando lo estúpido no funcionará?
¿Recuerde antes que mencioné crear un script de rizo? Bien nos hizo, probados y todas esas cosas que menciona a realmente funciona si no wordpress profundidad en rodilla. Así que para aquellos de ustedes como desesperada como una solución y listo para doblar largo hacia atrás para una solución, tengo algo.
SHHHHhhhhhh
Doblez a la secuencia de comandos de rizo. Sí lo dije. Doblez de rodilla en wordpress a otro lugar del sitio (inicio de sesión protegida por supuesto) y tiene que hacer toda la imagen guardar etc..Boooyaaaa, dije a fuerza bruta y um, permítame añadir, funciona perfectamente.
Enviar lo que quieras de la secuencia de comandos. Lo más importante, enviar el archivo que necesita ir conseguir.
$url =… “? local_file=”.trim($local_file). “& archivo_remoto = “.$ remote_url;
ch $ = curl_init(trim($check_url));
curl_exec($CH);
La secuencia de comandos independiente debe manejar la obtención de todo y guardar el proceso. Su script principal será terminar el adjunto a la Galería de wordpress entonces obtener la url de la columna del registro.
Qué dices
¿File_get_contents dices? Podría recortar la mitad esta basura. ¿Bueno hizo añadir que algunos de los enlaces en la wern’t de csv real? REENVÍA a otro lugar. Además, no creo estaba trabajando incluso sin este problema, intente y me avisas. Finalmente, cuando el código tonto deja de funcionar llegamos a bruta.
Conclusión
Si alguien te pide una imagen de algún otro dominio y subirlo a las suyas, ejecuta. Mal chiste tal vez, pero en mi caso, las imágenes eran parte de un acuerdo de publicidad y anuncios. Una importante red suplía la info y el cliente no quería ir a la ruta de la api.
Si tiene una razón de fiar para obtener imágenes y cargarles a tu servidor/wordpress entonces su posible. Debéis hackear en ello, pero es posible.
Voy a tener que agregar algunos archivos reales a esto en algún punto, viendo que tiene varias líneas para hacer todo esto. Sin embargo, para aquellos que realmente van por esa vía, con el cual es explicado aquí, ya tienes el código. OK, suficiente jedi, al menos unas líneas

……………………………………………………………………………………………………………………

Main File

$remote_url = addslashes(strip_tags($arr[11]));
$raw_file = explode(“/”,$remote_url);
$filename = $uploads[‘path’].”/”.$raw_file[sizeof($raw_file)-1];//get filename
if(http_get_file($remote_url, $filename)){//if succesfully downloaded then attach to gallery

……………………………………………………………………………………………………………………

Curl to curl

function http_get_file($remote_url, $local_file)    {

$check_url = “whatever.php?local_file=”.trim($local_file).”&remote_file=”.$remote_url;

$ch = curl_init(trim($check_url));
curl_exec($ch);
……………………………………………………………………………………………………………………

Standalone

$local_file = $_GET[“local_file”];
$remote_file = $_GET[“remote_file”];
$raw_file = explode(“/”,$remote_file);
$filename = $raw_file[sizeof($raw_file)-1];
header(‘Content-Type: image/jpeg’);
header(‘Content-Disposition: attachment; filename=’ . urlencode($filename));
require(“../../../wp-load.php”);
if (is_admin()) {

Leave a Comment

Sign in

Sign Up

Forgotten Password

Cart

Cart

Share