I have a piece of a PHP code:
<?php
$image_cdn = "http://ddragon.leagueoflegends.com/cdn/4.2.6/img/champion/";
$championsJson = "http://ddragon.leagueoflegends.com/cdn/4.2.6/data/en_GB/champion.json";
$ch = curl_init();`
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $championsJson);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
$json_array = json_decode($json, true);
$champions = $json_array["data"];
foreach ($champions as $championdata) {
$image_url = $image_cdn.$championdata["image"]["full"];
$image = file_get_contents($image_url);
file_put_contents("imgfolder/".$championdata["image"]["full"], $image);
}
?>
So the idea of the code is to basically to decode a JSON and to download the images from the following website:
http://gameinfo.na.leagueoflegends.com/en/game-info/champions/
The pictures download perfectly fine and are stored into a folder I have created on my hard drive. The next step is, is it possible for me to use this same piece of code, to download/display the images onto a website I have recently created:
www.lolguides4you.co.uk
the website is basically a day old and I have literally been messing around with some HTML coding. I am new to both HTML and PHP so if someone could point me into the right direction, that would be great!
Assuming that all you want to do it insert the images into a page on your website, then this is quite simple.
However, it may be illegal for you to use an automated scraping tool to save/replicate/duplicate any of the images. Look into that before doing anything on the internet.
The first step is to upload your previous PHP script to your website. That way, rather than downloading the images to your computer and then trying to upload them to your site it allows you to just save the files straight into a directory on the website.
Next, you can create a basic PHP page anywhere on your site:
<?php
echo "Images downloaded:\n";
?>
Next you can use PHP's scandir() function to find every file in the download directory:
<?php
echo "Images downloaded:\n";
$files = scandir('imgfolder/');
foreach($files as $file) {
// Do something
}
?>
Finally, now you just show each image:
<?php
echo "Images downloaded:\n";
$files = scandir('imgfolder/');
foreach($files as $file) {
echo $file . "\n";
}
?>
You could also use Glob, which allows you to ignore any files which aren't a certain type (in case you have other files in the same directory:
<?php
echo "Images downloaded:\n";
$files = glob("imgfolder/*.jpg");
foreach($files as $file){
echo $file . "\n";
}
?>
Related
This file is runing
my-site.com/includes/classes/build/cg.php
and it loads
my-site.com/data/data.json
with a such structure
$data = json_decode(file_get_contents("http://my-site.com/data/data.json"), true);
I want to load it with relevant path, how to do it?
After trying some combinations, realised this:
$data = json_decode(file_get_contents(__DIR__ ."/../../../data/data.json"), true);
or
$data = json_decode(file_get_contents("././././data/data.json"), true);
When I use to following PHP code;
<?php if (file_exists("/foto/Maurice.jpg"))
{
echo "<center><img src='/foto/Maurice.jpg'/></center>";
}
else {
echo "<center><img src='/afbeeldingen/kaars1.png'/></center>";
?>
My browser always shows kaars1.png
instead of Maurice.jpg
I also tried !file_exists but then it doesn't show kaars1.png, when Maurice.jpg doesn't exist.
Is there a simpel way to fix this?
file_exists is only for files on your server's (local) filesystem. You need to actually try to request the URL and see if it exists or not.
You can use cURL to do this.
$handle = curl_init('https://picathartes.com/foto/Maurice.jpg');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_NOBODY, TRUE);
$response = curl_exec($handle);
// Check for 404 (file not found).
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
echo "<center><img src='https://picathartes.com/afbeeldingen/kaars1.png'/></center>";
}
else{
echo "<center><img src='https://picathartes.com/foto/Maurice.jpg'/></center>";
}
curl_close($handle);
(Code from this question: https://stackoverflow.com/a/408416)
This is an answer to your second question
The correct solution depends upon your actual directory structure and the location of the script file in relation to the actual folder and file you are looking for, but to start finding a solution the / in "/foto/Maurice.jpg" say go back to the root directory and look for a directory called /foto
So if this folder is under your DocumentRoot try using
if (file_exists("foto/Maurice.jpg"))
i have a .php file from a videohoster who says that this code is a comandline code which allows me to upload a video to their site and i need to create an interface for a random user that he can upload a video to the videohoster while staying on my website. i thought i simple form like below in html is enought but apparently it doesent work:
front-end, html:
<h2>This form allows you to upload a Video.</h2>
<form action="uploadapi.php" method="post" enctype="multipart/form-data"><br>
<p>Video Name: <input type="text" name="titel" size="50" /></p>
<p>Video Description:<br/><textarea name="text" rows="5" cols="50"> </textarea></p>
<p>Select File, allowed: .mpg </br><input type="file" name="file"></p>
<p><input type="submit" value="Upload"</p>
</form>
the uploadapi.php is supplied by the hoster and so i assume it is correct.
<?php
////////////////////////////////////////////////////////
// for php 5.6+ you need to make some changes in code
// method 1
// add the following line
// curl_setopt($ch, CURLOPT_SAFE_UPLOAD, 0);
//
// method 2
// change
// $post_fields['vfile'] = "#".$file;
// to
// $post_fields['vfile'] = CURLFile($file);
////////////////////////////////////////////////////////
$apiversion = "2.123.20150426";
//REQUIRED Registered Users - You can find your user token in API page.
$user_token = "xxx";
if(count($argv) < 2)
die("Usage: php $argv[0] [VIDEO TO UPLOAD] {SUB FILE}\n");
$file = $argv[1];
if(!file_exists("$file"))
die("ERROR: Can't find '$file'!\n");
$path_parts = pathinfo($file);
$ext = $path_parts['extension'];
$allowed = array("mov");
if (!in_array(strtolower($ext),$allowed))
die("ERROR: Video format not permitted. Formats allowed: .mov!\n");
if(isset($argv[2]))
{
$sub_file = $argv[2];
if(!file_exists("$sub_file"))
die("ERROR: Can't find '$file'!\n");
$path_parts = pathinfo($sub_file);
$ext = $path_parts['extension'];
$allowed = array("srt");
if (!in_array(strtolower($ext),$allowed))
die("ERROR: Subtitle format not permitted. Formats allowed: .srt!\n");
$post_fields['subfile'] = "#".$sub_file;
}
$converter = file_get_contents("http://.../getconv_uploadapi.php? upload_hash=".$user_token);
if($converter=="ERROR")
die("ERROR: Could not choose converter. Aborting... \n");
$post_fields['vfile'] = CURLFile($file);
$post_fields['upload'] = "1";
$post_fields ['token'] = 'xxx';
if(!empty($user_token))
$post_fields['upload_hash'] = $user_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$converter);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
curl_close ($ch);
echo "$result\n";
?>
is my methodology correct (using html form to call the uploadapi.php on my server) or do i need in order to sumit my video to the videohoster via uploadapi.php other programming languages (ajax, javascript etc)?
Provided file is command-line file. It means it won't work on web as expected.
For example, on web you won't have $argv[1] or $argv[2].
You have two options:
you can rewrite uploadapi.php considering that source file is a file that came from your form
or upload your file and call uploadapi.php as a command-line script with arguments using shell_exec or exec, for example.
i thought that i define or fill the variable $argv[1] from the html form since: type="file" name="file"> = $file = $argv[1];?
... ok rewriting upload api is no alternative since it comes from the hoster.
so what i need to do is uploading the uploadapi.php on my server and then keeping my html form like it is? and insted of action=uploadapi.php i need a action=somethingsomething.php which has an exec command to execute uploadapi.php?:
<?php
function somethingsomething($uploadapi) {
exec($uploadapi . " > /dev/null &");
}
?>
Im trying to pass post file information to an upload.php file and have that information be sent to a CGI script. There is nothing on the net on how to go about doing this that i can find, iv spent days. I know there are a few people out there that need this, it could help us all that have legacy perl scripts.
Dataflow:
Jquery --> Upload.php --> index.cgi
My php:
<?php
if(isset($_FILES['file'])) {
if(move_uploaded_file($_FILES['file']['tmp_name'], "../index.cgi" . $_FILES['file']['name'])){
echo "success";
exit;
}
}
?>
Post call to CGI example:
foobar.com/index.cgi?act=store&data=$filename
Any suggestions would help greatly. Thank you.
From my understanding, your CGI script is receiving a parameter which is the path of the uploaded script. However you are attempting to pass the uploaded script to your CGI script using a function that is only supposed to move a file from 1 place to another without executing a script.
my suggestion is to do the following
<?php
if(isset($_FILES['file'])) {
$destination = "new/path/to/".$_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $destination)){
$data = array();
//You can add multiple post parameters here
//$data = array('param1' => 'value1', 'param2' => 'value2');
$url = "http://url/to/hello.cgi";
// You can POST a file by prefixing with an # (for <input type="file"> fields)
$data['file'] = '#'.$destination;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($handle);
if($result) {
echo "success";
}
exit;
}
}
?>
You can execute the cgi script via a CURL POST and pass any params you want
I was trying out this tutorial for reading rss feeds with a php file and caching it.
I copied and pasted the source into my own project. I am using XAMPP on Mac OS X installation.
Here is the source:
First of all, I cannot create a directory with mkdir. It says permission denied.
Second, $feed = file_get_contents($path, true); is not returning a php object. I mean when i check it with if ( is_object($feed) && $feed->query->count ), I cannot get through.
Last, I cannot $cachefile = fopen($cache, 'wb');
<?php
$cache = dirname(__FILE__) . "/cache/feed";
echo filemtime($cache);
if(filemtime($cache))
{
// Get from server
if ( !file_exists(dirname(__FILE__) . '/cache') ) {
mkdir(dirname(__FILE__) . '/cache', 0777);
}
// YQL query (SELECT * from feed ... ) // Split for readability
$path = "http://query.yahooapis.com/v1/public/yql?q=";
$path .= urlencode("SELECT * FROM feed WHERE url='http://feeds.hindustantimes.com/HT-HomePage-TopStories'");
$path .= "&format=json";
// Call YQL, and if the query didn't fail, cache the returned data
$feed = file_get_contents($path, true);
print_r($feed);
// If something was returned, cache
if ( is_object($feed) && $feed->query->count ) {
$cachefile = fopen($cache, 'wb');
fwrite($cachefile, $feed);
fclose($cachefile);
echo 'writing to disk';
}
}
else
{
// We already have local cache. Use that instead.
$feed = file_get_contents($cache);
}
// Decode that shizzle
$feed = json_decode($feed);
print_r($feed);
// Include the view
//include('views/site.tmpl.php');
?>
Pretty sure XAMPP runs as the "nobody" user so you're going to have to give "nobody" permissions to the directories you want to be writable:
chown nobody:nobody dir_in_question
Keep in mind that XAMPP is a great dev server, but is not secure out of the box so be careful about using this in production. See this article for relevant issues.